navbar.html 32 KB

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