Untitled
unknown
typescript
a year ago
7.1 kB
0
Indexable
import { Component, Inject, OnInit, ViewChild } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { Util } from '@core/utils/util'; import { ECompania } from '@models/enum/compania.enum'; import { ParametroEnum } from '@models/enum/parametro.enum'; import { TipoDenuncianteEnum } from '@models/enum/tipo-denunciante.enum'; import { ParametroModel } from '@models/parametro.model'; import { LoginRequestModel } from '@models/request/login-request.model'; import { ResponseEntityModel } from '@models/response-entity.model'; import { AuthService } from '@services/auth-service'; import { ParametroService } from '@services/parametro.service'; import { StorageService } from '@services/storage-service'; import { OnExecuteData, OnExecuteErrorData } from 'ng-recaptcha'; import { environment } from 'src/environments/environment'; import { LoginRepresentanteComponent } from '../login-representante/login-representante.component'; import { RecaptchaV3Component } from '../recaptcha-v3/recaptcha-v3.component'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm: FormGroup; intentos: number = 0; hideOTP: boolean = true; isShowPassword : boolean = false; dataUrl: any; @ViewChild(RecaptchaV3Component) captchaComponent: RecaptchaV3Component; public readonly executionLog: Array<OnExecuteData | OnExecuteErrorData> = []; recuperarClave: string = ''; registro: string = ''; constructor(public dialogRef: MatDialogRef<LoginComponent>, private formBuilder: FormBuilder, private _authService: AuthService, private _parametroService: ParametroService, private _storageService: StorageService, private _modalDialog: MatDialog, @Inject(MAT_DIALOG_DATA) public data: any) { this.dataUrl = data; } ngOnInit(): void { sessionStorage.clear(); this.loginForm = this.formBuilder.group({ rut: ['', [Validators.required]], clave: ['', Validators.required] }); Util.setScrollfixIos(this); this.getUrlRegistroRevuperacion(); } close() { this.dialogRef.close(); } onFormatRut() { if(this.loginForm.controls['rut'].value && this.loginForm.controls['rut'].value.length > 12) { return } const rutFormatead = Util.formatearRut(this.loginForm.controls['rut'].value); this.loginForm.controls['rut'].setValue(rutFormatead); } onValidaRut() { const rutValido = Util.esRutValido(this.loginForm.controls['rut'].value); if (!rutValido) { this.loginForm.controls['rut'].setErrors({ error: 'rut inválido' }); } } login() { if (this.loginForm.invalid) { const formKeys = Object.keys(this.loginForm.controls); formKeys.forEach(item => { const control = this.loginForm.controls[item] if (control.invalid) { control.markAsTouched(); } }); return; } this.autenticar(); } otpView(option: boolean) { this.hideOTP = option; return false; } cedulaLogin() { this.loginForm.controls['rut'].setErrors(null); this.loginForm.controls['rut'].markAsUntouched(); const modalRef = this._modalDialog.open(LoginRepresentanteComponent, { width: '780px', disableClose: false, maxWidth: '92vw', data: { tipoDenuncianteId: TipoDenuncianteEnum.Asegurado } }); modalRef.afterClosed() .subscribe(logged => { if (logged) { window.location.href = environment.url + "/polizas/" + Util.rencryptToUrl(this.data.compania.toString()) + '/' + Util.rencryptToUrl(this.data.tipoVehiculo.toString()) + '/' + Util.rencryptToUrl(this.data.tipoDenunciante.toString()); } }); } authOK(res: ResponseEntityModel) { if (res.Code === 200) { this._storageService.setToken(res.Data.Token); this._storageService.setRefreshToken(res.Data.RefreshToken); this._storageService.setDatosUsuarioAutenticado(res.Data.Profile); const listPrametros = Object.values(ParametroEnum); this._parametroService.getByCodes(listPrametros).subscribe((paramRes: ResponseEntityModel) => { if (paramRes.Code == 200) { this._storageService.setParametrosAplicacion(paramRes.Data as ParametroModel[]); this.dialogRef.close(true); } else { console.error('Error al obtener parámetros de aplicación: ', paramRes.Message); } }, (error) => console.log(error)); } else { this.intentos++; this.loginForm.controls['clave'].setErrors({ 'login': true }); } } autenticar() { const payload = this.getPayload(); this._authService.login(payload) .subscribe( (res: ResponseEntityModel) => this.authOK(res), (error) => { this.intentos++; this.loginForm.controls['clave'].setErrors({ 'solicitud': true }); } ); } getPayload() { let codCompania = this._storageService.getSistema(); return { Username: Util.limpiarRut(this.Rut), Password: this.Password, Compania: codCompania ? parseInt(codCompania) : ECompania.bci } as LoginRequestModel; } get Rut(): string { return this.loginForm.controls['rut'].value } get Password(): string { return this.loginForm.controls['clave'].value } getErrorRutMsg() { let errorMsg = ''; const control = this.loginForm.controls['rut']; if (control.errors && control.errors?.required) { errorMsg = 'Este campo es requerido'; } else if (control.errors && control.errors?.error) { errorMsg = 'El rut es inválido'; } return errorMsg; } showPassword() { this.isShowPassword = !this.isShowPassword ; } getUrlRegistroRevuperacion(){ const codigosUrl = [ 'bcis.login.recuperar.clave', 'bcis.login.registro', 'zenit.login.recuperar.clave', 'zenit.login.registro', ]; this._parametroService.getByCodes(codigosUrl).subscribe( response => { if(response && response.Data && response.Data.length > 0) { const recuperacion = '.login.recuperar.clave'; const registro = '.login.registro'; const sistema = this._storageService.getSistema(); let urlList = response.Data as ParametroModel[]; this.recuperarClave = urlList.find(url => {return url.Codigo.includes(sistema == '1' ? ('bcis' + recuperacion) : ('zenit' + recuperacion))})?.Valor ?? '#'; this.registro = urlList.find(url => {return url.Codigo.includes(sistema == '1' ? ('bcis' + registro) : ('zenit' + registro))})?.Valor ?? '#'; } }, error => { console.error('No se pudo obtener las direcciones de recuperación y registro', error); } ); } }