all_notifications.html 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. {% extends "layouts/base.html" %}
  2. {% block styles %}
  3. <style>
  4. .notification-fade-in {
  5. animation: fadeIn 0.3s ease-in-out;
  6. }
  7. @keyframes fadeIn {
  8. from { opacity: 0; transform: translateY(-10px); }
  9. to { opacity: 1; transform: translateY(0); }
  10. }
  11. .notification-item {
  12. transition: all 0.2s ease;
  13. }
  14. .notification-read {
  15. opacity: 0.7;
  16. background-color: #f9fafb;
  17. }
  18. .notification-removing {
  19. opacity: 0;
  20. transform: translateX(-100%);
  21. transition: all 0.3s ease;
  22. }
  23. .pagination-btn:disabled {
  24. opacity: 0.5;
  25. cursor: not-allowed;
  26. }
  27. </style>
  28. {% endblock %}
  29. {% block header_actions %}
  30. <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 w-full sm:w-auto">
  31. <!-- Counter -->
  32. <div class="bg-blue-50 px-3 py-1.5 rounded-lg border border-blue-200 flex-shrink-0 text-center">
  33. <span class="text-xs sm:text-sm text-blue-700 font-medium">
  34. <span id="unread-count">{{ unread_count }}</span> {{ _("No leídas") }}
  35. </span>
  36. </div>
  37. <!-- Mark all as read button -->
  38. <button id="mark-all-read" class="bg-green-600 hover:bg-green-700 text-white px-3 sm:px-4 py-2 rounded-lg transition-colors duration-200 flex items-center justify-center gap-2 text-sm flex-1 sm:flex-none">
  39. <i class="fas fa-check-double"></i>
  40. <span class="hidden xs:inline">{{ _("Marcar todas") }}</span>
  41. </button>
  42. <!-- Delete all button -->
  43. <button id="delete-all" class="bg-red-600 hover:bg-red-700 text-white px-3 sm:px-4 py-2 rounded-lg transition-colors duration-200 flex items-center justify-center gap-2 text-sm flex-1 sm:flex-none">
  44. <i class="fas fa-trash"></i>
  45. <span class="hidden xs:inline">{{ _("Eliminar todas") }}</span>
  46. </button>
  47. </div>
  48. {% endblock %}
  49. {% block content %}
  50. <div class="w-full space-y-6">
  51. <!-- Filters -->
  52. <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
  53. <div class="flex flex-wrap gap-4 items-center">
  54. <div class="flex items-center gap-2">
  55. <span class="text-sm font-medium text-gray-700">{{ _("Filtrar por:") }}</span>
  56. <select id="filter-type" class="text-sm border border-gray-300 rounded-lg px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500 min-w-[140px]">
  57. <option value="all">{{ _("Todos los tipos") }}</option>
  58. <option value="error">{{ _("Errores") }}</option>
  59. <option value="warning">{{ _("Advertencias") }}</option>
  60. <option value="success">{{ _("Éxitos") }}</option>
  61. <option value="info">{{ _("Información") }}</option>
  62. </select>
  63. </div>
  64. <div class="flex items-center gap-2">
  65. <select id="filter-source" class="text-sm border border-gray-300 rounded-lg px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500 min-w-[150px]">
  66. <option value="all">{{ _("Todas las fuentes") }}</option>
  67. <option value="squid">{{ _("Squid") }}</option>
  68. <option value="system">{{ _("Sistema") }}</option>
  69. <option value="security">{{ _("Seguridad") }}</option>
  70. <option value="users">{{ _("Usuarios") }}</option>
  71. <option value="git">{{ _("Git") }}</option>
  72. </select>
  73. </div>
  74. <div class="flex items-center gap-2">
  75. <select id="filter-status" class="text-sm border border-gray-300 rounded-lg px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500 min-w-[155px]">
  76. <option value="all">{{ _("Todos los estados") }}</option>
  77. <option value="unread">{{ _("Sin leer") }}</option>
  78. <option value="read">{{ _("Leída") }}</option>
  79. </select>
  80. </div>
  81. <button id="clear-filters" class="text-sm text-gray-600 hover:text-gray-800 flex items-center gap-1">
  82. <i class="fas fa-times"></i>
  83. <span>{{ _("Limpiar filtros") }}</span>
  84. </button>
  85. </div>
  86. </div>
  87. <!-- Pagination information -->
  88. <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
  89. <div class="flex flex-col sm:flex-row justify-between items-center gap-4">
  90. <div class="text-sm text-gray-600">
  91. {{ _("Mostrando") }} <span id="current-range">1-{{ notifications|length }}</span> de
  92. <span id="total-notifications">{{ pagination.total_notifications if pagination else notifications|length }}</span> notificaciones
  93. </div>
  94. <div class="flex items-center gap-2">
  95. <button id="prev-page" class="pagination-btn px-3 py-1 bg-gray-200 rounded hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
  96. {% if not pagination or not pagination.has_prev %}disabled{% endif %}>
  97. <i class="fas fa-chevron-left"></i>
  98. </button>
  99. <span id="page-info" class="px-3 py-1 text-gray-700 text-sm">
  100. {{ _("Página") }} {{ pagination.current_page if pagination else 1 }} de {{ pagination.total_pages if pagination else 1 }}
  101. </span>
  102. <button id="next-page" class="pagination-btn px-3 py-1 bg-gray-200 rounded hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
  103. {% if not pagination or not pagination.has_next %}disabled{% endif %}>
  104. <i class="fas fa-chevron-right"></i>
  105. </button>
  106. </div>
  107. </div>
  108. </div>
  109. <!-- Notifications List -->
  110. <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
  111. {% if notifications %}
  112. <div id="notifications-list">
  113. {% for notification in notifications %}
  114. <div class="notification-item border-b border-gray-100 last:border-b-0 {% if notification.read %}notification-read{% endif %}"
  115. data-id="{{ notification.id }}"
  116. data-type="{{ notification.type }}"
  117. data-source="{{ notification.source }}"
  118. data-read="{{ notification.read|lower }}">
  119. <div class="p-6 flex items-start gap-4">
  120. <!-- Icon -->
  121. <div class="flex-shrink-0">
  122. <div class="w-12 h-12 rounded-full flex items-center justify-center
  123. {% if notification.type == 'error' %}bg-red-100 text-red-600
  124. {% elif notification.type == 'warning' %}bg-yellow-100 text-yellow-600
  125. {% elif notification.type == 'success' %}bg-green-100 text-green-600
  126. {% else %}bg-blue-100 text-blue-600{% endif %}">
  127. <i class="fas {{ notification.icon }} text-lg"></i>
  128. </div>
  129. </div>
  130. <!-- Content -->
  131. <div class="flex-1 min-w-0">
  132. <div class="flex items-start justify-between mb-2">
  133. <div>
  134. <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
  135. {% if notification.type == 'error' %}bg-red-100 text-red-800
  136. {% elif notification.type == 'warning' %}bg-yellow-100 text-yellow-800
  137. {% elif notification.type == 'success' %}bg-green-100 text-green-800
  138. {% else %}bg-blue-100 text-blue-800{% endif %}">
  139. {{ notification.source|upper }}
  140. </span>
  141. <span class="ml-2 text-sm text-gray-500">{{ notification.time }}</span>
  142. </div>
  143. {% if not notification.read %}
  144. <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
  145. {{ _("No leída") }}
  146. </span>
  147. {% endif %}
  148. </div>
  149. <p class="text-gray-900 font-medium mb-1">{{ notification.message }}</p>
  150. <div class="flex items-center gap-4 mt-3 text-sm text-gray-500">
  151. <span class="flex items-center gap-1">
  152. <i class="fas fa-clock"></i>
  153. <span>{{ notification.timestamp|datetime_format }}</span>
  154. </span>
  155. <span class="flex items-center gap-1">
  156. <i class="fas fa-{{ notification.icon }}"></i>
  157. <span class="capitalize">{{ notification.type }}</span>
  158. </span>
  159. </div>
  160. </div>
  161. <!-- Actions -->
  162. <div class="flex-shrink-0 flex items-center gap-2">
  163. {% if not notification.read %}
  164. <button class="mark-read-btn text-green-600 hover:text-green-800 p-2 rounded-lg hover:bg-green-50 transition-colors duration-150"
  165. data-id="{{ notification.id }}"
  166. title="{{ _("Marcar como leída") }}">
  167. <i class="fas fa-check"></i>
  168. </button>
  169. {% endif %}
  170. <button class="delete-btn text-red-600 hover:text-red-800 p-2 rounded-lg hover:bg-red-50 transition-colors duration-150"
  171. data-id="{{ notification.id }}"
  172. title="{{ _("Eliminar notificación") }}">
  173. <i class="fas fa-trash"></i>
  174. </button>
  175. </div>
  176. </div>
  177. </div>
  178. {% endfor %}
  179. </div>
  180. {% else %}
  181. <!-- Empty state -->
  182. <div class="text-center py-16">
  183. <div class="w-24 h-24 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center">
  184. <i class="fas fa-bell-slash text-gray-400 text-3xl"></i>
  185. </div>
  186. <h3 class="text-lg font-medium text-gray-900 mb-2">{{ _("No hay notificaciones") }}</h3>
  187. <p class="text-gray-500 max-w-md mx-auto">{{ _("Todas las notificaciones aparecerán aquí. ¡Mantente atento a las actualizaciones del sistema!") }}</p>
  188. </div>
  189. {% endif %}
  190. </div>
  191. </div>
  192. {% endblock %}
  193. {% block scripts %}
  194. <script>
  195. document.addEventListener('DOMContentLoaded', function() {
  196. const i18n = {
  197. errorLoadNotifications: "{{ _('Error al cargar notificaciones') }}",
  198. noNotifications: "{{ _('No hay notificaciones') }}",
  199. noNotificationsDescription: "{{ _('Todas las notificaciones aparecerán aquí. ¡Mantente atento a las actualizaciones del sistema!') }}",
  200. unreadLabel: "{{ _('No leída') }}",
  201. markAsReadTitle: "{{ _('Marcar como leída') }}",
  202. deleteNotificationTitle: "{{ _('Eliminar notificación') }}",
  203. noNotificationsUnread: "{{ _('No hay notificaciones sin leer') }}",
  204. confirmDeleteNotification: "{{ _('¿Estás seguro de que quieres eliminar esta notificación?') }}",
  205. notificationDeleted: "{{ _('Notificación eliminada') }}",
  206. errorDeleteNotification: "{{ _('Error al eliminar notificación:') }}",
  207. confirmDeleteAll: "{{ _('¿Estás seguro de que quieres eliminar TODAS las notificaciones? Esta acción no se puede deshacer.') }}",
  208. allNotificationsDeleted: "{{ _('Todas las notificaciones han sido eliminadas') }}",
  209. errorDeleteNotifications: "{{ _('Error al eliminar notificaciones:') }}",
  210. filtersCleared: "{{ _('Filtros limpiados') }}",
  211. errorConnectionPrefix: "{{ _('Error de conexión:') }}",
  212. errorUnknown: "{{ _('Error desconocido') }}",
  213. markReadSuccess: "{{ _('{count} notificación(es) marcada(s) como leída(s)') }}",
  214. errorMarkReadNotifications: "{{ _('Error al marcar notificaciones como leídas:') }}",
  215. agoJustNow: "{{ _('Hace unos momentos') }}",
  216. agoMinutesSingular: "{{ _('Hace {count} minuto') }}",
  217. agoMinutesPlural: "{{ _('Hace {count} minutos') }}",
  218. agoHoursSingular: "{{ _('Hace {count} hora') }}",
  219. agoHoursPlural: "{{ _('Hace {count} horas') }}",
  220. agoDaysSingular: "{{ _('Hace {count} día') }}",
  221. agoDaysPlural: "{{ _('Hace {count} días') }}",
  222. systemSource: "{{ _('Sistema') }}",
  223. squidSource: "{{ _('Squid') }}",
  224. gitSource: "{{ _('Git') }}",
  225. securitySource: "{{ _('Seguridad') }}",
  226. usersSource: "{{ _('Usuarios') }}",
  227. errorType: "{{ _('Error') }}",
  228. warningType: "{{ _('Advertencia') }}",
  229. successType: "{{ _('Éxito') }}",
  230. infoType: "{{ _('Información') }}"
  231. };
  232. const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
  233. let currentPage = {{ pagination.current_page if pagination else 1 }};
  234. const totalPages = {{ pagination.total_pages if pagination else 1 }};
  235. const perPage = {{ pagination.per_page if pagination else 20 }};
  236. // Función para mostrar toast usando toastr
  237. function showToast(message, type = 'info') {
  238. if (window.toastr) {
  239. if (type === 'error') {
  240. toastr.error(message);
  241. } else if (type === 'success') {
  242. toastr.success(message);
  243. } else if (type === 'warning') {
  244. toastr.warning(message);
  245. } else {
  246. toastr.info(message);
  247. }
  248. }
  249. }
  250. // Function to load notifications with pagination
  251. function loadNotifications(page = currentPage) {
  252. const url = `/api/notifications?page=${page}&per_page=${perPage}`;
  253. fetch(url)
  254. .then(response => response.json())
  255. .then(data => {
  256. if (data.notifications && data.notifications.length > 0) {
  257. renderNotifications(data.notifications);
  258. updatePagination(data.pagination);
  259. } else {
  260. showEmptyState();
  261. }
  262. })
  263. .catch(error => {
  264. console.error('Error loading notifications:', error);
  265. showToast(i18n.errorLoadNotifications || 'Error loading notifications:', 'error');
  266. });
  267. }
  268. // Function to render notifications
  269. function renderNotifications(notifications) {
  270. const container = document.getElementById('notifications-list');
  271. if (!container) return;
  272. const sourceMap = {
  273. squid: i18n.squidSource || 'Squid',
  274. git: i18n.gitSource || 'Git',
  275. system: i18n.systemSource || 'System',
  276. security: i18n.securitySource || 'Security',
  277. users: i18n.usersSource || 'Users'
  278. };
  279. const typeLabels = {
  280. error: i18n.errorType || 'Error',
  281. warning: i18n.warningType || 'Warning',
  282. success: i18n.successType || 'Success',
  283. info: i18n.infoType || 'Info'
  284. };
  285. container.innerHTML = notifications.map(notification => `
  286. <div class="notification-item border-b border-gray-100 last:border-b-0 ${notification.read ? 'notification-read' : ''}"
  287. data-id="${notification.id}"
  288. data-type="${notification.type}"
  289. data-source="${notification.source}"
  290. data-read="${notification.read}">
  291. <div class="p-6 flex items-start gap-4">
  292. <div class="flex-shrink-0">
  293. <div class="w-12 h-12 rounded-full flex items-center justify-center
  294. ${notification.type === 'error' ? 'bg-red-100 text-red-600' :
  295. notification.type === 'warning' ? 'bg-yellow-100 text-yellow-600' :
  296. notification.type === 'success' ? 'bg-green-100 text-green-600' :
  297. 'bg-blue-100 text-blue-600'}">
  298. <i class="fas ${notification.icon} text-lg"></i>
  299. </div>
  300. </div>
  301. <div class="flex-1 min-w-0">
  302. <div class="flex items-start justify-between mb-2">
  303. <div>
  304. <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
  305. ${notification.type === 'error' ? 'bg-red-100 text-red-800' :
  306. notification.type === 'warning' ? 'bg-yellow-100 text-yellow-800' :
  307. notification.type === 'success' ? 'bg-green-100 text-green-800' :
  308. 'bg-blue-100 text-blue-800'}">
  309. ${(() => {
  310. const sourceMap = {
  311. squid: i18n.squidSource || 'Squid',
  312. git: i18n.gitSource || 'Git',
  313. system: i18n.systemSource || 'Sistema',
  314. security: i18n.securitySource || 'Seguridad',
  315. users: i18n.usersSource || 'Users'
  316. };
  317. return sourceMap[notification.source] || notification.source.toUpperCase();
  318. })()}
  319. </span>
  320. <span class="ml-2 text-sm text-gray-500">${formatTimeAgo(notification.timestamp)}</span>
  321. </div>
  322. ${!notification.read ? `
  323. <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
  324. ${i18n.unreadLabel || 'No leída'}
  325. </span>
  326. ` : ''}
  327. </div>
  328. <p class="text-gray-900 font-medium mb-1">${notification.message}</p>
  329. <div class="flex items-center gap-4 mt-3 text-sm text-gray-500">
  330. <span class="flex items-center gap-1">
  331. <i class="fas fa-clock"></i>
  332. <span>${new Date(notification.timestamp).toLocaleString('es-ES')}</span>
  333. </span>
  334. <span class="flex items-center gap-1">
  335. <i class="fas fa-${notification.icon}"></i>
  336. <span class="capitalize">${typeLabels[notification.type] || notification.type}</span>
  337. </span>
  338. </div>
  339. </div>
  340. <div class="flex-shrink-0 flex items-center gap-2">
  341. ${!notification.read ? `
  342. <button class="mark-read-btn text-green-600 hover:text-green-800 p-2 rounded-lg hover:bg-green-50 transition-colors duration-150"
  343. data-id="${notification.id}"
  344. title="Marcar como leída">
  345. <i class="fas fa-check"></i>
  346. </button>
  347. ` : ''}
  348. <button class="delete-btn text-red-600 hover:text-red-800 p-2 rounded-lg hover:bg-red-50 transition-colors duration-150"
  349. data-id="${notification.id}"
  350. title="${i18n.deleteNotificationTitle}">
  351. <i class="fas fa-trash"></i>
  352. </button>
  353. </div>
  354. </div>
  355. </div>
  356. `).join('');
  357. // Re-aplicar filtros después de cargar
  358. applyFilters();
  359. }
  360. // Función para actualizar la paginación
  361. function updatePagination(pagination) {
  362. currentPage = pagination.current_page;
  363. const totalPages = pagination.total_pages;
  364. const totalNotifications = pagination.total_notifications;
  365. // Actualizar información de paginación
  366. document.getElementById('current-range').textContent =
  367. `${((currentPage - 1) * perPage) + 1}-${Math.min(currentPage * perPage, totalNotifications)}`;
  368. document.getElementById('total-notifications').textContent = totalNotifications;
  369. document.getElementById('page-info').textContent = `Página ${currentPage} de ${totalPages}`;
  370. // Actualizar botones de paginación
  371. document.getElementById('prev-page').disabled = currentPage <= 1;
  372. document.getElementById('next-page').disabled = currentPage >= totalPages;
  373. }
  374. // Función para mostrar estado vacío
  375. function showEmptyState() {
  376. const container = document.getElementById('notifications-list');
  377. if (!container) return;
  378. container.innerHTML = `
  379. <div class="text-center py-16">
  380. <div class="w-24 h-24 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center">
  381. <i class="fas fa-bell-slash text-gray-400 text-3xl"></i>
  382. </div>
  383. <h3 class="text-lg font-medium text-gray-900 mb-2">${i18n.noNotifications || 'No hay notificaciones'}</h3>
  384. <p class="text-gray-500 max-w-md mx-auto">${i18n.noNotificationsDescription || 'Todas las notificaciones aparecerán aquí. ¡Mantente atento a las actualizaciones del sistema!'}</p>
  385. </div>
  386. `;
  387. }
  388. // Función para formatear "hace X tiempo"
  389. function formatTimeAgo(timestamp) {
  390. const now = new Date();
  391. const notificationTime = new Date(timestamp);
  392. const diffMs = now - notificationTime;
  393. const diffMins = Math.floor(diffMs / 60000);
  394. const diffHours = Math.floor(diffMs / 3600000);
  395. const diffDays = Math.floor(diffMs / 86400000);
  396. if (diffMins < 1) return i18n.agoJustNow || 'Hace unos momentos';
  397. if (diffMins < 60) return (diffMins === 1 ? i18n.agoMinutesSingular : i18n.agoMinutesPlural)
  398. .replace('{count}', diffMins);
  399. if (diffHours < 24) return (diffHours === 1 ? i18n.agoHoursSingular : i18n.agoHoursPlural)
  400. .replace('{count}', diffHours);
  401. return (diffDays === 1 ? i18n.agoDaysSingular : i18n.agoDaysPlural)
  402. .replace('{count}', diffDays);
  403. }
  404. // Function to mark notification as read
  405. function markAsRead(notificationIds) {
  406. fetch('/api/notifications/mark-read', {
  407. method: 'POST',
  408. headers: {
  409. 'Content-Type': 'application/json',
  410. 'X-CSRFToken': csrfToken,
  411. },
  412. body: JSON.stringify({
  413. notification_ids: notificationIds // Cambiado de 'ids' a 'notification_ids'
  414. })
  415. })
  416. .then(response => {
  417. if (!response.ok) {
  418. throw new Error(`Error HTTP: ${response.status}`);
  419. }
  420. return response.json();
  421. })
  422. .then(data => {
  423. if (data.success || data.status === 'success') {
  424. // Actualizar contador en el header
  425. document.getElementById('unread-count').textContent = data.unread_count;
  426. // Reload notifications to reflect changes
  427. loadNotifications(currentPage);
  428. showToast(i18n.markReadSuccess.replace('{count}', notificationIds.length), 'success');
  429. } else {
  430. showToast(`${i18n.errorMarkReadNotifications || 'Error al marcar notificaciones como leídas:'} ${data.error || i18n.errorUnknown || 'Error desconocido'}`, 'error');
  431. }
  432. })
  433. .catch(error => {
  434. console.error('Error:', error);
  435. showToast(`${i18n.errorConnectionPrefix || 'Error de conexión:'} ${error.message}`, 'error');
  436. });
  437. }
  438. // Función para marcar TODAS las notificaciones como leídas
  439. function markAllAsRead() {
  440. const unreadNotifications = document.querySelectorAll('.notification-item[data-read="false"]');
  441. const unreadIds = Array.from(unreadNotifications).map(el => parseInt(el.getAttribute('data-id')));
  442. if (unreadIds.length > 0) {
  443. markAsRead(unreadIds);
  444. } else {
  445. showToast(i18n.noNotificationsUnread, 'info');
  446. }
  447. }
  448. // Función para ELIMINAR notificación
  449. function deleteNotification(notificationId) {
  450. if (!confirm(i18n.confirmDeleteNotification)) {
  451. return;
  452. }
  453. fetch(`/api/notifications/${notificationId}`, {
  454. method: 'DELETE',
  455. headers: {
  456. 'X-CSRFToken': csrfToken,
  457. }
  458. })
  459. .then(response => {
  460. if (!response.ok) {
  461. throw new Error(`Error HTTP: ${response.status}`);
  462. }
  463. return response.json();
  464. })
  465. .then(data => {
  466. if (data.success || data.status === 'success') {
  467. // Recargar notificaciones
  468. loadNotifications(currentPage);
  469. // Actualizar contador
  470. document.getElementById('unread-count').textContent = data.unread_count;
  471. showToast(i18n.notificationDeleted, 'success');
  472. } else {
  473. showToast(`${i18n.errorDeleteNotification || 'Error al eliminar notificación:'} ${data.error || i18n.errorUnknown || 'Error desconocido'}`, 'error');
  474. }
  475. })
  476. .catch(error => {
  477. console.error('Error:', error);
  478. showToast(`${i18n.errorConnectionPrefix || 'Error de conexión:'} ${error.message}`, 'error');
  479. });
  480. }
  481. // Función para ELIMINAR TODAS las notificaciones
  482. function deleteAllNotifications() {
  483. if (!confirm(i18n.confirmDeleteAll)) {
  484. return;
  485. }
  486. fetch('/api/notifications/delete-all', {
  487. method: 'DELETE',
  488. headers: {
  489. 'X-CSRFToken': csrfToken,
  490. }
  491. })
  492. .then(response => {
  493. if (!response.ok) {
  494. throw new Error(`Error HTTP: ${response.status}`);
  495. }
  496. return response.json();
  497. })
  498. .then(data => {
  499. if (data.success || data.status === 'success') {
  500. // Mostrar estado vacío
  501. showEmptyState();
  502. // Actualizar contador
  503. document.getElementById('unread-count').textContent = '0';
  504. // Actualizar paginación
  505. document.getElementById('current-range').textContent = '0-0';
  506. document.getElementById('total-notifications').textContent = '0';
  507. document.getElementById('page-info').textContent = 'Página 1 de 1';
  508. // Deshabilitar botones de paginación
  509. document.getElementById('prev-page').disabled = true;
  510. document.getElementById('next-page').disabled = true;
  511. showToast(i18n.allNotificationsDeleted, 'success');
  512. } else {
  513. showToast(`${i18n.errorDeleteNotifications || 'Error al eliminar notificaciones:'} ${data.error || i18n.errorUnknown || 'Error desconocido'}`, 'error');
  514. }
  515. })
  516. .catch(error => {
  517. console.error('Error:', error);
  518. showToast(`${i18n.errorConnectionPrefix || 'Error de conexión:'} ${error.message}`, 'error');
  519. });
  520. }
  521. // Filtros
  522. function applyFilters() {
  523. const typeFilter = document.getElementById('filter-type').value;
  524. const sourceFilter = document.getElementById('filter-source').value;
  525. const statusFilter = document.getElementById('filter-status').value;
  526. const notifications = document.querySelectorAll('.notification-item');
  527. let visibleCount = 0;
  528. notifications.forEach(notification => {
  529. const type = notification.getAttribute('data-type');
  530. const source = notification.getAttribute('data-source');
  531. const read = notification.getAttribute('data-read') === 'true';
  532. const typeMatch = typeFilter === 'all' || type === typeFilter;
  533. const sourceMatch = sourceFilter === 'all' || source === sourceFilter;
  534. const statusMatch = statusFilter === 'all' ||
  535. (statusFilter === 'unread' && !read) ||
  536. (statusFilter === 'read' && read);
  537. if (typeMatch && sourceMatch && statusMatch) {
  538. notification.style.display = 'block';
  539. visibleCount++;
  540. } else {
  541. notification.style.display = 'none';
  542. }
  543. });
  544. if (visibleCount === 0 && notifications.length > 0) {
  545. // No mostrar toast aquí para evitar spam al aplicar filtros
  546. }
  547. }
  548. // Event Listeners
  549. document.addEventListener('click', function(e) {
  550. if (e.target.closest('.mark-read-btn')) {
  551. const button = e.target.closest('.mark-read-btn');
  552. const notificationId = parseInt(button.getAttribute('data-id'));
  553. markAsRead([notificationId]);
  554. }
  555. if (e.target.closest('.delete-btn')) {
  556. const button = e.target.closest('.delete-btn');
  557. const notificationId = parseInt(button.getAttribute('data-id'));
  558. deleteNotification(notificationId);
  559. }
  560. });
  561. document.getElementById('mark-all-read').addEventListener('click', markAllAsRead);
  562. document.getElementById('delete-all').addEventListener('click', deleteAllNotifications);
  563. // Paginación
  564. document.getElementById('prev-page').addEventListener('click', function() {
  565. if (currentPage > 1) {
  566. currentPage--;
  567. loadNotifications(currentPage);
  568. }
  569. });
  570. document.getElementById('next-page').addEventListener('click', function() {
  571. if (currentPage < totalPages) {
  572. currentPage++;
  573. loadNotifications(currentPage);
  574. }
  575. });
  576. // Filtros
  577. document.getElementById('filter-type').addEventListener('change', applyFilters);
  578. document.getElementById('filter-source').addEventListener('change', applyFilters);
  579. document.getElementById('filter-status').addEventListener('change', applyFilters);
  580. document.getElementById('clear-filters').addEventListener('click', function() {
  581. document.getElementById('filter-type').value = 'all';
  582. document.getElementById('filter-source').value = 'all';
  583. document.getElementById('filter-status').value = 'all';
  584. applyFilters();
  585. showToast(i18n.filtersCleared, 'info');
  586. });
  587. });
  588. </script>
  589. {% endblock %}