navbar.html 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. <nav class="top-0 z-[1000] fixed w-full bg-gradient-to-br from-blue-800 to-blue-900 shadow-lg border-b border-white/10 backdrop-blur-md transition-transform duration-300" x-data="{ mobileMenuOpen: false }">
  2. <!-- UNIFIED CONTAINER WITH THE REST -->
  3. <div class="w-full px-4 sm:px-6 lg:px-8">
  4. <div class="max-w-7xl mx-auto flex items-center justify-between py-4 h-[64px]">
  5. <!-- Brand/Logo Section -->
  6. <div class="flex items-center gap-3 font-bold text-xl text-white no-underline">
  7. <spam class="font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-white to-blue-300">SquidStats</spam>
  8. </div>
  9. <!-- Container for mobile icons (notifications + hamburger) -->
  10. <div class="lg:hidden flex items-center gap-3">
  11. <!-- Mobile Notifications Button -->
  12. <div class="relative" x-data="{ open: false }">
  13. <button @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Notificaciones">
  14. <i class="fas fa-bell"></i>
  15. <span class="notification-badge absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 bg-gradient-to-r from-red-500 to-red-600 text-white text-xs font-semibold rounded-full border-2 border-white shadow-lg hidden">0</span>
  16. </button>
  17. <!-- Mobile notifications dropdown -->
  18. <div x-show="open"
  19. @click.away="open = false"
  20. @keydown.escape.window="open = false"
  21. x-transition:enter="transition ease-out duration-200"
  22. x-transition:enter-start="opacity-0 scale-95"
  23. x-transition:enter-end="opacity-100 scale-100"
  24. x-transition:leave="transition ease-in duration-150"
  25. x-transition:leave-start="opacity-100 scale-100"
  26. x-transition:leave-end="opacity-0 scale-95"
  27. class="origin-top-right absolute right-0 mt-2 w-80 rounded-lg shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50"
  28. style="display: none">
  29. <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
  30. <span class="font-semibold text-gray-800">Notificaciones</span>
  31. <button @click="open = false" class="text-gray-400 hover:text-gray-600 focus:outline-none">
  32. <i class="fas fa-times"></i>
  33. </button>
  34. </div>
  35. <ul class="max-h-72 overflow-y-auto divide-y divide-gray-100 notifications-mobile">
  36. <li class="px-4 py-3 text-gray-500 text-center">
  37. Cargando notificaciones...
  38. </li>
  39. </ul>
  40. <div class="py-2 px-4 text-center border-t border-gray-200">
  41. <a href="/all-notifications" class="text-sm text-blue-600 hover:underline">Ver todas las notificaciones</a>
  42. </div>
  43. </div>
  44. </div>
  45. <!-- Hamburger Button for Mobile -->
  46. <button @click="mobileMenuOpen = !mobileMenuOpen" class="flex flex-col w-8 h-8 justify-center items-center gap-1.5 text-white focus:outline-none z-[1001]" aria-label="Toggle menu">
  47. <span class="w-6 h-0.5 bg-white transition-all" :class="{'rotate-45 translate-y-2': mobileMenuOpen}"></span>
  48. <span class="w-6 h-0.5 bg-white transition-all" :class="{'opacity-0': mobileMenuOpen}"></span>
  49. <span class="w-6 h-0.5 bg-white transition-all" :class="{'-rotate-45 -translate-y-2': mobileMenuOpen}"></span>
  50. </button>
  51. </div>
  52. <!-- Navigation Links - Desktop -->
  53. <div class="hidden lg:flex items-center gap-2">
  54. <a href="/" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Panel principal con conexiones activas">
  55. <i class="fas fa-home text-base"></i>
  56. <span class="font-medium">Inicio</span>
  57. </a>
  58. <a href="/stats" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Estadísticas de rendimiento del cache">
  59. <i class="fas fa-chart-bar text-base"></i>
  60. <span class="font-medium">Estadísticas</span>
  61. </a>
  62. <a href="/logs" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Actividad y logs de usuarios">
  63. <i class="fas fa-user-friends text-base"></i>
  64. <span class="font-medium">Usuarios</span>
  65. </a>
  66. <a href="/reports" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Reportes y gráficas avanzadas">
  67. <i class="fas fa-chart-simple text-base"></i>
  68. <span class="font-medium">Reportes</span>
  69. </a>
  70. <a href="/blacklist" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Sitios bloqueados y actividad restringida">
  71. <i class="fas fa-ban text-base"></i>
  72. <span class="font-medium">Blacklist</span>
  73. </a>
  74. <a href="/auditoria" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Auditoría de actividad por usuario y fecha">
  75. <i class="fas fa-magnifying-glass text-base"></i>
  76. <span class="font-medium">Auditoría</span>
  77. </a>
  78. </div>
  79. <!-- Desktop Notifications -->
  80. <div class="hidden lg:flex items-center gap-3">
  81. <div class="relative" x-data="{ open: false }">
  82. <!-- Desktop Notifications Button -->
  83. <button @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Notificaciones">
  84. <i class="fas fa-bell"></i>
  85. <span class="notification-badge absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 bg-gradient-to-r from-red-500 to-red-600 text-white text-xs font-semibold rounded-full border-2 border-white shadow-lg hidden">0</span>
  86. </button>
  87. <!-- Desktop notifications dropdown -->
  88. <div x-show="open"
  89. @click.away="open = false"
  90. @keydown.escape.window="open = false"
  91. x-transition:enter="transition ease-out duration-200"
  92. x-transition:enter-start="opacity-0 scale-95"
  93. x-transition:enter-end="opacity-100 scale-100"
  94. x-transition:leave="transition ease-in duration-150"
  95. x-transition:leave-start="opacity-100 scale-100"
  96. x-transition:leave-end="opacity-0 scale-95"
  97. class="origin-top-right absolute right-0 mt-2 w-80 rounded-lg shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50"
  98. style="display: none">
  99. <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
  100. <span class="font-semibold text-gray-800">Notificaciones</span>
  101. <button @click="open = false" class="text-gray-400 hover:text-gray-600 focus:outline-none">
  102. <i class="fas fa-times"></i>
  103. </button>
  104. </div>
  105. <ul class="max-h-72 overflow-y-auto divide-y divide-gray-100 notifications">
  106. <li class="px-4 py-3 text-gray-500 text-center">
  107. Cargando notificaciones...
  108. </li>
  109. </ul>
  110. <div class="py-2 px-4 text-center border-t border-gray-200">
  111. <a href="/all-notifications" class="text-sm text-blue-600 hover:underline">Ver todas las notificaciones</a>
  112. </div>
  113. </div>
  114. </div>
  115. <!-- Action Buttons - Desktop -->
  116. <div class="flex items-center gap-3">
  117. {% if session.user and session.user.role == "admin" %}
  118. <a href="/admin" class="action-btn flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm bg-gradient-to-r from-blue-600 to-blue-500 text-white shadow hover:from-blue-700 hover:to-blue-600 hover:-translate-y-0.5 transition-all duration-300" data-tooltip="Panel de administración del sistema">
  119. <i class="fas fa-cog"></i>
  120. <span>Admin</span>
  121. </a>
  122. {% endif %}
  123. <button onclick="confirmSquidUpdate()" class="action-btn flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm bg-gradient-to-r from-emerald-600 to-emerald-400 text-white shadow hover:from-emerald-700 hover:to-emerald-600 hover:-translate-y-0.5 transition-all duration-300" data-tooltip="Actualizar paquetes y configuración de Squid">
  124. <i class="fas fa-sync-alt"></i>
  125. <span>Squid</span>
  126. </button>
  127. <button onclick="confirmWebUpdate()" class="action-btn flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm bg-gradient-to-r from-purple-600 to-purple-400 text-white shadow hover:from-purple-700 hover:to-purple-600 hover:-translate-y-0.5 transition-all duration-300" data-tooltip="Actualizar aplicación web SquidStats">
  128. <i class="fas fa-cloud-download-alt"></i>
  129. <span>Web</span>
  130. </button>
  131. </div>
  132. </div>
  133. </div>
  134. </div>
  135. <!-- Mobile Menu Overlay -->
  136. <div x-show="mobileMenuOpen" @click="mobileMenuOpen = false" class="fixed inset-0 bg-black bg-opacity-50 z-[999] lg:hidden" style="display: none;">
  137. </div>
  138. <!-- Mobile Menu Content -->
  139. <div x-show="mobileMenuOpen"
  140. x-transition:enter="transition ease-out duration-300"
  141. x-transition:enter-start="opacity-0 transform -translate-y-4"
  142. x-transition:enter-end="opacity-100 transform translate-y-0"
  143. x-transition:leave="transition ease-in duration-200"
  144. x-transition:leave-start="opacity-100 transform translate-y-0"
  145. x-transition:leave-end="opacity-0 transform -translate-y-4"
  146. class="absolute top-full left-0 right-0 bg-gradient-to-b from-blue-800 to-blue-900 shadow-2xl z-[1000] lg:hidden overflow-y-auto border-t border-white/10"
  147. style="display: none;">
  148. <div class="p-6">
  149. <!-- Mobile Navigation Links -->
  150. <div class="flex flex-col gap-2 mb-8">
  151. <a href="/" @click="mobileMenuOpen = false" class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
  152. <i class="fas fa-home text-lg"></i>
  153. <span>Inicio</span>
  154. </a>
  155. <a
  156. href="/stats" @click="mobileMenuOpen = false"
  157. class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
  158. <i class="fas fa-chart-bar text-lg"></i>
  159. <span>Estadísticas</span>
  160. </a>
  161. <a href="/logs" @click="mobileMenuOpen = false" class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
  162. <i class="fas fa-user-friends text-lg"></i>
  163. <span>Usuarios</span>
  164. </a>
  165. <a href="/reports" @click="mobileMenuOpen = false" class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
  166. <i class="fas fa-chart-simple text-lg"></i>
  167. <span>Reportes</span>
  168. </a>
  169. <a href="/blacklist" @click="mobileMenuOpen = false" class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
  170. <i class="fas fa-ban text-lg"></i>
  171. <span>Blacklist</span>
  172. </a>
  173. <a href="/auditoria" @click="mobileMenuOpen = false" class="flex items-center gap-3 px-4 py-3 text-gray-200 rounded-lg font-medium text-base transition-all duration-300 hover:text-white hover:bg-white/10">
  174. <i class="fas fa-magnifying-glass text-lg"></i>
  175. <span>Auditoría</span>
  176. </a>
  177. </div>
  178. <!-- Botones Squid y Web en fila -->
  179. <div class="flex flex-row gap-3 mb-8">
  180. <div class="flex flex-1 gap-2">
  181. <button onclick="confirmSquidUpdate(); mobileMenuOpen = false" class="flex-1 flex items-center justify-center gap-2 px-3 py-3 rounded-lg font-semibold text-sm bg-gradient-to-r from-emerald-600 to-emerald-400 text-white shadow hover:from-emerald-700 hover:to-emerald-600 transition-all duration-300">
  182. <i class="fas fa-sync-alt"></i>
  183. <span>Squid</span>
  184. </button>
  185. <button onclick="confirmWebUpdate(); mobileMenuOpen = false" class="flex-1 flex items-center justify-center gap-2 px-3 py-3 rounded-lg font-semibold text-sm bg-gradient-to-r from-purple-600 to-purple-400 text-white shadow hover:from-purple-700 hover:to-purple-600 transition-all duration-300">
  186. <i class="fas fa-cloud-download-alt"></i>
  187. <span>Web</span>
  188. </button>
  189. </div>
  190. </div>
  191. </div>
  192. </div>
  193. </div>
  194. </nav>
  195. <!-- Custom Confirm Modal -->
  196. {% include 'components/confirm_modal.html' %}
  197. <!-- Scripts -->
  198. <script src="{{ url_for('static', filename='src/tailwind.min.js') }}"></script>
  199. <script defer src="{{ url_for('static', filename='src/alpine.min.js') }}"></script>
  200. <script src="{{ url_for('static', filename='js/confirm_modal.js') }}"></script>
  201. <script>
  202. // Enhanced Navbar Functionality with Real-time Notifications
  203. document.addEventListener("DOMContentLoaded", function () {
  204. // Tooltip functionality
  205. function initTooltips() {
  206. const elements = document.querySelectorAll('[data-tooltip]');
  207. elements.forEach(element => {
  208. const tooltipText = element.getAttribute('data-tooltip');
  209. const tooltip = document.createElement('div');
  210. tooltip.className = 'absolute invisible bg-gray-900 text-white text-xs rounded py-1 px-2 top-full left-1/2 transform -translate-x-1/2 mt-2 whitespace-nowrap z-50 opacity-0 transition-opacity duration-200';
  211. tooltip.textContent = tooltipText;
  212. element.appendChild(tooltip);
  213. element.addEventListener('mouseenter', function() {
  214. tooltip.classList.remove('invisible', 'opacity-0');
  215. tooltip.classList.add('visible', 'opacity-100');
  216. });
  217. element.addEventListener('mouseleave', function() {
  218. tooltip.classList.remove('visible', 'opacity-100');
  219. tooltip.classList.add('invisible', 'opacity-0');
  220. });
  221. });
  222. }
  223. // Navbar scroll effect
  224. function initNavbarScroll() {
  225. const navbar = document.querySelector('nav');
  226. let lastScrollY = window.scrollY;
  227. window.addEventListener('scroll', () => {
  228. if (window.scrollY > lastScrollY && window.scrollY > 100) {
  229. navbar.style.transform = 'translateY(-100%)';
  230. } else {
  231. navbar.style.transform = 'translateY(0)';
  232. }
  233. lastScrollY = window.scrollY;
  234. });
  235. }
  236. // Active link highlighting
  237. function setActiveLink() {
  238. const currentPath = window.location.pathname;
  239. const links = document.querySelectorAll('nav a[href]');
  240. links.forEach(link => {
  241. if (link.getAttribute('href') === currentPath) {
  242. link.classList.add('text-white', 'bg-white/20');
  243. link.classList.remove('text-gray-200', 'hover:bg-white/10');
  244. }
  245. });
  246. }
  247. // Función para obtener el token CSRF de forma segura
  248. function getCSRFToken() {
  249. const metaTag = document.querySelector('meta[name="csrf-token"]');
  250. if (metaTag) {
  251. return metaTag.getAttribute('content');
  252. }
  253. console.warn('CSRF token meta tag no encontrado');
  254. return '';
  255. }
  256. // Enhanced Notifications System with WebSocket
  257. function initNotifications() {
  258. let notificationSocket = null;
  259. let notificationsData = {
  260. unread_count: 0,
  261. notifications: []
  262. };
  263. // Conectar WebSocket
  264. function connectWebSocket() {
  265. // Flask-SocketIO se conecta automáticamente al host actual
  266. notificationSocket = io();
  267. notificationSocket.on('connect', function() {
  268. console.log('Conectado al servidor de notificaciones Squid');
  269. });
  270. notificationSocket.on('new_notification', function(data) {
  271. addNewNotification(data.notification);
  272. updateNotificationBadges(data.unread_count);
  273. showNotificationToast(data.notification);
  274. });
  275. notificationSocket.on('notification_updated', function(data) {
  276. updateExistingNotification(data.notification);
  277. updateNotificationBadges(data.unread_count);
  278. showNotificationToast(data.notification);
  279. });
  280. notificationSocket.on('disconnect', function() {
  281. // Reconectar después de 5 segundos
  282. setTimeout(connectWebSocket, 5000);
  283. });
  284. }
  285. function addNewNotification(notification) {
  286. // Evitar duplicados por ID
  287. const existingIndex = notificationsData.notifications.findIndex(n => n.id === notification.id);
  288. if (existingIndex === -1) {
  289. notificationsData.notifications.unshift(notification);
  290. if (!notification.read) {
  291. notificationsData.unread_count++;
  292. }
  293. // Actualizar ambas listas (desktop y móvil)
  294. updateNotificationLists();
  295. updateNotificationBadges(notificationsData.unread_count);
  296. }
  297. }
  298. function updateExistingNotification(notification) {
  299. // Buscar y actualizar la notificación existente
  300. const existingIndex = notificationsData.notifications.findIndex(n => n.id === notification.id);
  301. if (existingIndex !== -1) {
  302. // Actualizar la notificación existente
  303. notificationsData.notifications[existingIndex] = notification;
  304. // Moverla al principio de la lista
  305. const updated = notificationsData.notifications.splice(existingIndex, 1)[0];
  306. notificationsData.notifications.unshift(updated);
  307. } else {
  308. // Si no existe, agregarla como nueva
  309. notificationsData.notifications.unshift(notification);
  310. }
  311. // Actualizar ambas listas (desktop y móvil)
  312. updateNotificationLists();
  313. }
  314. function showNotificationToast(notification) {
  315. if (!window.toastr) return;
  316. // Construir el título con la fuente
  317. const source = notification.source === 'squid' ? 'Squid' :
  318. notification.source === 'git' ? 'Git' : 'Sistema';
  319. const title = notification.count && notification.count > 1 ?
  320. `${source} (×${notification.count})` : source;
  321. // Mostrar notificación según el tipo
  322. if (notification.type === 'error') {
  323. toastr.error(notification.message, title);
  324. } else if (notification.type === 'warning') {
  325. toastr.warning(notification.message, title);
  326. } else if (notification.type === 'success') {
  327. toastr.success(notification.message, title);
  328. } else {
  329. toastr.info(notification.message, title);
  330. }
  331. }
  332. function updateNotificationLists() {
  333. const desktopUl = document.querySelector(".notifications");
  334. const mobileUl = document.querySelector(".notifications-mobile");
  335. const renderNotificationList = (ul, notifications) => {
  336. if (!ul) return;
  337. ul.innerHTML = "";
  338. // Usar el estado local actual - SOLO notificaciones no leídas
  339. const unreadNotifications = notificationsData.notifications.filter(n => !n.read);
  340. const notificationsToShow = unreadNotifications.slice(0, 10);
  341. if (notificationsToShow.length > 0) {
  342. notificationsToShow.forEach((notification) => {
  343. let bgColor, textColor;
  344. switch(notification.type) {
  345. case 'success':
  346. bgColor = 'bg-green-100';
  347. textColor = 'text-green-600';
  348. break;
  349. case 'warning':
  350. bgColor = 'bg-yellow-100';
  351. textColor = 'text-yellow-600';
  352. break;
  353. case 'error':
  354. bgColor = 'bg-red-100';
  355. textColor = 'text-red-600';
  356. break;
  357. case 'info':
  358. default:
  359. bgColor = 'bg-blue-100';
  360. textColor = 'text-blue-600';
  361. }
  362. // Create list item safely
  363. const li = document.createElement('li');
  364. li.className = `px-4 py-3 flex items-start hover:bg-gray-50 cursor-pointer notification-item ${
  365. notification.read ? 'opacity-60' : ''
  366. }`;
  367. li.dataset.id = notification.id;
  368. const iconSpan = document.createElement('span');
  369. iconSpan.className = `inline-flex items-center justify-center h-8 w-8 rounded-full ${bgColor} ${textColor} mr-3`;
  370. const icon = document.createElement('i');
  371. icon.className = `fas ${notification.icon}`;
  372. iconSpan.appendChild(icon);
  373. const contentDiv = document.createElement('div');
  374. contentDiv.className = 'flex-1';
  375. const sourceP = document.createElement('p');
  376. sourceP.className = 'text-sm font-medium text-gray-900';
  377. sourceP.textContent = notification.source === 'squid' ? 'Squid' :
  378. notification.source === 'git' ? 'Git' : 'Sistema';
  379. const messageP = document.createElement('p');
  380. messageP.className = 'text-sm text-gray-700 mt-1';
  381. messageP.textContent = notification.message;
  382. const timeSpan = document.createElement('span');
  383. timeSpan.className = 'text-xs text-gray-400 mt-1';
  384. timeSpan.textContent = notification.time;
  385. contentDiv.appendChild(sourceP);
  386. contentDiv.appendChild(messageP);
  387. contentDiv.appendChild(timeSpan);
  388. li.appendChild(iconSpan);
  389. li.appendChild(contentDiv);
  390. if (!notification.read) {
  391. const badge = document.createElement('span');
  392. badge.className = 'w-2 h-2 bg-blue-500 rounded-full mt-2 flex-shrink-0';
  393. li.appendChild(badge);
  394. }
  395. ul.appendChild(li);
  396. });
  397. } else {
  398. ul.innerHTML = `
  399. <li class='px-4 py-3 text-gray-500 text-center'>
  400. No hay notificaciones nuevas
  401. </li>
  402. `;
  403. }
  404. };
  405. renderNotificationList(desktopUl, notificationsData.notifications);
  406. renderNotificationList(mobileUl, notificationsData.notifications);
  407. }
  408. function updateNotificationBadges(count) {
  409. const badges = document.querySelectorAll('.notification-badge');
  410. badges.forEach(badge => {
  411. if (count > 0) {
  412. badge.textContent = count > 99 ? '99+' : count.toString();
  413. badge.classList.remove('hidden');
  414. } else {
  415. badge.classList.add('hidden');
  416. }
  417. });
  418. }
  419. function markAsRead(notificationIds) {
  420. const csrfToken = getCSRFToken();
  421. fetch('/api/notifications/mark-read', {
  422. method: 'POST',
  423. headers: {
  424. 'Content-Type': 'application/json',
  425. 'X-CSRF-Token': csrfToken,
  426. },
  427. body: JSON.stringify({
  428. ids: notificationIds
  429. })
  430. })
  431. .then(response => {
  432. if (!response.ok) {
  433. throw new Error(`Error HTTP: ${response.status}`);
  434. }
  435. return response.json();
  436. })
  437. .then(data => {
  438. if (data.success) {
  439. // CORRECCIÓN: Filtrar notificaciones marcadas del estado local
  440. notificationsData.notifications = notificationsData.notifications.filter(
  441. notification => !notificationIds.includes(notification.id)
  442. );
  443. notificationsData.unread_count = data.unread_count;
  444. updateNotificationBadges(data.unread_count);
  445. updateNotificationLists();
  446. } else {
  447. console.error('Error del servidor al marcar como leída:', data.error);
  448. showNotificationToast({
  449. type: 'error',
  450. message: 'Error al marcar notificación como leída: ' + (data.error || 'Error desconocido')
  451. });
  452. }
  453. })
  454. .catch(error => {
  455. showNotificationToast({
  456. type: 'error',
  457. message: 'Error al marcar notificación como leída: ' + error.message
  458. });
  459. });
  460. }
  461. function fetchInitialNotifications() {
  462. fetch("/api/notifications")
  463. .then((res) => {
  464. if (!res.ok) {
  465. throw new Error(`Error HTTP: ${res.status}`);
  466. }
  467. return res.json();
  468. })
  469. .then((data) => {
  470. // REEMPLAZAR completamente el estado local
  471. notificationsData.notifications = data.notifications || [];
  472. notificationsData.unread_count = data.unread_count || 0;
  473. updateNotificationLists();
  474. updateNotificationBadges(data.unread_count);
  475. })
  476. .catch((error) => {
  477. console.error('Error fetching notifications:', error);
  478. notificationsData.notifications = [];
  479. notificationsData.unread_count = 0;
  480. updateNotificationLists();
  481. updateNotificationBadges(0);
  482. });
  483. }
  484. // Event listeners para marcar como leído
  485. document.addEventListener('click', function(e) {
  486. const notificationItem = e.target.closest('.notification-item');
  487. if (notificationItem) {
  488. const notificationId = parseInt(notificationItem.dataset.id);
  489. markAsRead([notificationId]);
  490. }
  491. });
  492. // Inicializar
  493. fetchInitialNotifications();
  494. connectWebSocket();
  495. }
  496. // Initialize all functionality
  497. initTooltips();
  498. initNavbarScroll();
  499. setActiveLink();
  500. initNotifications();
  501. });
  502. // Close modals when clicking outside
  503. document.addEventListener("click", function (e) {
  504. if (e.target.classList.contains("modal-overlay")) {
  505. const modals = document.querySelectorAll("[x-show]");
  506. modals.forEach((modal) => {
  507. const alpineData = Alpine.$data(modal);
  508. if (alpineData) {
  509. alpineData.showSquidModal = false;
  510. alpineData.showWebModal = false;
  511. }
  512. });
  513. }
  514. });
  515. // Add escape key handling for modals
  516. document.addEventListener("keydown", function (e) {
  517. if (e.key === "Escape") {
  518. const modals = document.querySelectorAll("[x-show]");
  519. modals.forEach((modal) => {
  520. const alpineData = Alpine.$data(modal);
  521. if (alpineData) {
  522. alpineData.showSquidModal = false;
  523. alpineData.showWebModal = false;
  524. }
  525. });
  526. }
  527. });
  528. // Mobile menu close on outside click
  529. document.addEventListener('click', function(event) {
  530. const mobileMenu = document.querySelector('[x-data]');
  531. const hamburger = document.querySelector('.lg\\:hidden');
  532. const mobileMenuContent = document.querySelector('.absolute.top-full');
  533. if (mobileMenuContent && mobileMenuContent.style.display !== 'none') {
  534. const isClickInside = hamburger.contains(event.target) || mobileMenuContent.contains(event.target);
  535. if (!isClickInside) {
  536. const alpineData = Alpine.$data(mobileMenu);
  537. if (alpineData) {
  538. alpineData.mobileMenuOpen = false;
  539. }
  540. }
  541. }
  542. });
  543. // Función para obtener el token CSRF
  544. function getCSRFToken() {
  545. const metaTag = document.querySelector('meta[name="csrf-token"]');
  546. return metaTag ? metaTag.getAttribute('content') : '';
  547. }
  548. // Funciones de confirmación para actualizaciones
  549. function confirmSquidUpdate() {
  550. showCustomConfirm(
  551. '¿Estás seguro de que deseas actualizar el servicio Squid? Guarda tu configuración antes de continuar, el servicio se reiniciará automáticamente.',
  552. async () => {
  553. try {
  554. const response = await fetch('/install', {
  555. method: 'POST',
  556. headers: {
  557. 'Content-Type': 'application/x-www-form-urlencoded',
  558. 'X-CSRFToken': getCSRFToken()
  559. },
  560. body: new URLSearchParams({ csrf_token: getCSRFToken() })
  561. });
  562. if (response.ok) {
  563. window.location.reload();
  564. } else {
  565. alert('Error al actualizar Squid');
  566. }
  567. } catch (error) {
  568. alert('Error de conexión');
  569. }
  570. }
  571. );
  572. }
  573. function confirmWebUpdate() {
  574. showCustomConfirm(
  575. '¿Estás seguro de que deseas actualizar SquidStats? Se actualizará la interfaz web, funcionalidades y correcciones de seguridad.',
  576. async () => {
  577. try {
  578. const response = await fetch('/update', {
  579. method: 'POST',
  580. headers: {
  581. 'Content-Type': 'application/x-www-form-urlencoded',
  582. 'X-CSRFToken': getCSRFToken()
  583. },
  584. body: new URLSearchParams({ csrf_token: getCSRFToken() })
  585. });
  586. if (response.ok) {
  587. window.location.reload();
  588. } else {
  589. alert('Error al actualizar la aplicación web');
  590. }
  591. } catch (error) {
  592. alert('Error de conexión');
  593. }
  594. }
  595. );
  596. }
  597. </script>