import { Component, ViewChild, AfterViewInit, OnInit } from '@angular/core'; import { MatPaginator } from '@angular/material/paginator'; import { MatTableDataSource } from '@angular/material/table'; import { Router } from '@angular/router'; import { MatDialog } from '@angular/material/dialog'; import { MatSnackBar } from '@angular/material/snack-bar'; import { AlertaComponent } from '../../resources/dialogos/alerta/alerta.component'; import { MESMHSService } from '../../../services/mes/mesmhs/mesmhs.service'; import { MESMHSFORMComponent } from './mesmhs-form/mesmhs-form.component'; import { MESMHSFORMDAYSComponent } from './mesmhs-form-days/mesmhs-form-days.component'; import { IAMService } from '../../../services/iam/iam.service'; import { USERInterface } from '../../../interfaces/user-interface'; import { ENCService } from 'src/app/services/enc/enc.service'; import { MCOMAUService } from 'src/app/services/mco/mcomau/mcomau.service'; @Component({ selector: 'app-mesmhs', templateUrl: './mesmhs.component.html', styleUrls: ['./mesmhs.component.css'], }) export class MESMHSComponent implements AfterViewInit { loading: Boolean = true; disabled = false; usuario_session: USERInterface = {} as USERInterface; hide: boolean = false; solicitudes: any[] = []; historial_admin: any[] = []; solicitud: any; select_value: string = ''; data_empty = false; displayedColumns: string[] = []; dataSource = new MatTableDataSource(this.solicitudes); subordinados: any; isAdmin = false; today = new Date(); @ViewChild(MatPaginator) paginator!: MatPaginator; constructor( public dialog: MatDialog, private _mesmhsService: MESMHSService, private _encService: ENCService, private _snackBar: MatSnackBar, private _mcomauService: MCOMAUService, private _iamService: IAMService ) { this.usuario_session = JSON.parse(localStorage.getItem('TIMUSERENC')!); this.isAdmin = this._encService.desencriptar(JSON.parse(localStorage.getItem('TIMUSERENC')!).PERFIL) == 'Administrador'; if (this.isAdmin) { this.displayedColumns = [ 'no', 'fecha_inicial', 'fecha_final', 'estatus', 'periodovacacional', 'id_usuario', 'agregarFecha', 'detalles' ] } else { this.displayedColumns = [ 'no', 'fecha_inicial', 'fecha_final', 'estatus', 'periodovacacional', 'id_usuario', 'detalles' ] } } ngAfterViewInit(): void { this.obtenerHistorialPorNumero( this._encService.desencriptar(this.usuario_session.IDUSUARIO) ); if (this.isAdmin) { this.cargarSubordinadosAdmin(); } else { this.cargarSubordiandos(); } } OnInit() { this.dataSource.data = []; } applyFilter(filterValue: any) { this.dataSource.filter = filterValue.target.value.trim().toLowerCase(); } obtenerHistorialPorNumero(numero_empleado: string) { this.loading = true; this._mesmhsService.obtenerHistorial(numero_empleado).subscribe( (res) => { if (res.status == 'Token is Expired') { this._iamService.logout(); this.snackAlert('Sesión expirada. Vuelva a iniciar sesión'); } else if (!res.status && res.response.length > 0) { this.loading = false; this.dataSource.data = res.response; this.historial_admin = res.response; this.cargarTabla(res.response); } else { this.solicitudes = []; this.snackAlert( res.response.length > 0 ? res.msg : 'No hay datos para mostrar'); this.data_empty = true; } this.loading = false; }, (error) => { if (!error.ok) { this.snackAlert('Ocurrió un error inesperado'); } if (error.error.msg != undefined) { this.snackAlert(error.error.msg); } if (error.status == 408) { this.snackAlert('Conexion lenta'); } } ); } obtenerHistorialSubordinado(numero_empleado: string) { this._mesmhsService.obtenerHistorial(numero_empleado).subscribe( (res) => { if (res.status == 'Token is Expired') { this._iamService.logout(); this.snackAlert('Sesión expirada. Vuelva a iniciar sesión'); } else if (!res.status && res.response.length > 0) { let usuarios_repetidos_removidos = res.response.filter( (element: any) => element.IDUSUARIO == numero_empleado ); this.loading = false; this.dataSource.data = usuarios_repetidos_removidos; this.data_empty = false; this.cargarTabla(usuarios_repetidos_removidos); } else { this.solicitudes = []; this.snackAlert( res.response.length > 0 ? res.msg : 'No hay datos para mostrar'); this.data_empty = true; } this.loading = false; }, (error) => { if (!error.ok) { this.snackAlert('Ocurrió un error inesperado'); } if (error.error.msg != undefined) { this.snackAlert(error.error.msg); } if (error.status == 408) { this.snackAlert('Conexion lenta'); } } ); } obtenerMiHistorial() { this.loading = true; this._mesmhsService.obtenerHistorial(this._encService.desencriptar(this.usuario_session.IDUSUARIO)).subscribe( (res) => { if (res.status == 'Token is Expired') { this._iamService.logout(); this.snackAlert('Sesión expirada. Vuelva a iniciar sesión'); } else if (!res.status && res.response.length > 0) { let mi_historial = res.response.filter( (element: any) => element.IDUSUARIO == this._encService.desencriptar(this.usuario_session.IDUSUARIO) ); this.dataSource.data = mi_historial; this.cargarTabla(mi_historial); } else { this.snackAlert( res.response.length > 0 ? res.msg : 'No hay datos para mostrar'); this.data_empty = true; } this.loading = false; }, (error) => { if (!error.ok) { this.snackAlert('Ocurrió un error inesperado'); } if (error.error.msg != undefined) { this.snackAlert(error.error.msg); } if (error.status == 408) { this.snackAlert('Conexion lenta'); } } ); } obtenerTodosHistorial() { this.loading = true; this._mesmhsService.obtenerHistorial( this._encService.desencriptar(this.usuario_session.IDUSUARIO) ) .subscribe( (res) => { if (res.status == 'Token is Expired') { this._iamService.logout(); this.snackAlert('Sesión expirada. Vuelva a iniciar sesión'); } else if (!res.status && res.response.length > 0) { this.dataSource.data = res.response; this.data_empty = false; console.log(this.dataSource.data); this.cargarTabla(res.response); } else { this.snackAlert( res.response.length > 0 ? res.msg : 'No hay datos para mostrar'); this.data_empty = true; } this.loading = false; }, (error) => { if (!error.ok) { this.snackAlert('Ocurrió un error inesperado'); } if (error.error.msg != undefined) { this.snackAlert(error.error.msg); } if (error.status == 408) { this.snackAlert('Conexion lenta'); } } ); } private async cargarSubordinadosAdmin() { const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); await sleep(1000); let usuarios = this.historial_admin; var hash: any = {}; usuarios = usuarios.filter(function (current) { var exists = !hash[current.IDUSUARIO]; hash[current.IDUSUARIO] = true; return exists; }); let arr_user: any[] = []; usuarios.forEach((element) => { if ( element.IDUSUARIO != this._encService.desencriptar(this.usuario_session.IDUSUARIO) ) { arr_user.push(element); } }); this.subordinados = arr_user; } private cargarSubordiandos() { this._mesmhsService.obtenerSubordinados( this._encService.desencriptar(this.usuario_session.IDUSUARIO) ).subscribe( (res) => { if (res.status == 'Token is Expired') { this._iamService.logout(); this.snackAlert('Sesión expirada. Vuelva a iniciar sesión'); } else if (!res.status) { this.subordinados = res; } else { this.snackAlert( res.response.length > 0 ? res.msg : 'No hay datos para mostrar'); this.data_empty = true; } }, (error) => { if (!error.ok) { this.snackAlert('Ocurrió un error inesperado'); } if (error.error.msg != undefined) { this.snackAlert(error.error.msg); } if (error.status == 408) { this.snackAlert('Conexion lenta'); } } ); } private formato(fecha: string) { let fechaAux = fecha.split('-'); return `${fechaAux[2]}-${fechaAux[1]}-${fechaAux[0]}`; } private formatDate(date: Date) { var d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return [year, month, day].join('-'); } private cargarTabla(solicitudes:any) { this.solicitudes = solicitudes; this.dataSource = new MatTableDataSource(this.solicitudes); this.dataSource.filterPredicate = function (data, filter: string): boolean { return ( data.FECHAINICIAL.toString().toLowerCase().includes(filter) || data.FECHAFINAL.toString().toLowerCase().includes(filter) || data.ESTATUS.toLowerCase().includes(filter) || data.PERIODOVACACIONAL.toLowerCase().includes(filter) || data.IDUSUARIO.toLowerCase().includes(filter) ); }; this.dataSource.paginator = this.paginator; this.paginator._intl.itemsPerPageLabel = 'Datos por página'; this.paginator._intl.firstPageLabel = 'Primera Página'; this.paginator._intl.lastPageLabel = 'Últmina Página'; this.paginator._intl.nextPageLabel = 'Siguiente Página'; this.paginator._intl.previousPageLabel = 'Anterior Página'; this.mapearTabla(); } private mapearTabla() { this.solicitudes.map( ( solicitud: any ) => { if (solicitud.PERIODOVACACIONAL == null) { solicitud.PERIODOVACACIONAL = 'N/A'; } else { solicitud.PERIODOVACACIONAL = this.formatoFechaPeriodo(solicitud.PERIODOVACACIONAL); } solicitud.FECHAINICIAL = this.formato(solicitud.FECHAINICIAL); solicitud.FECHAFINAL = this.formato(solicitud.FECHAFINAL); return solicitud; }); } validatedDateNow(element:any) { let finalDate = this.getDateWithString(this.dateFormat(element.FECHAFINAL)); if (element.ESTATUS !== 'Aprobado' && finalDate.getTime() > this.today.getTime()) { return false; } return true; } openDialogForm(item: any) { let dataAction = { action: 'Detalles solicitud', item: item, }; this.dialog.open(MESMHSFORMComponent, { data: dataAction, }); } openDialogAddDays(item: any) { let dataAction = { action: 'Detalles solicitud', item: item, }; this.dialog.open(MESMHSFORMDAYSComponent, { data: dataAction, }); } private getDateWithString(fecha: string) { let fechaAux = fecha.split('-'); return new Date(parseInt(fechaAux[0]), parseInt(fechaAux[1]) - 1, parseInt(fechaAux[2])); } private dateFormat(fecha: string) { let fechaAux = fecha.split('-'); return `${fechaAux[2]}-${fechaAux[1]}-${fechaAux[0]}`; } obtenerIDUsuario(item: any) { let arr1 = item.split('('); let IDUsuario1 = arr1[1].split(')'); return IDUsuario1[0]; } formatoFechaPeriodo(item: any) { let arrPeriodoVacacional = []; let fechaPeriodo = item.split('|'); arrPeriodoVacacional.push( 'De ' + this.formato(fechaPeriodo[0]) + ' a ' + this.formato(fechaPeriodo[1]) ); return arrPeriodoVacacional; } obtenerDetalleSolicitud(item: any) { this._mesmhsService.obtenerDetalleSolicitud(item.IDSOLICITUD).subscribe((res) => { this.solicitud = res; this.openDialogForm(this.solicitud); }, error => { if (!error.ok) { this.snackAlert('Ocurrió un error inesperado'); } if (error.error.msg != undefined) { this.snackAlert(error.error.msg); } if (error.status == 408) { this.snackAlert('Conexion lenta'); } }); } private snackAlert(mensaje: string) { this._snackBar.open(mensaje, 'Cerrar', { duration: 4000, }); } }