You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
aConnect-UX/src/app/user-management/reset-password/reset-password.component.ts

188 lines
6.2 KiB
TypeScript

import { Component, ViewChild, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl, ValidationErrors, ReactiveFormsModule } from '@angular/forms';
import { TranslateModule } from '@ngx-translate/core';
import { CommonModule } from '@angular/common';
import { PasswordHideShowComponent } from '../../shared/components/password-hide-show/password-hide-show.component';
import { URIKey } from '../../utils/uri-enums';
import { HttpURIService } from '../../app.http.uri.service';
import { StorageService } from '../../shared/services/storage.service';
import { I18NService } from '../../services/i18n.service';
import { ErrorMessages, SuccessMessages } from '../../utils/enums';
import { HttpErrorResponse, HttpParams } from '@angular/common/http';
import { Router } from '@angular/router';
6 days ago
import { NgSelectModule } from '@ng-select/ng-select';
import { SetupUser } from '../../models/user';
@Component({
selector: 'app-reset-password',
6 days ago
imports: [TranslateModule, PasswordHideShowComponent, CommonModule, ReactiveFormsModule, NgSelectModule],
templateUrl: './reset-password.component.html',
styleUrl: './reset-password.component.scss'
})
export class ResetPasswordComponent implements OnInit{
resetPasswordForm!: FormGroup
passwordType1: string = 'password';
passwordType2: string = 'password';
isLoading: boolean = false;
allUsersDropdown: SetupUser[] = [];
selectedUserId: string | null = null;
6 days ago
isSubmitting: boolean = false;
@ViewChild('psh1') passwordHideShow1?: PasswordHideShowComponent;
@ViewChild('psh2') passwordHideShow2?: PasswordHideShowComponent;
6 days ago
constructor(
private fb: FormBuilder,
private httpService: HttpURIService,
private storageService: StorageService,
private i18nService: I18NService,
private router: Router
){}
ngOnInit(): void {
6 days ago
this.initializeForm();
this.loadUsersForDropdown();
}
initializeForm(): void {
this.resetPasswordForm = this.fb.group({
6 days ago
userId: ['', Validators.required], // Changed to empty string and required
newPassword: ['', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(20),
Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/)
6 days ago
]],
confirmPassword: ['', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(20),
Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/)
6 days ago
]]
}, {
validators: this.passwordMatchValidator
6 days ago
});
6 days ago
// Update confirm password validation when new password changes
this.resetPasswordForm.get('newPassword')?.valueChanges.subscribe(() => {
this.resetPasswordForm.get('confirmPassword')?.updateValueAndValidity();
});
}
6 days ago
togglePasswordType1() {
this.passwordType1 = this.passwordHideShow1?.showPassword ? 'password' : 'text';
}
6 days ago
togglePasswordType2() {
this.passwordType2 = this.passwordHideShow2?.showPassword ? 'password' : 'text';
}
passwordMatchValidator(group: AbstractControl): ValidationErrors | null {
const newPassword = group.get('newPassword');
const confirmPassword = group.get('confirmPassword');
6 days ago
if (!newPassword || !confirmPassword) return null;
6 days ago
if (confirmPassword.errors && !confirmPassword.errors['passwordMismatch']) {
return null;
}
6 days ago
if (newPassword.value !== confirmPassword.value) {
confirmPassword.setErrors({ passwordMismatch: true });
return { passwordMismatch: true };
} else {
confirmPassword.setErrors(null);
return null;
}
}
onSubmit() {
6 days ago
if (this.resetPasswordForm.invalid) {
this.resetPasswordForm.markAllAsTouched();
return;
}
this.isSubmitting = true;
const selectedId = this.resetPasswordForm.get('userId')?.value;
6 days ago
console.log("userid.....", selectedId);
const payload = {
userId: selectedId,
newPassword: this.resetPasswordForm.get('newPassword')?.value,
porOrgaCode: this.storageService.getItem('POR_ORGACODE')
};
6 days ago
this.httpService.requestPOST(URIKey.RESET_PASSWORD_URI, payload).subscribe({
next: (response) => {
if (!(response instanceof HttpErrorResponse)) {
this.i18nService.success(SuccessMessages.RESET_PASSWORD_SUCCESS, []);
this.resetForm(); // Reset form after successful submission
// Optional: Navigate to dashboard or stay on page
setTimeout(() => {
this.router.navigate(['/dashboard']);
6 days ago
}, 1500);
}
6 days ago
this.isSubmitting = false;
},
error: (error) => {
console.error('Error resetting password:', error);
this.isSubmitting = false;
}
});
}
// Method to properly reset the form
resetForm(): void {
// Reset the form values
this.resetPasswordForm.reset();
// Reset password visibility
this.passwordType1 = 'password';
this.passwordType2 = 'password';
// Reset password hide/show components if available
if (this.passwordHideShow1) {
this.passwordHideShow1.showPassword = false;
}
if (this.passwordHideShow2) {
this.passwordHideShow2.showPassword = false;
}
// Mark all controls as untouched and pristine
Object.keys(this.resetPasswordForm.controls).forEach(key => {
const control = this.resetPasswordForm.get(key);
control?.markAsUntouched();
control?.markAsPristine();
});
// Reset ng-select by clearing the value
setTimeout(() => {
this.resetPasswordForm.patchValue({
userId: '',
newPassword: '',
confirmPassword: ''
});
6 days ago
}, 0);
}
6 days ago
loadUsersForDropdown(): void {
this.isLoading = true;
let params = new HttpParams()
.set('page', '0')
.set('size', '1000');
this.httpService.requestGET<SetupUser[]>(URIKey.GET_ALL_USER_URI, params).subscribe({
6 days ago
next: (response) => {
this.allUsersDropdown = response || [];
this.isLoading = false;
},
6 days ago
error: (err) => {
console.error('Error fetching users:', err);
this.allUsersDropdown = [];
this.isLoading = false;
}
6 days ago
});
}
6 days ago
}