auditoria.html 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
  2. <link
  3. rel="stylesheet"
  4. href="{{ url_for('static', filename='css/toastr.min.css') }}"
  5. />
  6. <script src="{{ url_for('static', filename='js/jquery-3.7.1.min.js') }}"></script>
  7. <script src="{{ url_for('static', filename='js/toastr.min.js') }}"></script>
  8. <style>
  9. /* Estilo para los "chips" de redes sociales */
  10. .social-chip {
  11. padding: 8px 16px;
  12. border-radius: 9999px;
  13. font-size: 0.875rem;
  14. font-weight: 600;
  15. cursor: pointer;
  16. transition: all 0.2s ease-in-out;
  17. border: 1px solid #e5e7eb; /* gray-200 */
  18. background-color: #f9fafb; /* gray-50 */
  19. color: #374151; /* gray-700 */
  20. box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
  21. }
  22. .social-chip:hover {
  23. border-color: #93c5fd; /* blue-300 */
  24. background-color: #eff6ff; /* blue-50 */
  25. transform: translateY(-1px);
  26. box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
  27. }
  28. .social-chip.selected {
  29. background-color: #2563eb; /* blue-600 */
  30. color: white;
  31. border-color: #1d4ed8; /* blue-800 */
  32. box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
  33. }
  34. .social-chip.selected:hover {
  35. background-color: #1d4ed8;
  36. }
  37. /* Estilo para el tooltip de ayuda sobre los chips */
  38. .tooltip {
  39. position: absolute;
  40. bottom: 100%;
  41. left: 50%;
  42. transform: translateX(-50%);
  43. margin-bottom: 8px;
  44. background-color: #111827; /* gray-900 */
  45. color: white;
  46. padding: 4px 8px;
  47. border-radius: 4px;
  48. font-size: 0.75rem;
  49. font-weight: 500;
  50. white-space: nowrap;
  51. opacity: 0;
  52. transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;
  53. pointer-events: none; /* Para que no interfiera con el click */
  54. transform-origin: bottom center;
  55. transform: translateX(-50%) scale(0.95);
  56. }
  57. .group:hover .tooltip {
  58. opacity: 1;
  59. transform: translateX(-50%) scale(1);
  60. }
  61. </style>
  62. <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
  63. <div class="flex items-center mb-6 border-b pb-4">
  64. <i class="fas fa-magnifying-glass text-3xl text-blue-600 mr-4"></i>
  65. <div>
  66. <h1 class="text-3xl font-bold text-gray-800">Centro de Auditoría</h1>
  67. <p class="text-gray-500 mt-1">
  68. Herramienta para el análisis de actividad y seguridad.
  69. </p>
  70. </div>
  71. </div>
  72. <div class="bg-white p-6 rounded-lg shadow-lg mb-8">
  73. <form
  74. id="audit-form"
  75. class="grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-6"
  76. >
  77. <div class="lg:col-span-2 grid grid-cols-1 md:grid-cols-2 gap-6">
  78. <div class="md:col-span-2">
  79. <label
  80. for="audit-type"
  81. class="block text-sm font-semibold text-gray-700 mb-1"
  82. >Tipo de Auditoría</label
  83. >
  84. <select
  85. id="audit-type"
  86. name="audit_type"
  87. class="w-full border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 bg-gray-50"
  88. >
  89. <optgroup label="Actividad General">
  90. <option value="user_summary" data-requires="user">
  91. Resumen por Usuario
  92. </option>
  93. <option value="top_users_data">Top 10 Usuarios (Datos)</option>
  94. <!-- <option value="daily_activity" data-requires="user">
  95. Actividad Diaria
  96. </option> -->
  97. </optgroup>
  98. <optgroup label="Seguridad y Políticas">
  99. <option
  100. value="keyword_search"
  101. data-requires="user_optional,keyword"
  102. >
  103. Búsqueda por Palabra Clave
  104. </option>
  105. <option
  106. value="social_media_activity"
  107. data-requires="user_optional,social_media"
  108. >
  109. Actividad en Redes Sociales
  110. </option>
  111. </optgroup>
  112. <optgroup label="Auditoría Técnica">
  113. <option value="ip_activity" data-requires="ip">
  114. Actividad por Dirección IP
  115. </option>
  116. <option
  117. value="response_code_search"
  118. data-requires="user_optional,response_code"
  119. >
  120. Análisis por Código de Respuesta
  121. </option>
  122. </optgroup>
  123. </select>
  124. </div>
  125. <div id="conditional-inputs" class="contents">
  126. <div id="user-filter-container" class="conditional-input">
  127. <label
  128. for="username-filter"
  129. class="block text-sm font-semibold text-gray-700 mb-1"
  130. >Usuario</label
  131. >
  132. <div class="relative">
  133. <input
  134. type="text"
  135. id="user-search-input"
  136. placeholder="Buscar usuario..."
  137. class="w-full border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 bg-gray-50 pr-8"
  138. autocomplete="off"
  139. />
  140. <i
  141. class="fas fa-search absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm"
  142. ></i>
  143. <div
  144. id="user-dropdown"
  145. class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-48 overflow-y-auto hidden"
  146. >
  147. <div id="user-options-container">
  148. <!-- Las opciones se llenarán dinámicamente -->
  149. </div>
  150. </div>
  151. </div>
  152. <select id="username-filter" name="username" class="hidden">
  153. <option value="">-- Todos --</option>
  154. </select>
  155. </div>
  156. <div id="keyword-input-container" class="conditional-input">
  157. <label
  158. for="keyword-input"
  159. class="block text-sm font-semibold text-gray-700 mb-1"
  160. >Palabra Clave</label
  161. >
  162. <input
  163. type="text"
  164. id="keyword-input"
  165. name="keyword"
  166. class="w-full border-gray-300 rounded-md shadow-sm bg-gray-50"
  167. placeholder="Ej: juegos, descargas..."
  168. />
  169. </div>
  170. <div id="ip-input-container" class="conditional-input">
  171. <label
  172. for="ip-input"
  173. class="block text-sm font-semibold text-gray-700 mb-1"
  174. >Dirección IP</label
  175. >
  176. <input
  177. type="text"
  178. id="ip-input"
  179. name="ip_address"
  180. class="w-full border-gray-300 rounded-md shadow-sm bg-gray-50"
  181. placeholder="Ej: 192.168.1.100"
  182. />
  183. </div>
  184. <div
  185. id="social-media-input-container"
  186. class="conditional-input md:col-span-2"
  187. >
  188. <label class="block text-sm font-semibold text-gray-700 mb-2"
  189. >Redes Sociales</label
  190. >
  191. <div id="social-media-chips" class="flex flex-wrap gap-3">
  192. <div class="relative group">
  193. <button type="button" class="social-chip" data-value="Facebook">
  194. Facebook
  195. </button>
  196. <span class="tooltip">Selección múltiple</span>
  197. </div>
  198. <div class="relative group">
  199. <button
  200. type="button"
  201. class="social-chip"
  202. data-value="Instagram"
  203. >
  204. Instagram
  205. </button>
  206. <span class="tooltip">Selección múltiple</span>
  207. </div>
  208. <div class="relative group">
  209. <button type="button" class="social-chip" data-value="YouTube">
  210. YouTube
  211. </button>
  212. <span class="tooltip">Selección múltiple</span>
  213. </div>
  214. <div class="relative group">
  215. <button
  216. type="button"
  217. class="social-chip"
  218. data-value="Twitter/X"
  219. >
  220. Twitter/X
  221. </button>
  222. <span class="tooltip">Selección múltiple</span>
  223. </div>
  224. <div class="relative group">
  225. <button type="button" class="social-chip" data-value="WhatsApp">
  226. WhatsApp
  227. </button>
  228. <span class="tooltip">Selección múltiple</span>
  229. </div>
  230. <div class="relative group">
  231. <button type="button" class="social-chip" data-value="Telegram">
  232. Telegram
  233. </button>
  234. <span class="tooltip">Selección múltiple</span>
  235. </div>
  236. <div class="relative group">
  237. <button
  238. type="button"
  239. class="social-chip"
  240. data-value="Pinterest"
  241. >
  242. Pinterest
  243. </button>
  244. <span class="tooltip">Selección múltiple</span>
  245. </div>
  246. </div>
  247. </div>
  248. <div id="response-code-input-container" class="conditional-input">
  249. <label
  250. for="response-code-input"
  251. class="block text-sm font-semibold text-gray-700 mb-1"
  252. >Código HTTP</label
  253. >
  254. <select
  255. id="response-code-input"
  256. name="response_code"
  257. class="w-full border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 bg-gray-50"
  258. >
  259. <option value="">-- Seleccione un código --</option>
  260. <optgroup label="Respuestas Exitosas (2xx)">
  261. <option value="200">200 OK</option>
  262. </optgroup>
  263. <optgroup label="Redirecciones (3xx)">
  264. <option value="301">301 Moved Permanently</option>
  265. <option value="302">302 Found</option>
  266. <option value="304">304 Not Modified</option>
  267. </optgroup>
  268. <optgroup label="Errores de Cliente (4xx)">
  269. <option value="400">400 Bad Request</option>
  270. <option value="401">401 Unauthorized</option>
  271. <option value="403">403 Forbidden</option>
  272. <option value="404">404 Not Found</option>
  273. </optgroup>
  274. <optgroup label="Errores de Servidor (5xx)">
  275. <option value="500">500 Internal Server Error</option>
  276. <option value="502">502 Bad Gateway</option>
  277. <option value="503">503 Service Unavailable</option>
  278. <option value="504">504 Gateway Timeout</option>
  279. </optgroup>
  280. </select>
  281. </div>
  282. </div>
  283. </div>
  284. <div
  285. class="lg:col-span-1 bg-slate-50 border border-slate-200 rounded-lg p-4 h-fit"
  286. >
  287. <h3 class="text-md font-semibold text-slate-800 mb-4 border-b pb-2">
  288. Fecha del Reporte
  289. </h3>
  290. <div class="space-y-4">
  291. <div id="start-date-container">
  292. <label
  293. for="start-date"
  294. class="block text-sm font-semibold text-gray-700 mb-1"
  295. >Fecha</label
  296. >
  297. <input
  298. type="date"
  299. id="start-date"
  300. name="start_date"
  301. class="w-full border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 bg-gray-50"
  302. />
  303. </div>
  304. <div id="end-date-container">
  305. <label
  306. for="end-date"
  307. class="block text-sm font-semibold text-gray-700 mb-1"
  308. >Fecha de Fin</label
  309. >
  310. <input
  311. type="date"
  312. id="end-date"
  313. name="end_date"
  314. class="w-full border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 bg-gray-50"
  315. />
  316. </div>
  317. </div>
  318. </div>
  319. <div class="lg:col-span-3">
  320. <button
  321. type="submit"
  322. class="w-full bg-blue-600 text-white font-bold py-2.5 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl"
  323. >
  324. <i class="fas fa-play mr-2"></i>
  325. Generar Reporte
  326. </button>
  327. </div>
  328. </form>
  329. </div>
  330. <div id="audit-results-container" class="space-y-4">
  331. <div
  332. class="bg-white p-6 rounded-lg shadow-lg min-h-[300px] flex items-center justify-center"
  333. >
  334. <div class="text-center text-gray-500 py-10">
  335. <i class="fas fa-clipboard-list text-5xl mb-4 text-gray-300"></i>
  336. <h3 class="text-xl font-semibold">
  337. Seleccione los filtros y genere un reporte
  338. </h3>
  339. <p class="mt-2">Los resultados de su auditoría aparecerán aquí.</p>
  340. </div>
  341. </div>
  342. </div>
  343. </div>
  344. <script>
  345. toastr.options = {
  346. closeButton: false,
  347. debug: false,
  348. newestOnTop: true,
  349. progressBar: false,
  350. positionClass: "toast-top-right",
  351. preventDuplicates: true,
  352. onclick: null,
  353. showDuration: "300",
  354. hideDuration: "1000",
  355. timeOut: "5000",
  356. extendedTimeOut: "1000",
  357. showEasing: "swing",
  358. hideEasing: "linear",
  359. showMethod: "fadeIn",
  360. hideMethod: "fadeOut",
  361. };
  362. function toggleDetails(header) {
  363. const details = header.nextElementSibling;
  364. const icon = header.querySelector(".toggle-icon");
  365. if (details.style.display === "block") {
  366. details.style.display = "none";
  367. icon.classList.remove("rotate-180");
  368. } else {
  369. details.style.display = "block";
  370. icon.classList.add("rotate-180");
  371. }
  372. }
  373. document.addEventListener("DOMContentLoaded", function () {
  374. const form = document.getElementById("audit-form");
  375. const resultsContainer = document.getElementById("audit-results-container");
  376. const auditTypeSelect = document.getElementById("audit-type");
  377. const usernameSelect = document.getElementById("username-filter");
  378. const startDateInput = document.getElementById("start-date");
  379. const endDateInput = document.getElementById("end-date");
  380. const startDateContainer = document.getElementById("start-date-container");
  381. const endDateContainer = document.getElementById("end-date-container");
  382. const defaultResultsHTML = `<div class="bg-white p-6 rounded-lg shadow-lg min-h-[300px] flex items-center justify-center">
  383. <div class="text-center text-gray-500 py-10">
  384. <i class="fas fa-clipboard-list text-5xl mb-4 text-gray-300"></i>
  385. <h3 class="text-xl font-semibold">Seleccione los filtros y genere un reporte</h3>
  386. <p class="mt-2">Los resultados de su auditoría aparecerán aquí.</p>
  387. </div>
  388. </div>`;
  389. resultsContainer.innerHTML = defaultResultsHTML;
  390. const conditionalInputs = {
  391. user: document.getElementById("user-filter-container"),
  392. user_optional: document.getElementById("user-filter-container"),
  393. keyword: document.getElementById("keyword-input-container"),
  394. ip: document.getElementById("ip-input-container"),
  395. response_code: document.getElementById("response-code-input-container"),
  396. social_media: document.getElementById("social-media-input-container"),
  397. };
  398. const getLocalDateString = () => {
  399. const today = new Date();
  400. const year = today.getFullYear();
  401. const month = String(today.getMonth() + 1).padStart(2, "0");
  402. const day = String(today.getDate()).padStart(2, "0");
  403. return `${year}-${month}-${day}`;
  404. };
  405. const todayString = getLocalDateString();
  406. startDateInput.value = todayString;
  407. endDateInput.value = todayString;
  408. // Variables para el buscador de usuarios
  409. let allUsers = [];
  410. let filteredUsers = [];
  411. let selectedUserIndex = -1;
  412. const userSearchInput = document.getElementById("user-search-input");
  413. const userDropdown = document.getElementById("user-dropdown");
  414. const userOptionsContainer = document.getElementById(
  415. "user-options-container"
  416. );
  417. const usernameFilterSelect = document.getElementById("username-filter");
  418. // Función para renderizar las opciones de usuarios
  419. function renderUserOptions(users, searchTerm = "") {
  420. userOptionsContainer.innerHTML = "";
  421. // Agregar opción "Todos" si no hay término de búsqueda
  422. if (!searchTerm) {
  423. const allOption = document.createElement("div");
  424. allOption.className =
  425. "px-3 py-2 hover:bg-blue-50 cursor-pointer text-gray-700 border-b border-gray-100";
  426. allOption.textContent = "-- Todos --";
  427. allOption.dataset.value = "";
  428. allOption.addEventListener("click", () =>
  429. selectUser("", "-- Todos --")
  430. );
  431. userOptionsContainer.appendChild(allOption);
  432. }
  433. users.forEach((user, index) => {
  434. const option = document.createElement("div");
  435. option.className =
  436. "px-3 py-2 hover:bg-blue-50 cursor-pointer text-gray-700";
  437. option.textContent = user;
  438. option.dataset.value = user;
  439. option.dataset.index = index;
  440. option.addEventListener("click", () => selectUser(user, user));
  441. // Resaltar texto coincidente
  442. if (searchTerm) {
  443. const regex = new RegExp(`(${searchTerm})`, "gi");
  444. option.innerHTML = user.replace(
  445. regex,
  446. '<mark class="bg-yellow-200">$1</mark>'
  447. );
  448. }
  449. userOptionsContainer.appendChild(option);
  450. });
  451. if (users.length === 0 && searchTerm) {
  452. const noResults = document.createElement("div");
  453. noResults.className = "px-3 py-2 text-gray-500 italic";
  454. noResults.textContent = "No se encontraron usuarios";
  455. userOptionsContainer.appendChild(noResults);
  456. }
  457. }
  458. // Función para seleccionar un usuario
  459. function selectUser(value, displayText) {
  460. userSearchInput.value = displayText;
  461. usernameFilterSelect.value = value;
  462. userDropdown.classList.add("hidden");
  463. selectedUserIndex = -1;
  464. }
  465. // Función para filtrar usuarios
  466. function filterUsers(searchTerm) {
  467. if (!searchTerm) {
  468. filteredUsers = [...allUsers];
  469. } else {
  470. filteredUsers = allUsers.filter((user) =>
  471. user.toLowerCase().includes(searchTerm.toLowerCase())
  472. );
  473. }
  474. renderUserOptions(filteredUsers, searchTerm);
  475. }
  476. // Event listeners para el buscador de usuarios
  477. userSearchInput.addEventListener("input", function (e) {
  478. const searchTerm = e.target.value;
  479. filterUsers(searchTerm);
  480. userDropdown.classList.remove("hidden");
  481. selectedUserIndex = -1;
  482. });
  483. userSearchInput.addEventListener("focus", function () {
  484. filterUsers(userSearchInput.value);
  485. userDropdown.classList.remove("hidden");
  486. });
  487. userSearchInput.addEventListener("keydown", function (e) {
  488. const options = userOptionsContainer.querySelectorAll("[data-value]");
  489. if (e.key === "ArrowDown") {
  490. e.preventDefault();
  491. selectedUserIndex = Math.min(selectedUserIndex + 1, options.length - 1);
  492. updateSelectedOption(options);
  493. } else if (e.key === "ArrowUp") {
  494. e.preventDefault();
  495. selectedUserIndex = Math.max(selectedUserIndex - 1, -1);
  496. updateSelectedOption(options);
  497. } else if (e.key === "Enter") {
  498. e.preventDefault();
  499. if (selectedUserIndex >= 0 && options[selectedUserIndex]) {
  500. const selectedOption = options[selectedUserIndex];
  501. selectUser(selectedOption.dataset.value, selectedOption.textContent);
  502. }
  503. } else if (e.key === "Escape") {
  504. userDropdown.classList.add("hidden");
  505. selectedUserIndex = -1;
  506. }
  507. });
  508. function updateSelectedOption(options) {
  509. options.forEach((option, index) => {
  510. option.classList.toggle("bg-blue-100", index === selectedUserIndex);
  511. });
  512. }
  513. // Cerrar dropdown al hacer clic fuera
  514. document.addEventListener("click", function (e) {
  515. if (
  516. !userSearchInput.contains(e.target) &&
  517. !userDropdown.contains(e.target)
  518. ) {
  519. userDropdown.classList.add("hidden");
  520. selectedUserIndex = -1;
  521. }
  522. });
  523. fetch("/api/all-users")
  524. .then((response) => response.json())
  525. .then((users) => {
  526. allUsers = users;
  527. filteredUsers = [...users];
  528. // Llenar el select oculto para compatibilidad
  529. users.forEach((user) => {
  530. const option = document.createElement("option");
  531. option.value = user;
  532. option.textContent = user;
  533. usernameFilterSelect.appendChild(option);
  534. });
  535. renderUserOptions(filteredUsers);
  536. /* toastr.success(`${users.length} usuarios cargados`, "Usuarios disponibles", {
  537. "timeOut": 2000 */
  538. })
  539. .catch((error) => {
  540. toastr.error("Error al cargar la lista de usuarios", "Error de carga");
  541. });
  542. function toggleConditionalInputs() {
  543. resultsContainer.innerHTML = defaultResultsHTML;
  544. Object.values(conditionalInputs).forEach((el) => {
  545. if (el) el.style.display = "none";
  546. });
  547. const selectedOption =
  548. auditTypeSelect.options[auditTypeSelect.selectedIndex];
  549. const auditType = selectedOption.value;
  550. const required = selectedOption.dataset.requires?.split(",") || [];
  551. required.forEach((inputId) => {
  552. if (conditionalInputs[inputId]) {
  553. conditionalInputs[inputId].style.display = "block";
  554. }
  555. });
  556. const userSelectContainer = conditionalInputs.user;
  557. const defaultUserOption = userSelectContainer.querySelector(
  558. 'select option[value=""]'
  559. );
  560. if (auditType === "daily_activity") {
  561. endDateContainer.style.display = "none";
  562. startDateContainer.querySelector("label").textContent = "Fecha";
  563. } else {
  564. endDateContainer.style.display = "block";
  565. startDateContainer.querySelector("label").textContent =
  566. "Fecha de Inicio";
  567. }
  568. if (auditType === "user_summary" || auditType === "daily_activity") {
  569. userSearchInput.placeholder = "Seleccionar usuario...";
  570. userSearchInput.value = "";
  571. usernameFilterSelect.value = "";
  572. userSearchInput.disabled = false;
  573. } else {
  574. userSearchInput.placeholder = "Buscar usuario... (Opcional)";
  575. userSearchInput.value = "-- Todos --";
  576. usernameFilterSelect.value = "";
  577. userSearchInput.disabled = false;
  578. }
  579. }
  580. auditTypeSelect.addEventListener("change", toggleConditionalInputs);
  581. toggleConditionalInputs();
  582. const socialMediaChipsContainer =
  583. document.getElementById("social-media-chips");
  584. socialMediaChipsContainer.addEventListener("click", function (event) {
  585. if (event.target.classList.contains("social-chip")) {
  586. event.target.classList.toggle("selected");
  587. }
  588. });
  589. // Función para restaurar el botón de envío a su estado original
  590. function restoreSubmitButton() {
  591. const submitButton = form.querySelector('button[type="submit"]');
  592. const buttonIcon = submitButton.querySelector("i");
  593. submitButton.disabled = false;
  594. submitButton.classList.remove("opacity-50", "cursor-not-allowed");
  595. submitButton.classList.add("hover:bg-blue-700", "hover:shadow-xl");
  596. // Restaurar el icono y texto original
  597. buttonIcon.className = "fas fa-play mr-2";
  598. submitButton.innerHTML =
  599. '<i class="fas fa-play mr-2"></i>Generar Reporte';
  600. }
  601. form.addEventListener("submit", function (event) {
  602. event.preventDefault();
  603. const formData = new FormData(form);
  604. const data = Object.fromEntries(formData.entries());
  605. const selectedChips = socialMediaChipsContainer.querySelectorAll(
  606. ".social-chip.selected"
  607. );
  608. data.social_media_sites = Array.from(selectedChips).map(
  609. (chip) => chip.dataset.value
  610. );
  611. const selectedOption =
  612. auditTypeSelect.options[auditTypeSelect.selectedIndex];
  613. const requiredInputs = selectedOption.dataset.requires?.split(",") || [];
  614. if (requiredInputs.includes("user") && !usernameFilterSelect.value) {
  615. toastr.error("Por favor, seleccione un usuario.", "Campo requerido");
  616. return;
  617. }
  618. if (requiredInputs.includes("keyword") && !data.keyword) {
  619. toastr.error(
  620. "Por favor, ingrese una palabra clave.",
  621. "Campo requerido"
  622. );
  623. return;
  624. }
  625. if (requiredInputs.includes("ip") && !data.ip_address) {
  626. toastr.error("Por favor, ingrese una dirección IP.", "Campo requerido");
  627. return;
  628. }
  629. if (requiredInputs.includes("response_code") && !data.response_code) {
  630. toastr.error(
  631. "Por favor, seleccione un código de respuesta.",
  632. "Campo requerido"
  633. );
  634. return;
  635. }
  636. if (
  637. requiredInputs.includes("social_media") &&
  638. data.social_media_sites.length === 0
  639. ) {
  640. toastr.error(
  641. "Por favor, seleccione al menos una red social.",
  642. "Campo requerido"
  643. );
  644. return;
  645. }
  646. /* toastr.info("Generando reporte, por favor espere...", "Procesando", {
  647. "timeOut": 0,
  648. "extendedTimeOut": 0,
  649. "tapToDismiss": false,
  650. "closeButton": false
  651. }); */
  652. // Deshabilitar el botón y cambiar su apariencia
  653. const submitButton = form.querySelector('button[type="submit"]');
  654. const buttonIcon = submitButton.querySelector("i");
  655. const buttonText =
  656. submitButton.querySelector("span") || submitButton.lastChild;
  657. submitButton.disabled = true;
  658. submitButton.classList.add("opacity-50", "cursor-not-allowed");
  659. submitButton.classList.remove("hover:bg-blue-700", "hover:shadow-xl");
  660. // Cambiar el icono a spinner
  661. buttonIcon.className = "fas fa-spinner fa-spin mr-2";
  662. // Cambiar el texto del botón
  663. if (buttonText.nodeType === Node.TEXT_NODE) {
  664. buttonText.textContent = "Generando Reporte...";
  665. } else {
  666. submitButton.innerHTML =
  667. '<i class="fas fa-spinner fa-spin mr-2"></i>Generando Reporte...';
  668. }
  669. resultsContainer.innerHTML = `
  670. <div class="bg-white p-6 rounded-lg shadow-lg min-h-[300px] flex items-center justify-center">
  671. <div class="text-center text-gray-500 py-10">
  672. <i class="fas fa-spinner fa-spin text-5xl mb-4 text-blue-500"></i>
  673. <h3 class="text-xl font-semibold">Generando reporte...</h3>
  674. </div>
  675. </div>`;
  676. fetch("/api/run-audit", {
  677. method: "POST",
  678. headers: { "Content-Type": "application/json" },
  679. body: JSON.stringify(data),
  680. })
  681. .then((response) => response.json())
  682. .then((result) => {
  683. toastr.clear();
  684. restoreSubmitButton();
  685. if (result.error) {
  686. toastr.error(result.error, "Error en la auditoría");
  687. } else {
  688. toastr.success(
  689. "Reporte generado exitosamente",
  690. "Auditoría completada"
  691. );
  692. }
  693. renderResults(data.audit_type, result, data);
  694. })
  695. .catch((error) => {
  696. toastr.clear();
  697. restoreSubmitButton();
  698. toastr.error("Error de conexión con el servidor", "Error de red");
  699. resultsContainer.innerHTML = `<div class="bg-white p-6 rounded-lg shadow-lg"><div class="text-center text-red-500 py-10"><strong>Error de red o del servidor:</strong> ${error}</div></div>`;
  700. });
  701. });
  702. function renderResults(auditType, data, formData) {
  703. let html = "";
  704. if (data.error) {
  705. html = `<div class="bg-white p-6 rounded-lg shadow-lg"><div class="text-center text-red-500 py-10"><strong>Error:</strong> ${data.error}</div></div>`;
  706. } else {
  707. if (auditType === "user_summary") {
  708. html = renderUserSummary(data);
  709. } else if (auditType === "top_users_data") {
  710. html = renderTopUsers(data);
  711. } else if (auditType === "daily_activity") {
  712. const user = formData.username;
  713. const date = formData.start_date;
  714. let title = `Distribución de Peticiones para '${user}' el ${date}`;
  715. if (data.total_requests > 0) {
  716. html = `<div class="bg-white p-6 rounded-lg shadow-lg">
  717. <h2 class="text-2xl font-bold mb-2">${title}</h2>
  718. <p class="text-gray-600 mb-4">Total de Peticiones en el día: <span class="font-bold text-blue-600">${data.total_requests.toLocaleString()}</span></p>
  719. <canvas id="daily-activity-chart"></canvas>
  720. </div>`;
  721. } else {
  722. html = `<div class="bg-white p-6 rounded-lg shadow-lg"><h2 class="text-2xl font-bold mb-4">${title}</h2><p class="text-gray-500">No se encontraron peticiones para la fecha y usuario seleccionado.</p></div>`;
  723. }
  724. } else if (
  725. [
  726. "keyword_search",
  727. "ip_activity",
  728. "response_code_search",
  729. "social_media_activity",
  730. ].includes(auditType)
  731. ) {
  732. let title = "";
  733. if (auditType === "keyword_search") {
  734. const user = formData.username || "Todos";
  735. title = `Resultados para la palabra clave "${formData.keyword}" para: ${user}`;
  736. } else if (auditType === "ip_activity") {
  737. title = `Resultados de Búsqueda para la IP: ${formData.ip_address}`;
  738. } else if (auditType === "response_code_search") {
  739. const user = formData.username || "Todos";
  740. title = `Resultados por Código de Respuesta ${formData.response_code} para: ${user}`;
  741. } else if (auditType === "social_media_activity") {
  742. const user = formData.username || "Todos";
  743. const sites = formData.social_media_sites.join(", ");
  744. title = `Actividad en Redes Sociales (${sites}) para: ${user}`;
  745. }
  746. html = renderNestedAccordionResults(title, data.results);
  747. } else {
  748. html =
  749. '<div class="bg-white p-6 rounded-lg shadow-lg"><p>Tipo de reporte no reconocido.</p></div>';
  750. }
  751. }
  752. resultsContainer.innerHTML = html;
  753. const dailyActivityChartCanvas = document.getElementById(
  754. "daily-activity-chart"
  755. );
  756. if (dailyActivityChartCanvas && data.hourly_activity) {
  757. renderDailyActivityChart(
  758. dailyActivityChartCanvas,
  759. data.hourly_activity
  760. );
  761. }
  762. const domainChartCanvas = document.getElementById("domain-chart");
  763. if (domainChartCanvas && data.top_domains) {
  764. renderDomainChart(domainChartCanvas, data.top_domains);
  765. }
  766. const responseChartCanvas = document.getElementById("response-chart");
  767. if (responseChartCanvas && data.response_summary) {
  768. renderResponseChart(responseChartCanvas, data.response_summary);
  769. }
  770. }
  771. function formatBytes(bytes, decimals = 2) {
  772. if (!+bytes) return "0 Bytes";
  773. const k = 1024;
  774. const dm = decimals < 0 ? 0 : decimals;
  775. const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
  776. const i = Math.floor(Math.log(bytes) / Math.log(k));
  777. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
  778. }
  779. function formatTime(datetimeString) {
  780. if (!datetimeString || typeof datetimeString !== "string") {
  781. return "--";
  782. }
  783. try {
  784. const parts = datetimeString.split(" ");
  785. if (parts.length < 5) return "--";
  786. const timePart = parts[4];
  787. const [hoursStr, minutesStr, secondsStr] = timePart.split(":");
  788. let hour = parseInt(hoursStr, 10);
  789. if (isNaN(hour)) return "--";
  790. const ampm = hour >= 12 ? "PM" : "AM";
  791. hour = hour % 12;
  792. hour = hour || 12;
  793. const formattedHour = String(hour).padStart(2, "0");
  794. return `${formattedHour}:${minutesStr}:${secondsStr} ${ampm}`;
  795. } catch (error) {
  796. console.error(
  797. "Error crítico al formatear la hora:",
  798. error,
  799. "Input was:",
  800. datetimeString
  801. );
  802. return "--";
  803. }
  804. }
  805. function renderNestedAccordionResults(title, results) {
  806. if (!results || results.length === 0) {
  807. return `<div class="bg-white p-6 rounded-lg shadow-lg"><h2 class="text-2xl font-bold mb-4">${title}</h2><p class="text-gray-500">No se encontraron registros.</p></div>`;
  808. }
  809. const usersData = {};
  810. results.forEach((item) => {
  811. if (!usersData[item.username]) usersData[item.username] = {};
  812. const dateStr = `${item.log_date.substring(
  813. 0,
  814. 4
  815. )}-${item.log_date.substring(4, 6)}-${item.log_date.substring(6, 8)}`;
  816. if (!usersData[item.username][dateStr]) {
  817. usersData[item.username][dateStr] = {
  818. daily_requests: 0,
  819. daily_data: 0,
  820. activities: [],
  821. };
  822. }
  823. const dateGroup = usersData[item.username][dateStr];
  824. dateGroup.activities.push(item);
  825. dateGroup.daily_requests += Number(item.access_count) || 0;
  826. dateGroup.daily_data += Number(item.total_data) || 0;
  827. });
  828. let html = `<h2 class="text-2xl font-bold mb-4">${title}</h2>`;
  829. for (const username in usersData) {
  830. const userDataByDate = usersData[username];
  831. html += `
  832. <div class="border rounded-lg mb-3 shadow-md bg-white">
  833. <div class="bg-gray-100 p-3 flex justify-between items-center cursor-pointer hover:bg-gray-200" onclick="toggleDetails(this)">
  834. <h3 class="font-bold text-gray-800 flex items-center"><i class="fas fa-user mr-3 text-blue-600"></i>${username}</h3>
  835. <i class="fas fa-chevron-down toggle-icon transition-transform"></i>
  836. </div>
  837. <div class="user-card-details border-t border-gray-200" style="display: none;">`;
  838. const sortedDates = Object.keys(userDataByDate).sort().reverse();
  839. for (const date of sortedDates) {
  840. const dateData = userDataByDate[date];
  841. html += `<div class="border-b last:border-b-0">
  842. <div class="bg-blue-50 p-2 pl-6 flex justify-between items-center cursor-pointer hover:bg-blue-100" onclick="toggleDetails(this)">
  843. <h4 class="font-semibold text-blue-800"><i class="fas fa-calendar-alt mr-2"></i>${date}</h4>
  844. <div class="flex items-center space-x-4 text-sm">
  845. <span class="font-medium text-blue-700"><i class="fas fa-hashtag mr-1"></i>${dateData.daily_requests.toLocaleString()} Peticiones</span>
  846. <span class="font-medium text-green-700"><i class="fas fa-database mr-1"></i>${formatBytes(
  847. dateData.daily_data
  848. )}</span>
  849. <i class="fas fa-chevron-down toggle-icon transition-transform text-xs"></i>
  850. </div>
  851. </div>
  852. <div class="date-details p-3" style="display: none;">
  853. <table class="w-full text-left text-sm mt-2">
  854. <thead class="border-b-2 border-gray-300">
  855. <tr>
  856. <th class="py-1 px-2 text-center">Hora (Últ. Acceso)</th>
  857. <th class="py-1 px-2">URL</th>
  858. <th class="py-1 px-2 text-center">Intentos</th>
  859. <th class="py-1 px-2">Datos</th>
  860. </tr>
  861. </thead>
  862. <tbody class="divide-y divide-gray-100">`;
  863. const ensureProtocol = (url) =>
  864. url.startsWith("http") ? url : `http://${url}`;
  865. dateData.activities.forEach((activity) => {
  866. html += `<tr class="hover:bg-gray-50">
  867. <td class="py-1 px-2 text-center font-mono text-xs">${formatTime(
  868. activity.last_seen
  869. )}</td>
  870. <td class="py-1 px-2 truncate">
  871. <a href="${ensureProtocol(
  872. activity.url
  873. )}" target="_blank" class="text-blue-600 hover:underline" title="${
  874. activity.url
  875. }">${activity.url}</a>
  876. </td>
  877. <td class="py-1 px-2 text-center">${
  878. activity.access_count
  879. }</td>
  880. <td class="py-1 px-2">${formatBytes(
  881. activity.total_data
  882. )}</td>
  883. </tr>`;
  884. });
  885. html += `</tbody></table></div></div>`;
  886. }
  887. html += `</div></div>`;
  888. }
  889. return html;
  890. }
  891. function renderUserSummary(data) {
  892. const topDomainsHtml = data.top_domains
  893. .map(
  894. (d) =>
  895. `<li>${d.domain} <span class="font-bold">(${d.count} reqs)</span></li>`
  896. )
  897. .join("");
  898. const responseSummaryHtml = data.response_summary
  899. .slice(0, 5)
  900. .map(
  901. (r) =>
  902. `<li>${
  903. r.code
  904. }: <span class="font-bold">${r.count.toLocaleString()}</span></li>`
  905. )
  906. .join("");
  907. return `<div class="bg-white p-6 rounded-lg shadow-lg">
  908. <h2 class="text-2xl font-bold mb-4">Resumen de Actividad</h2>
  909. <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
  910. <div class="bg-blue-100 p-4 rounded-lg text-center"><div class="text-3xl font-bold">${data.total_requests.toLocaleString()}</div><div class="text-sm">Peticiones Totales</div></div>
  911. <div class="bg-green-100 p-4 rounded-lg text-center"><div class="text-3xl font-bold">${
  912. data.total_data_gb
  913. }</div><div class="text-sm">GB Consumidos</div></div>
  914. <div class="bg-gray-100 p-4 rounded-lg">
  915. <h4 class="font-semibold text-sm mb-1 text-center">Resumen de Respuestas</h4>
  916. <ul class="text-xs space-y-1">${responseSummaryHtml}</ul>
  917. </div>
  918. </div>
  919. <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
  920. <div>
  921. <h3 class="text-xl font-semibold mb-2">Top 15 Dominios Visitados</h3>
  922. <canvas id="domain-chart"></canvas>
  923. </div>
  924. <div>
  925. <h3 class="text-xl font-semibold mb-2">Distribución de Respuestas HTTP</h3>
  926. <canvas id="response-chart"></canvas>
  927. </div>
  928. </div></div>`;
  929. }
  930. function renderTopUsers(data) {
  931. const rows = data.top_users
  932. .map(
  933. (user, index) => `
  934. <tr class="hover:bg-gray-50">
  935. <td class="p-3">${index + 1}</td>
  936. <td class="p-3 font-medium">${user.username}</td>
  937. <td class="p-3 font-mono">${user.total_data_gb.toFixed(
  938. 2
  939. )} GB</td>
  940. </tr>`
  941. )
  942. .join("");
  943. return `<div class="bg-white p-6 rounded-lg shadow-lg"><h2 class="text-2xl font-bold mb-4">Top 10 Usuarios por Consumo de Datos</h2>
  944. <table class="w-full text-left">
  945. <thead class="bg-gray-100"><tr><th class="p-3">#</th><th class="p-3">Usuario</th><th class="p-3">Datos Consumidos</th></tr></thead>
  946. <tbody class="divide-y">${rows}</tbody>
  947. </table></div>`;
  948. }
  949. function renderDailyActivityChart(canvas, hourlyData) {
  950. const labels = Array.from({ length: 24 }, (_, i) => {
  951. const hour = i % 12 === 0 ? 12 : i % 12;
  952. const ampm = i < 12 ? "AM" : "PM";
  953. return `${hour} ${ampm}`;
  954. });
  955. new Chart(canvas, {
  956. type: "bar",
  957. data: {
  958. labels: labels,
  959. datasets: [
  960. {
  961. label: "Peticiones por Hora",
  962. data: hourlyData,
  963. backgroundColor: "rgba(59, 130, 246, 0.5)",
  964. borderColor: "rgba(37, 99, 235, 1)",
  965. borderWidth: 1,
  966. },
  967. ],
  968. },
  969. options: {
  970. responsive: true,
  971. scales: {
  972. x: {
  973. grid: { display: false },
  974. title: { display: true, text: "Hora del Día" },
  975. },
  976. y: {
  977. beginAtZero: true,
  978. title: { display: true, text: "Número de Peticiones" },
  979. },
  980. },
  981. plugins: {
  982. legend: { display: false },
  983. },
  984. },
  985. });
  986. }
  987. function renderDomainChart(canvas, domains) {
  988. // Genera colores equidistantes en el espectro HSL
  989. const generateColors = (count) =>
  990. Array.from(
  991. { length: count },
  992. (_, i) => `hsl(${((i * 360) / count) % 360}, 70%, 50%)`
  993. );
  994. // Configuración del gráfico
  995. const config = {
  996. type: "pie",
  997. data: {
  998. labels: domains.map((d) => d.domain),
  999. datasets: [
  1000. {
  1001. label: "Requests",
  1002. data: domains.map((d) => d.count),
  1003. backgroundColor: generateColors(domains.length),
  1004. },
  1005. ],
  1006. },
  1007. options: {
  1008. responsive: true,
  1009. plugins: {
  1010. legend: {
  1011. position: "right",
  1012. labels: {
  1013. boxWidth: 12,
  1014. font: { size: 10 },
  1015. generateLabels: (chart) => {
  1016. const { labels, datasets } = chart.data;
  1017. if (!labels.length || !datasets.length) return [];
  1018. return labels.map((label, i) => ({
  1019. text: `${label} (${datasets[0].data[i]})`,
  1020. fillStyle: datasets[0].backgroundColor[i],
  1021. strokeStyle: datasets[0].backgroundColor[i],
  1022. lineWidth: 0,
  1023. index: i,
  1024. }));
  1025. },
  1026. },
  1027. },
  1028. tooltip: {
  1029. callbacks: {
  1030. label: (context) => {
  1031. const label = context.label || "";
  1032. const value = context.raw || 0;
  1033. const total = context.dataset.data.reduce((a, b) => a + b, 0);
  1034. const percentage = Math.round((value / total) * 100);
  1035. return `${label}: ${value} (${percentage}%)`;
  1036. },
  1037. },
  1038. },
  1039. },
  1040. },
  1041. };
  1042. return new Chart(canvas, config);
  1043. }
  1044. function renderResponseChart(canvas, responses) {
  1045. // Mapeo de códigos de respuesta a colores
  1046. const getResponseColor = (code) => {
  1047. if (code >= 500) return "#DC2626"; // Error de servidor
  1048. if (code >= 400) return "#F59E0B"; // Error de cliente
  1049. if (code >= 300) return "#3B82F6"; // Redirección
  1050. if (code >= 200) return "#10B981"; // Éxito
  1051. return "#6B7280"; // Otros
  1052. };
  1053. // Configuración del gráfico
  1054. const config = {
  1055. type: "pie",
  1056. data: {
  1057. labels: responses.map((r) => `HTTP ${r.code}`),
  1058. datasets: [
  1059. {
  1060. label: "Respuestas",
  1061. data: responses.map((r) => r.count),
  1062. backgroundColor: responses.map((r) => getResponseColor(r.code)),
  1063. borderWidth: 1,
  1064. },
  1065. ],
  1066. },
  1067. options: {
  1068. responsive: true,
  1069. maintainAspectRatio: true,
  1070. plugins: {
  1071. legend: {
  1072. position: "right",
  1073. labels: {
  1074. font: {
  1075. size: 12,
  1076. },
  1077. padding: 10,
  1078. usePointStyle: true,
  1079. pointStyle: "circle",
  1080. },
  1081. },
  1082. tooltip: {
  1083. callbacks: {
  1084. label: (context) => {
  1085. const label = context.label.replace("HTTP ", "") || "";
  1086. const value = context.raw || 0;
  1087. const total = context.dataset.data.reduce((a, b) => a + b, 0);
  1088. const percentage = Math.round((value / total) * 100);
  1089. return `${label}: ${value} (${percentage}%)`;
  1090. },
  1091. },
  1092. },
  1093. },
  1094. },
  1095. };
  1096. return new Chart(canvas, config);
  1097. }
  1098. });
  1099. </script>