dashboard.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. import { getLocalDateString } from './utils/fecha.js';
  2. document.addEventListener("DOMContentLoaded", function () {
  3. // Referencias a elementos del DOM
  4. const searchInput = document.getElementById("username-search");
  5. const usersContainer = document.getElementById("users-container");
  6. const modalsContainer = document.getElementById("modals-container");
  7. const prevBtn = document.getElementById("prev-page");
  8. const nextBtn = document.getElementById("next-page");
  9. const firstBtn = document.getElementById("first-page");
  10. const lastBtn = document.getElementById("last-page");
  11. const pageNumbers = document.getElementById("page-numbers");
  12. const dateFilter = document.getElementById("date-filter");
  13. const clearSearchBtn = document.getElementById("clear-search");
  14. // Variables de estado
  15. let userCards = [];
  16. let filteredUsers = [];
  17. let currentPage = 1;
  18. const itemsPerPage = 15;
  19. let page = 1;
  20. // NUEVO: Paginación real usando backend
  21. let totalPages = 1;
  22. let totalUsers = 0;
  23. function fetchUsersPage(selectedDate, page) {
  24. fetch("/get-logs-by-date", {
  25. method: "POST",
  26. headers: { "Content-Type": "application/json" },
  27. body: JSON.stringify({ date: selectedDate, page }),
  28. })
  29. .then((response) => {
  30. return response.json().then((data) => {
  31. return data;
  32. });
  33. })
  34. .then((data) => {
  35. updateUsersData(data.users);
  36. totalPages = data.total_pages;
  37. totalUsers = data.total; // <-- Guarda el total de usuarios
  38. currentPage = data.page;
  39. renderPaginationControls(currentPage, totalPages, selectedDate);
  40. })
  41. .catch((error) => {
  42. console.error("Error:", error);
  43. usersContainer.innerHTML =
  44. '<div class="text-red-500 text-center p-4 col-span-full">Error al cargar los datos</div>';
  45. });
  46. }
  47. function renderPaginationControls(page, totalPages, selectedDate) {
  48. // Verifica que los botones existen antes de usarlos
  49. if (prevBtn) prevBtn.disabled = page <= 1;
  50. if (firstBtn) firstBtn.disabled = page <= 1;
  51. if (nextBtn) nextBtn.disabled = page >= totalPages;
  52. if (lastBtn) lastBtn.disabled = page >= totalPages;
  53. // Números de página
  54. if (pageNumbers) {
  55. pageNumbers.innerHTML = "";
  56. let start = Math.max(1, page - 2);
  57. let end = Math.min(totalPages, page + 2);
  58. if (page <= 3) end = Math.min(5, totalPages);
  59. if (page > totalPages - 2) start = Math.max(1, totalPages - 4);
  60. for (let i = start; i <= end; i++) {
  61. const btn = document.createElement("button");
  62. btn.textContent = i;
  63. btn.className =
  64. "pg-btn px-3 py-1 rounded " +
  65. (i === page ? "bg-blue-600 text-white" : "bg-white text-blue-600");
  66. btn.disabled = i === page;
  67. btn.onclick = () => {
  68. usersContainer.innerHTML = `
  69. <div class=\"loading-spinner flex justify-center items-center h-64 w-full col-span-full\">
  70. <svg class=\"animate-spin h-12 w-12 text-blue-500\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\">
  71. <circle class=\"opacity-25\" cx=\"12\" cy=\"12\" r=\"10\" stroke=\"currentColor\" stroke-width=\"4\"></circle>
  72. <path class=\"opacity-75\" fill=\"currentColor\" d=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"></path>
  73. </svg>
  74. </div>`;
  75. fetchUsersPage(selectedDate,i);
  76. };
  77. pageNumbers.appendChild(btn);
  78. }
  79. }
  80. }
  81. function updateUsersData(usersData) {
  82. if (!usersData || usersData.length === 0) {
  83. usersContainer.innerHTML =
  84. '<div class="text-gray-500 text-center p-4 col-span-full">No se encontraron datos</div>';
  85. return;
  86. }
  87. // Generar tarjetas de usuario
  88. usersContainer.innerHTML = usersData
  89. .map(
  90. (user, index) => `
  91. <div class="user-card group bg-[#f0f2f5] text-center overflow-hidden relative rounded-lg shadow-md w-full max-w-[320px] mx-auto pt-[25px] pb-[70px]" data-username="${user.username.toLowerCase()}">
  92. <div class="avatar-wrapper relative inline-block h-[100px] w-[100px] mb-[15px] z-[1]">
  93. <div class="avatar-effect absolute w-full h-0 bottom-[135%] left-0 rounded-full bg-[#1369ce] opacity-90 scale-[3] transition-all duration-300 ease-linear z-0 group-hover:h-full"></div>
  94. <div class="avatar-background absolute inset-0 rounded-full bg-[#1369ce] z-[1]"></div>
  95. <div class="avatar w-full h-full rounded-full bg-slate-200 flex items-center justify-center text-[2.5rem] text-slate-500 relative transition-all duration-900 ease-in-out group-hover:shadow-[0_0_0_10px_#f7f5ec] group-hover:scale-[0.7] z-[2]">
  96. <i class="fas fa-user"></i>
  97. </div>
  98. </div>
  99. <div class="user-info mt-[-15px] mb-4 px-[15px]">
  100. <h3 class="username font-semibold text-[1.2rem] text-[#1369ce] mb-0">${
  101. user.username
  102. }</h3>
  103. <h4 class="ip-address text-[0.9rem] text-gray-500">${user.ip}</h4>
  104. </div>
  105. <div class="card-action px-[15px] mt-[2px] relative z-[2]">
  106. <button class="activity-button w-full bg-[#1369ce] text-white font-bold py-2 rounded-md cursor-pointer transition-all duration-300 text-sm hover:bg-[#0d5bb5] hover:-translate-y-0.5 shadow-md"
  107. onclick="window.openLogsModal(${index});">
  108. ACTIVIDAD
  109. </button>
  110. </div>
  111. <ul class="card-footer absolute bottom-[-80px] left-0 w-full px-4 py-3 bg-[#1369ce] text-white text-sm flex justify-between transition-all duration-500 ease-in-out group-hover:bottom-0 shadow-[0_-4px_6px_rgba(0,0,0,0.2)] z-[1]">
  112. <li class="flex flex-col items-center">
  113. <span class="label text-xs font-light uppercase tracking-wide">Solicitudes:</span>
  114. <span class="value font-semib">${user.total_requests}</span>
  115. </li>
  116. <li class="flex flex-col items-center">
  117. <span class="label text-xs font-light uppercase tracking-wide">Datos:</span>
  118. <span class="value font-semib">${formatBytes(
  119. user.total_data
  120. )}</span>
  121. </li>
  122. </ul>
  123. </div>
  124. `
  125. )
  126. .join("");
  127. // Mensaje de no resultados
  128. usersContainer.insertAdjacentHTML(
  129. "beforeend",
  130. `
  131. <div class="no-results-msg hidden col-span-full text-center py-12">
  132. <i class="fas fa-user-slash text-4xl text-gray-400 mb-4"></i>
  133. <h3 class="text-xl font-semibold text-gray-600">
  134. No se encontraron usuarios
  135. </h3>
  136. <p class="text-gray-500 mt-2">
  137. Intenta con otro término de búsqueda
  138. </p>
  139. </div>
  140. `
  141. );
  142. function groupLogsByUrl(logs) {
  143. const groups = {};
  144. logs.forEach((log) => {
  145. if (!groups[log.url]) {
  146. groups[log.url] = {
  147. url: log.url,
  148. responses: {}, // Para contar frecuencia de códigos de respuesta
  149. total_requests: 0,
  150. total_data: 0,
  151. entryCount: 0, // Cuántas entradas originales se agruparon
  152. };
  153. }
  154. const group = groups[log.url];
  155. group.total_requests += log.request_count;
  156. group.total_data += log.data_transmitted;
  157. group.entryCount += 1;
  158. // Contar frecuencia de códigos de respuesta
  159. if (group.responses[log.response]) {
  160. group.responses[log.response] += log.request_count;
  161. } else {
  162. group.responses[log.response] = log.request_count;
  163. }
  164. });
  165. return Object.values(groups).map((group) => {
  166. // Determinar el código de respuesta dominante (el más frecuente)
  167. let dominantResponse = 0;
  168. let maxCount = 0;
  169. for (const [response, count] of Object.entries(group.responses)) {
  170. if (count > maxCount) {
  171. maxCount = count;
  172. dominantResponse = parseInt(response);
  173. }
  174. }
  175. return {
  176. url: group.url,
  177. response: dominantResponse,
  178. request_count: group.total_requests,
  179. data_transmitted: group.total_data,
  180. isGrouped: group.entryCount > 1, // Indica si es un grupo (más de una entrada original)
  181. };
  182. });
  183. }
  184. // Generar modales para cada usuario
  185. modalsContainer.innerHTML = usersData
  186. .map((user, index) => {
  187. // Contar los tipos de respuestas para los filtros
  188. const responseCounts = {
  189. informational: 0,
  190. successful: 0,
  191. redirection: 0,
  192. clientError: 0,
  193. serverError: 0,
  194. unknown: 0,
  195. };
  196. user.logs.forEach((log) => {
  197. const code = log.response;
  198. if (code >= 100 && code <= 199) responseCounts.informational++;
  199. else if (code >= 200 && code <= 299) responseCounts.successful++;
  200. else if (code >= 300 && code <= 399) responseCounts.redirection++;
  201. else if (code >= 400 && code <= 499) responseCounts.clientError++;
  202. else if (code >= 500 && code <= 599) responseCounts.serverError++;
  203. else responseCounts.unknown++;
  204. });
  205. // Configuración de grupos de respuestas
  206. const responseGroups = {
  207. informational: {
  208. icon: "fa-info-circle",
  209. color: "text-blue-500",
  210. label: "Respuestas informativas (100–199)",
  211. },
  212. successful: {
  213. icon: "fa-circle-check",
  214. color: "text-green-500",
  215. label: "Respuestas exitosas (200–299)",
  216. },
  217. redirection: {
  218. icon: "fa-arrow-right",
  219. color: "text-yellow-500",
  220. label: "Mensajes de redirección (300–399)",
  221. },
  222. clientError: {
  223. icon: "fa-circle-xmark",
  224. color: "text-red-500",
  225. label: "Respuestas de error del cliente (400–499)",
  226. },
  227. serverError: {
  228. icon: "fa-triangle-exclamation",
  229. color: "text-orange-400",
  230. label: "Respuestas de error del servidor (500–599)",
  231. },
  232. unknown: {
  233. icon: "fa-question",
  234. color: "text-gray-500",
  235. label: "Otros",
  236. },
  237. };
  238. // Resumen de respuestas
  239. const responseSummary = Object.entries(responseCounts)
  240. .map(([key, count]) => {
  241. if (count === 0) return "";
  242. const { icon, color, label } = responseGroups[key];
  243. return `
  244. <div class="filter-icon flex items-center gap-1 text-sm cursor-pointer transition-colors"
  245. data-filter-type="${key}"
  246. data-active="true"
  247. data-color="${color}"
  248. style="color: ${getComputedTailwindColor(color)}"
  249. title="${label}"
  250. onclick="window.toggleResponseFilter(this, ${index})">
  251. <i class="fa-solid ${icon}"></i>
  252. <span>${count}</span>
  253. </div>`;
  254. })
  255. .join("");
  256. // Agrupar logs por URL para mostrar en el modal
  257. const groupedLogs = groupLogsByUrl(user.logs);
  258. // Generar HTML del modal
  259. return `
  260. <div class="logs-modal hidden fixed inset-0 bg-black bg-opacity-50 z-[1000] justify-center items-center transition-all duration-1000 ease-in-out opacity-0" id="logs-modal-${index}">
  261. <div class="modal-content bg-white p-8 rounded-2xl w-[95%] max-w-[650px] max-h-[85vh] overflow-auto shadow-[0_10px_30px_rgba(0,0,0,0.3)] transition-all duration-1000 ease-in-out relative">
  262. <button onclick="window.closeLogsModal(${index})"
  263. class="close-btn absolute top-3 right-3 w-8 h-8 flex items-center justify-center bg-red-500 text-white rounded-full z-50 shadow-md transform transition-all duration-300 hover:bg-red-600 hover:scale-110 hover:rotate-90 hover:shadow-lg"
  264. title="Cerrar" aria-label="Cerrar">
  265. <i class="fas fa-times text-base"></i>
  266. </button>
  267. <div class="flex flex-col">
  268. <div class="flex justify-between items-center mb-4">
  269. <div class="flex items-center gap-2 min-w-0 flex-wrap">
  270. <h4 class="logs-title text-base text-gray-500 uppercase tracking-[1px] font-semibold whitespace-nowrap">
  271. Actividad reciente -
  272. </h4>
  273. <div class="flex items-center gap-2">
  274. <span class="username-highlight font-semibold truncate max-w-[120px] text-[#1369ce]">${
  275. user.username
  276. }</span>
  277. <!-- Contenedor de búsqueda al lado del nombre de usuario -->
  278. <div id="searchBox-${index}" class="relative w-auto h-[38px] bg-white rounded-full transition-all duration-500 ease-in-out shadow-md flex items-center border border-gray-300">
  279. <div id="toggleBtn-${index}" class="absolute left-0 top-0 w-[38px] h-[38px] flex items-center justify-center cursor-pointer z-10">
  280. <i class="fas fa-search text-blue-600 text-sm"></i>
  281. </div>
  282. <div id="inputWrapper-${index}" class="ml-[38px] w-0 h-[38px] flex items-center transition-[width] duration-500 ease-in-out overflow-hidden">
  283. <input id="mysearch-${index}" type="text" placeholder="Buscar URL..." class="w-full text-xs px-2 py-1 bg-transparent outline-none opacity-0 transition-opacity duration-300 ease-linear min-w-[150px]"/>
  284. </div>
  285. <button id="clearBtn-${index}"
  286. class="absolute right-2 h-full flex items-center justify-center opacity-0 transition-opacity duration-300 text-gray-400 hover:text-gray-700 text-sm"
  287. title="Limpiar búsqueda">
  288. <i class="fas fa-times text-lg leading-none"></i>
  289. </button>
  290. </div>
  291. </div>
  292. </div>
  293. </div>
  294. <div class="response-summary flex justify-end gap-4 items-center mb-4">
  295. ${responseSummary}
  296. </div>
  297. </div>
  298. <div class="logs-list mt-2 max-h-[60vh] overflow-y-auto">
  299. ${
  300. groupedLogs.length > 0
  301. ? `
  302. <div class="log-entries-container grid gap-3">
  303. ${groupedLogs
  304. .map((log) => {
  305. const truncatedUrl = truncate(log.url, 55);
  306. const isHttps = /:(443|8443)$/.test(log.url);
  307. const protocol = isHttps ? "https://" : "http://";
  308. const fullUrl = log.url.startsWith("http")
  309. ? log.url
  310. : protocol + log.url;
  311. // Determinar clase de badge según el código de respuesta
  312. let badgeClass = "bg-gray-400";
  313. if (log.response >= 100 && log.response <= 199)
  314. badgeClass = "bg-blue-400";
  315. else if (log.response >= 200 && log.response <= 299)
  316. badgeClass = "bg-green-500";
  317. else if (log.response >= 300 && log.response <= 399)
  318. badgeClass = "bg-yellow-400";
  319. else if (log.response >= 400 && log.response <= 499)
  320. badgeClass = "bg-red-500";
  321. else if (log.response >= 500 && log.response <= 599)
  322. badgeClass = "bg-orange-400";
  323. // Clase CSS adicional para entradas agrupadas
  324. const groupClass = log.isGrouped
  325. ? "grouped-log-entry"
  326. : "";
  327. const groupIcon = log.isGrouped
  328. ? '<i class="fas fa-layer-group text-blue-500 ml-2 text-xs" title="Solicitudes agrupadas"></i>'
  329. : "";
  330. return `
  331. <div class="log-entry relative group p-3 bg-white rounded-lg transition-all duration-300 ease-out shadow-md hover:shadow-2xl hover:-translate-y-1 hover:z-10 ${groupClass}"
  332. data-response-code="${log.response}">
  333. <div class="wave-container absolute inset-0 overflow-hidden rounded-lg">
  334. <div class="wave absolute w-full h-full"></div>
  335. </div>
  336. <div class="relative z-10 grid grid-cols-[minmax(0,1fr)_auto] items-start gap-2">
  337. <div class="log-details-grid min-w-0">
  338. <div class="flex items-baseline gap-3">
  339. <span class="log-url text-sm font-medium text-gray-800 truncate">
  340. ${truncatedUrl}
  341. </span>
  342. ${groupIcon}
  343. </div>
  344. <div class="mt-1 flex flex-wrap items-center gap-3 text-sm text-gray-600">
  345. <span class="response-badge ${badgeClass} inline-block px-2 py-[0.15rem] rounded-md text-[0.65rem] font-medium text-white">
  346. ${log.response}
  347. </span>
  348. <span class="log-meta flex items-center gap-1">
  349. <i class="fas fa-hashtag text-gray-400"></i>
  350. ${log.request_count} reqs
  351. </span>
  352. <span class="log-meta flex items-center gap-1">
  353. <i class="fas fa-database text-gray-400"></i>
  354. ${formatBytes(log.data_transmitted)}
  355. </span>
  356. </div>
  357. </div>
  358. <div class="flex items-center gap-2 flex-shrink-0">
  359. <i class="fa-solid fa-up-right-from-square text-blue-600 hover:text-blue-800 cursor-pointer text-lg"
  360. title="Abrir enlace"
  361. onclick="window.open('${fullUrl}', '_blank')"></i>
  362. </div>
  363. </div>
  364. </div>
  365. `;
  366. })
  367. .join("")}
  368. </div>
  369. `
  370. : '<div class="no-logs text-gray-500 text-center py-8">No hay actividad registrada</div>'
  371. }
  372. <div class="no-results hidden text-center py-8 text-gray-500">
  373. No se encontraron resultados
  374. </div>
  375. </div>
  376. </div>
  377. </div>
  378. `;
  379. })
  380. .join("");
  381. // Configurar eventos de búsqueda en modales
  382. usersData.forEach((_, index) => {
  383. const toggleBtn = document.getElementById(`toggleBtn-${index}`);
  384. const inputWrapper = document.getElementById(`inputWrapper-${index}`);
  385. const input = document.getElementById(`mysearch-${index}`);
  386. const clearBtn = document.getElementById(`clearBtn-${index}`);
  387. toggleBtn.addEventListener("click", () => {
  388. const isExpanding = !inputWrapper.classList.contains("w-[180px]");
  389. if (isExpanding) {
  390. inputWrapper.classList.add("w-[180px]");
  391. input.classList.remove("opacity-0");
  392. clearBtn.classList.remove("opacity-0");
  393. setTimeout(() => input.focus(), 300);
  394. } else {
  395. inputWrapper.classList.remove("w-[180px]");
  396. input.classList.add("opacity-0");
  397. clearBtn.classList.add("opacity-0");
  398. input.value = "";
  399. // SOLUCIÓN: Ahora usa la función unificada de filtrado
  400. applyFiltersToModal(index);
  401. }
  402. });
  403. clearBtn.addEventListener("click", () => {
  404. input.value = "";
  405. // SOLUCIÓN: Ahora usa la función unificada de filtrado
  406. applyFiltersToModal(index);
  407. input.focus();
  408. });
  409. input.addEventListener("input", () => {
  410. // SOLUCIÓN: Ahora usa la función unificada de filtrado
  411. applyFiltersToModal(index);
  412. });
  413. });
  414. // Actualizar estado de las tarjetas
  415. userCards = Array.from(document.querySelectorAll(".user-card"));
  416. filteredUsers = [...userCards];
  417. filterUsers();
  418. }
  419. function filterUsers() {
  420. const searchValue = searchInput.value.toLowerCase().trim();
  421. clearSearchBtn.style.display = searchValue ? "flex" : "none";
  422. filteredUsers = userCards.filter((card) => {
  423. return searchValue === "" || card.dataset.username.includes(searchValue);
  424. });
  425. const noResultsMsg = document.querySelector(".no-results-msg");
  426. if (noResultsMsg) {
  427. noResultsMsg.style.display =
  428. filteredUsers.length === 0 ? "block" : "none";
  429. }
  430. renderPage(page);
  431. }
  432. function renderPage(page) {
  433. if (page < 1 || page === null) page = 1;
  434. currentPage = page;
  435. // Ocultar todas las tarjetas
  436. userCards.forEach((card) => (card.style.display = "none"));
  437. // Manejar caso sin resultados
  438. const noResultsMsg = document.querySelector(".no-results-msg");
  439. if (filteredUsers.length === 0) {
  440. if (!noResultsMsg) {
  441. usersContainer.innerHTML = `
  442. <div class="no-results-msg col-span-full text-center py-12">
  443. <i class="fas fa-user-slash text-4xl text-gray-400 mb-4"></i>
  444. <h3 class="text-xl font-semibold text-gray-600">
  445. No se encontraron usuarios
  446. </h3>
  447. <p class="text-gray-500 mt-2">
  448. Intenta con otro término de búsqueda
  449. </p>
  450. </div>
  451. `;
  452. } else {
  453. noResultsMsg.style.display = "block";
  454. }
  455. // Deshabilitar paginación
  456. pageNumbers.innerHTML = "";
  457. firstBtn.disabled = true;
  458. prevBtn.disabled = true;
  459. nextBtn.disabled = true;
  460. lastBtn.disabled = true;
  461. return;
  462. } else if (noResultsMsg) {
  463. noResultsMsg.style.display = "none";
  464. }
  465. // Mostrar usuarios de la página actual
  466. const start = (page - 1) * itemsPerPage;
  467. const end = start + itemsPerPage;
  468. const currentUsers = filteredUsers.slice(start, end);
  469. currentUsers.forEach((card) => (card.style.display = "block"));
  470. // Actualizar controles de paginación
  471. pageNumbers.innerHTML = "";
  472. const startPage = Math.max(1, currentPage - 1);
  473. const endPage = Math.min(totalPages, startPage + 2);
  474. for (let i = startPage; i <= endPage; i++) {
  475. const btn = document.createElement("button");
  476. btn.textContent = i;
  477. btn.className = `pg-btn text-lg px-3 py-1 rounded-full shadow-md font-medium ${
  478. i === currentPage
  479. ? "bg-blue-500 text-white"
  480. : "bg-gray-100 text-gray-800 hover:bg-gray-300"
  481. }`;
  482. btn.onclick = () => renderPage(i);
  483. pageNumbers.appendChild(btn);
  484. }
  485. // Actualizar estado de botones de navegación
  486. firstBtn.disabled = currentPage === 1;
  487. prevBtn.disabled = currentPage === 1;
  488. nextBtn.disabled = currentPage === totalPages;
  489. lastBtn.disabled = currentPage === totalPages;
  490. }
  491. // Event listeners
  492. if (clearSearchBtn) {
  493. clearSearchBtn.addEventListener("click", () => {
  494. searchInput.value = "";
  495. clearSearchBtn.style.display = "none";
  496. filterUsers();
  497. });
  498. }
  499. if (searchInput) searchInput.addEventListener("input", filterUsers);
  500. if (prevBtn)
  501. prevBtn.addEventListener("click", () => {
  502. if (currentPage > 1) {
  503. const selectedDate = dateFilter.value;
  504. usersContainer.innerHTML = `
  505. <div class="loading-spinner flex justify-center items-center h-64 w-full col-span-full">
  506. <svg class="animate-spin h-12 w-12 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
  507. <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
  508. <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  509. </svg>
  510. </div>`;
  511. fetchUsersPage(selectedDate, currentPage - 1);
  512. }
  513. });
  514. if (nextBtn)
  515. nextBtn &&
  516. nextBtn.addEventListener("click", () => {
  517. if (currentPage < totalPages) {
  518. const selectedDate = dateFilter.value;
  519. usersContainer.innerHTML = `
  520. <div class="loading-spinner flex justify-center items-center h-64 w-full col-span-full">
  521. <svg class="animate-spin h-12 w-12 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
  522. <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
  523. <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  524. </svg>
  525. </div>`;
  526. fetchUsersPage(selectedDate, currentPage + 1);
  527. }
  528. });
  529. if (firstBtn)
  530. firstBtn.addEventListener("click", () => {
  531. usersContainer.innerHTML = `
  532. <div class="loading-spinner flex justify-center items-center h-64 w-full col-span-full">
  533. <svg class="animate-spin h-12 w-12 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
  534. <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
  535. <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  536. </svg>
  537. </div>`;
  538. fetchUsersPage(dateFilter.value, 1);
  539. });
  540. if (lastBtn)
  541. lastBtn.addEventListener("click", () => {
  542. usersContainer.innerHTML = `
  543. <div class="loading-spinner flex justify-center items-center h-64 w-full col-span-full">
  544. <svg class="animate-spin h-12 w-12 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
  545. <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
  546. <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  547. </svg>
  548. </div>`;
  549. fetchUsersPage(dateFilter.value, totalPages);
  550. });
  551. const today = getLocalDateString();
  552. if (!dateFilter.value) dateFilter.value = today;
  553. // Event listener para cambio de fecha
  554. dateFilter.addEventListener("change", async (e) => {
  555. const selectedDate = e.target.value;
  556. if (!selectedDate) return;
  557. try {
  558. // Mostrar spinner de carga
  559. usersContainer.innerHTML = `
  560. <div class="loading-spinner flex justify-center items-center h-64 w-full col-span-full">
  561. <svg class="animate-spin h-12 w-12 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
  562. <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
  563. <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  564. </svg>
  565. </div>`;
  566. // Obtener datos del servidor
  567. await fetchUsersPage(selectedDate, page);
  568. } catch (error) {
  569. console.error("Error:", error);
  570. usersContainer.innerHTML =
  571. '<div class="text-red-500 text-center p-4 col-span-full">Error al cargar los datos</div>';
  572. }
  573. });
  574. // Carga inicial
  575. dateFilter.dispatchEvent(new Event("change"));
  576. });
  577. function openLogsModal(index) {
  578. const modal = document.getElementById(`logs-modal-${index}`);
  579. const overlay = document.getElementById("overlay");
  580. if (modal) {
  581. modal.classList.remove("hidden");
  582. modal.classList.add("flex");
  583. setTimeout(() => {
  584. modal.classList.remove("opacity-0");
  585. modal.classList.add("opacity-100");
  586. }, 10);
  587. }
  588. if (overlay) {
  589. overlay.classList.remove("hidden");
  590. setTimeout(() => {
  591. overlay.classList.remove("opacity-0");
  592. overlay.classList.add("opacity-100");
  593. }, 10);
  594. }
  595. }
  596. function closeLogsModal(index) {
  597. const modal = document.getElementById(`logs-modal-${index}`);
  598. const overlay = document.getElementById("overlay");
  599. if (modal) {
  600. modal.classList.remove("opacity-100");
  601. modal.classList.add("opacity-0");
  602. setTimeout(() => {
  603. modal.classList.add("hidden");
  604. modal.classList.remove("flex");
  605. }, 1000);
  606. }
  607. if (overlay) {
  608. overlay.classList.remove("opacity-100");
  609. overlay.classList.add("opacity-0");
  610. setTimeout(() => {
  611. overlay.classList.add("hidden");
  612. }, 1000);
  613. }
  614. }
  615. function applyFiltersToModal(modalIndex) {
  616. const modal = document.getElementById(`logs-modal-${modalIndex}`);
  617. const entries = modal.querySelectorAll(".log-entry");
  618. const noResults = modal.querySelector(".no-results");
  619. const input = document.getElementById(`mysearch-${modalIndex}`);
  620. const query = input.value.toLowerCase();
  621. // Obtener estados actuales de todos los filtros de respuesta
  622. const filterButtons = modal.querySelectorAll(
  623. ".response-summary .filter-icon"
  624. );
  625. const activeFilters = {};
  626. filterButtons.forEach((btn) => {
  627. const type = btn.dataset.filterType;
  628. activeFilters[type] = btn.dataset.active === "true";
  629. });
  630. let visibleCount = 0;
  631. entries.forEach((entry) => {
  632. const code = parseInt(entry.dataset.responseCode);
  633. let type = "unknown";
  634. // Determinar categoría de respuesta basado en el código HTTP
  635. if (code >= 100 && code <= 199) type = "informational";
  636. else if (code >= 200 && code <= 299) type = "successful";
  637. else if (code >= 300 && code <= 399) type = "redirection";
  638. else if (code >= 400 && code <= 499) type = "clientError";
  639. else if (code >= 500 && code <= 599) type = "serverError";
  640. // Verificar ambos filtros: respuesta y búsqueda
  641. const passesResponseFilter = activeFilters[type];
  642. const urlText =
  643. entry.querySelector(".log-url")?.textContent.toLowerCase() || "";
  644. const passesSearchFilter = query === "" || urlText.includes(query);
  645. // Mostrar solo si pasa ambos filtros
  646. const isVisible = passesResponseFilter && passesSearchFilter;
  647. entry.style.display = isVisible ? "" : "none";
  648. if (isVisible) visibleCount++;
  649. });
  650. // Mostrar mensaje "no resultados" solo cuando hay filtros activos y no hay coincidencias
  651. noResults.style.display =
  652. visibleCount === 0 &&
  653. (query !== "" || Object.values(activeFilters).some((active) => !active))
  654. ? "block"
  655. : "none";
  656. }
  657. function toggleResponseFilter(el, modalIndex) {
  658. // Toggle del estado activo
  659. const isActive = el.dataset.active === "true";
  660. el.dataset.active = isActive ? "false" : "true";
  661. // Actualizar apariencia visual
  662. if (isActive) {
  663. el.style.color = "#9CA3AF"; // Color gris para inactivo
  664. } else {
  665. el.style.color = getComputedTailwindColor(el.dataset.color); // Color original
  666. }
  667. // SOLUCIÓN: Ahora aplica ambos tipos de filtros
  668. applyFiltersToModal(modalIndex);
  669. }
  670. function filterLogs(index) {
  671. // SOLUCIÓN: Ahora aplica ambos tipos de filtros
  672. applyFiltersToModal(index);
  673. }
  674. function getComputedTailwindColor(className) {
  675. const colorMap = {
  676. "text-blue-500": "#3B82F6",
  677. "text-green-500": "#22C55E",
  678. "text-yellow-500": "#EAB308",
  679. "text-red-500": "#EF4444",
  680. "text-orange-400": "#FB923C",
  681. "text-gray-500": "#6B7280",
  682. };
  683. return colorMap[className] || "#6B7280";
  684. }
  685. function truncate(str, n) {
  686. return str.length > n ? str.slice(0, n - 1) + "..." : str;
  687. }
  688. function formatBytes(bytes) {
  689. const units = ["B", "KB", "MB", "GB"];
  690. let value = bytes;
  691. let unitIndex = 0;
  692. while (value >= 1024 && unitIndex < units.length - 1) {
  693. value /= 1024;
  694. unitIndex++;
  695. }
  696. return `${value.toFixed(2)} ${units[unitIndex]}`;
  697. }
  698. // Hacer funciones disponibles globalmente
  699. window.openLogsModal = openLogsModal;
  700. window.closeLogsModal = closeLogsModal;
  701. window.toggleResponseFilter = toggleResponseFilter;
  702. window.filterLogs = filterLogs;