auditoría.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import { createApp, reactive } from 'https://unpkg.com/petite-vue?module'
  2. type Registro = {
  3. carrera: string;
  4. carrera_id: number;
  5. comentario: null;
  6. dia: string;
  7. duracion: string;
  8. duracion_id: number;
  9. estado_supervisor_id: number;
  10. facultad: string;
  11. facultad_id: number;
  12. horario_dia: number;
  13. horario_fin: string;
  14. horario_grupo: string;
  15. horario_hora: string;
  16. horario_id: number;
  17. materia: string;
  18. materia_id: number;
  19. nombre: string;
  20. periodo: string;
  21. periodo_id: number;
  22. profesor_clave: string;
  23. profesor_correo: string;
  24. profesor_grado: null;
  25. profesor_id: number;
  26. profesor_nombre: string;
  27. registro_fecha: null;
  28. registro_fecha_ideal: Date;
  29. registro_fecha_supervisor: Date;
  30. registro_id: number;
  31. registro_justificada: null;
  32. registro_retardo: null;
  33. salon: string;
  34. salon_id: number;
  35. supervisor_id: number;
  36. }
  37. type Estado = {
  38. color: string;
  39. icon: string;
  40. estado_supervisor_id: number;
  41. }
  42. type Facultad = {
  43. clave_dependencia: string;
  44. facultad_id: number;
  45. facultad_nombre: string;
  46. }
  47. type Bloque_Horario = {
  48. hora_fin: string;
  49. hora_inicio: string;
  50. id: number;
  51. selected: boolean;
  52. }
  53. type Periodo = {
  54. created_at: Date;
  55. estado_id: number;
  56. fecha_final: Date;
  57. id_periodo_sgu: number;
  58. nivel_id: number;
  59. periodo_clave: string;
  60. periodo_fecha_fin: Date;
  61. periodo_fecha_inicio: Date;
  62. periodo_id: number;
  63. periodo_nombre: string;
  64. }
  65. declare var $: any
  66. $('div.modal#cargando').modal({
  67. backdrop: 'static',
  68. keyboard: false,
  69. show: false,
  70. })
  71. const store = reactive({
  72. loading: false,
  73. perido: null as Periodo | null,
  74. current: {
  75. comentario: '',
  76. clase_vista: null,
  77. empty: '',
  78. page: 1,
  79. maxPages: 10,
  80. perPage: 10,
  81. modal_state: "Cargando datos...",
  82. justificada: null as Registro | null,
  83. fechas_clicked: false,
  84. observaciones: false,
  85. },
  86. facultades: {
  87. data: [] as Facultad[],
  88. async fetch() {
  89. this.data = [] as Facultad[]
  90. const res = await fetch('action/action_facultad.php')
  91. this.data = await res.json()
  92. },
  93. },
  94. filters: {
  95. facultad_id: null,
  96. fecha: null,
  97. fecha_inicio: null,
  98. fecha_fin: null,
  99. profesor: null,
  100. periodo_id: null,
  101. bloque_horario: null,
  102. estados: [],
  103. switchFecha: false,
  104. async switchFechas() {
  105. const periodo = await fetch('action/periodo_datos.php');
  106. const periodo_data = await periodo.json() as Periodo;
  107. if (!store.filters.switchFecha) {
  108. $('div.modal#cargando').modal('show');
  109. await store.registros.fetch()
  110. $('div.modal#cargando').modal('hide');
  111. }
  112. $(function () {
  113. store.filters.fecha_inicio = store.filters.fecha_fin = store.filters.fecha = null
  114. $("#fecha, #fecha_inicio, #fecha_fin").datepicker({
  115. minDate: new Date(`${periodo_data.periodo_fecha_inicio}:00:00:00`),
  116. maxDate: new Date(`${periodo_data.fecha_final}:00:00:00`),
  117. dateFormat: "yy-mm-dd",
  118. showAnim: "slide",
  119. beforeShowDay: (date: Date) => [(date.getDay() != 0), ""]
  120. });
  121. const fecha = $("#fecha"), inicio = $("#fecha_inicio"), fin = $("#fecha_fin")
  122. fecha.datepicker("setDate", new Date(`${periodo_data.fecha_final}:00:00:00`));
  123. inicio.on("change", function () {
  124. store.current.fechas_clicked = false;
  125. store.filters.fecha_inicio = inicio.val()
  126. fin.datepicker("option", "minDate", inicio.val());
  127. });
  128. fin.on("change", function () {
  129. store.current.fechas_clicked = false;
  130. store.filters.fecha_fin = fin.val()
  131. inicio.datepicker("option", "maxDate", fin.val());
  132. });
  133. fecha.on("change", async function () {
  134. store.filters.fecha = fecha.val()
  135. $('div.modal#cargando').modal('show');
  136. await store.registros.fetch(store.filters.fecha)
  137. $('div.modal#cargando').modal('hide');
  138. });
  139. });
  140. },
  141. async fetchByDate() {
  142. store.current.fechas_clicked = true;
  143. $('div.modal#cargando').modal('show');
  144. await store.registros.fetch(undefined, store.filters.fecha_inicio, store.filters.fecha_fin);
  145. store.current.page = 1;
  146. $('div.modal#cargando').modal('hide');
  147. }
  148. },
  149. estados: {
  150. data: [] as Estado[],
  151. async fetch() {
  152. this.data = [] as Estado[]
  153. const res = await fetch('action/action_estado_supervisor.php')
  154. this.data = await res.json()
  155. },
  156. getEstado(id: number): Estado {
  157. return this.data.find((estado: Estado) => estado.estado_supervisor_id === id) ?? {
  158. estado_color: 'dark',
  159. estado_icon: 'ing-cancelar',
  160. nombre: 'Sin registro',
  161. estado_supervisor_id: -1,
  162. }
  163. },
  164. printEstados() {
  165. if (store.filters.estados.length > 0)
  166. document.querySelector('#estados')!.innerHTML = store.filters.estados.map((estado: number) =>
  167. `<span class="mx-2 badge badge-${store.estados.getEstado(estado).estado_color}">
  168. <i class="${store.estados.getEstado(estado).estado_icon}"></i> ${store.estados.getEstado(estado).nombre}
  169. </span>`
  170. ).join('')
  171. else
  172. document.querySelector('#estados')!.innerHTML = `Todos los registros`
  173. }
  174. },
  175. bloques_horario: {
  176. data: [] as Bloque_Horario[],
  177. async fetch() {
  178. this.data = [] as Bloque_Horario[]
  179. const res = await fetch('action/action_grupo_horario.php')
  180. this.data = await res.json()
  181. if (this.data.every((bloque: Bloque_Horario) => !bloque.selected))
  182. this.data[0].selected = true
  183. },
  184. },
  185. toggle(arr: any, element: any) {
  186. const newArray = arr.includes(element) ? arr.filter((item: any) => item !== element) : [...arr, element]
  187. // if all are selected, then unselect all
  188. if (newArray.length === (this.estados.data.length + 1)) {
  189. setTimeout(() => {
  190. document.querySelectorAll('#dlAsistencia>ul>li.selected')!.forEach(element => element.classList.remove('selected'));
  191. }, 100)
  192. return []
  193. }
  194. return newArray
  195. },
  196. async justificar() {
  197. if (!store.current.justificada) return;
  198. store.current.justificada.registro_justificada = true
  199. let data: {
  200. justificador_nombre: string;
  201. justificador_clave: string;
  202. justificador_facultad: string;
  203. justificador_rol: string;
  204. registro_fecha_justificacion: Date;
  205. };
  206. try {
  207. const res = await fetch('action/justificar.php', {
  208. method: 'POST',
  209. headers: {
  210. 'Content-Type': 'application/json'
  211. },
  212. body: JSON.stringify(store.current.justificada)
  213. })
  214. data = await res.json()
  215. } catch (error) {
  216. alert('Error al justificar')
  217. store.current.justificada = store.current.clone_justificada
  218. } finally {
  219. delete store.current.clone_justificada
  220. }
  221. store.current.justificada.justificador_nombre = data.justificador_nombre
  222. store.current.justificada.justificador_clave = data.justificador_clave
  223. store.current.justificada.justificador_facultad = data.justificador_facultad
  224. store.current.justificada.justificador_rol = data.justificador_rol
  225. store.current.justificada.registro_fecha_justificacion = data.registro_fecha_justificacion
  226. },
  227. async justificarBloque(fecha: Date, bloques: Array<number>, justificacion: string) {
  228. if (bloques.length === 0) {
  229. alert('No se ha seleccionado ningún bloque');
  230. return;
  231. }
  232. if (!justificacion) {
  233. alert('No se ha ingresado ninguna observación');
  234. return;
  235. }
  236. try {
  237. const res = await fetch('action/action_justificar.php', {
  238. method: 'PUT',
  239. headers: {
  240. 'Content-Type': 'application/json'
  241. },
  242. body: JSON.stringify({
  243. fecha,
  244. bloques,
  245. justificacion,
  246. })
  247. })
  248. const resData = await res.json();
  249. if (resData.status === 'success') {
  250. alert('Se ha justificado el bloque');
  251. store.current.modal_state = 'Cargando datos...';
  252. $('div.modal#cargando').modal('show');
  253. await store.registros.fetch();
  254. $('div.modal#cargando').modal('hide');
  255. } else {
  256. alert('No se ha podido justificar el bloque');
  257. }
  258. } catch (error) {
  259. alert('Error al justificar');
  260. }
  261. },
  262. registros: {
  263. data: [] as Registro[],
  264. async fetch(fecha?: Date, fecha_inicio?: Date, fecha_fin?: Date) {
  265. // if (!store.filters.facultad_id || !store.filters.periodo_id) return
  266. this.loading = true
  267. this.data = [] as Registro[]
  268. const params = {
  269. facultad_id: 19,
  270. periodo_id: 2,
  271. }
  272. if (fecha) params['fecha'] = fecha
  273. if (fecha_inicio) params['fecha_inicio'] = fecha_inicio
  274. if (fecha_fin) params['fecha_fin'] = fecha_fin
  275. const paramsUrl = new URLSearchParams(params as any).toString()
  276. try {
  277. const res = await fetch(`action/action_auditoria.php?${paramsUrl}`, {
  278. method: 'GET',
  279. })
  280. this.data = await res.json()
  281. } catch (error) {
  282. alert('Error al cargar los datos')
  283. }
  284. this.loading = false
  285. store.current.page = 1
  286. },
  287. invertir() {
  288. this.data = this.data.reverse()
  289. },
  290. mostrarComentario(registro_id: number) {
  291. const registro = this.data.find((registro: Registro) => registro.registro_id === registro_id)
  292. store.current.comentario = registro.comentario
  293. $('#ver-comentario').modal('show')
  294. },
  295. get relevant() {
  296. /*
  297. facultad_id: null,
  298. fecha: null,
  299. fecha_inicio: null,
  300. fecha_fin: null,
  301. profesor: null,
  302. asistencia: null,
  303. estado_id: null,
  304. if one of the filters is null, then it is not relevant
  305. */
  306. const filters = Object.keys(store.filters).filter((filtro) => store.filters[filtro] !== null || store.filters[filtro]?.length > 0)
  307. return this.data.filter((registro: Registro) => {
  308. return filters.every((filtro) => {
  309. switch (filtro) {
  310. case 'fecha':
  311. return registro.registro_fecha_ideal === store.filters[filtro];
  312. case 'fecha_inicio':
  313. return registro.registro_fecha_ideal >= store.filters[filtro];
  314. case 'fecha_fin':
  315. return registro.registro_fecha_ideal <= store.filters[filtro];
  316. case 'profesor':
  317. const textoFiltro = store.filters[filtro].toLowerCase();
  318. if (/^\([^)]+\)\s[\s\S]+$/.test(textoFiltro)) {
  319. const clave = registro.profesor_clave.toLowerCase();
  320. const filtroClave = textoFiltro.match(/\((.*?)\)/)?.[1];
  321. // console.log(clave, filtroClave);
  322. return clave.includes(filtroClave);
  323. } else {
  324. const nombre = registro.profesor_nombre.toLowerCase();
  325. return nombre.includes(textoFiltro);
  326. }
  327. case 'facultad_id':
  328. return registro.facultad_id === store.filters[filtro];
  329. case 'estados':
  330. if (store.filters[filtro].length === 0) return true;
  331. else if (store.filters[filtro].includes(-1) && registro.estado_supervisor_id === null) return true;
  332. return store.filters[filtro].includes(registro.estado_supervisor_id);
  333. case 'bloque_horario':
  334. const bloque = store.bloques_horario.data.find((bloque: Bloque_Horario) => bloque.id === store.filters[filtro]) as Bloque_Horario;
  335. return registro.horario_hora < bloque.hora_fin && registro.horario_fin > bloque.hora_inicio;
  336. default: return true;
  337. }
  338. })
  339. })
  340. },
  341. async descargar() {
  342. store.current.modal_state = 'Generando reporte en Excel...'
  343. $('div.modal#cargando').modal('show');
  344. this.loading = true;
  345. if (this.relevant.length === 0) return;
  346. try {
  347. const res = await fetch('export/supervisor_excel.php', {
  348. method: 'POST',
  349. headers: {
  350. 'Content-Type': 'application/json'
  351. },
  352. body: JSON.stringify(this.relevant)
  353. });
  354. const blob = await res.blob();
  355. (window as any).saveAs(blob, `auditoria_${new Date().toISOString().slice(0, 10)}.xlsx`);
  356. } catch (error) {
  357. if (error.response && error.response.status === 413) {
  358. alert('Your request is too large! Please reduce the data size and try again.');
  359. } else {
  360. alert('An error occurred: ' + error.message);
  361. }
  362. }
  363. finally {
  364. $('#cargando').modal('hide');
  365. this.loading = false;
  366. }
  367. },
  368. loading: false,
  369. get pages() {
  370. return Math.ceil(this.relevant.length / store.current.perPage)
  371. }
  372. },
  373. })
  374. type Profesor = {
  375. profesor_id: number;
  376. profesor_nombre: string;
  377. profesor_correo: string;
  378. profesor_clave: string;
  379. profesor_grado: string;
  380. }
  381. createApp({
  382. store,
  383. messages: [] as Array<{ title: string, text: string, type: string, timestamp: string }>,
  384. get clase_vista() {
  385. return store.current.clase_vista
  386. },
  387. set_justificar(horario_id: Number, profesor_id: Number, registro_fecha_ideal: Date) {
  388. store.current.justificada = store.registros.relevant.find((registro: Registro) => registro.horario_id === horario_id && registro.profesor_id === profesor_id && registro.registro_fecha_ideal === registro_fecha_ideal)
  389. store.current.clone_justificada = JSON.parse(JSON.stringify(store.current.justificada))
  390. store.current.observaciones = false
  391. },
  392. cancelar_justificacion() {
  393. Object.assign(store.current.justificada, store.current.clone_justificada)
  394. delete store.current.clone_justificada
  395. },
  396. profesores: [] as Profesor[],
  397. async mounted() {
  398. $('div.modal#cargando').modal('show');
  399. try {
  400. // await store.registros.fetch()
  401. await store.facultades.fetch()
  402. await store.estados.fetch()
  403. await store.bloques_horario.fetch()
  404. await store.filters.switchFechas();
  405. store.periodo = await fetch('action/periodo_datos.php').then(res => res.json()) as Periodo;
  406. this.profesores = await (await fetch('action/action_profesor.php')).json() as Profesor[];
  407. this.messages.push({ title: 'Datos cargados', text: 'Los datos se han cargado correctamente', type: 'success', timestamp: new Date() })
  408. } catch (error) {
  409. this.messages.push({ title: 'Error al cargar datos', text: 'No se pudieron cargar los datos', type: 'danger', timestamp: new Date() })
  410. }
  411. finally {
  412. $('div.modal#cargando').modal('hide');
  413. }
  414. }
  415. }).mount('#app')