Update setup-user.component.ts

PRE-PRODUCTION-2026
Naeem Ullah 5 days ago
parent a054c192a7
commit 87e14d11ba

@ -92,77 +92,94 @@ export class SetupUserComponent implements OnInit {
} }
// Submit for creating new user // Submit for creating new user
onSubmit() { onSubmit() {
if (this.userForm.invalid) { // For create mode, check if password is required
if (this.mode === 'create') {
const passwordControl = this.userForm.get('defaultPassword');
if (!passwordControl?.value) {
passwordControl?.setErrors({ required: true });
this.userForm.markAllAsTouched(); this.userForm.markAllAsTouched();
return; return;
} }
}
const newUser: SetupUser = { if (this.userForm.invalid) {
userId: this.userForm.value.userId.trim().toLowerCase(), this.userForm.markAllAsTouched();
userFullname: this.userForm.value.userFullname.trim(), return;
email: this.userForm.value.email.trim(),
role: this.userForm.value.userRole,
porOrgacode: this.storageService.getItem('POR_ORGACODE'),
password: this.userForm.value.defaultPassword
};
this.isLoading = true;
this.httpService.requestPOST<SetupUser>(URIKey.CREATE_USER, newUser).subscribe({
next: (response) => {
if (!(response instanceof HttpErrorResponse)) {
this.i18nService.success(SuccessMessages.USER_CREATED_SUCCESS, []);
this.resetForm();
this.loadUsersDirect();
}
this.isLoading = false;
},
error: (error) => {
console.error('Error creating user:', error);
this.isLoading = false;
}
});
} }
// Update existing user const newUser: SetupUser = {
onUpdate() { userId: this.userForm.value.userId.trim().toLowerCase(),
if (this.userForm.invalid) { userFullname: this.userForm.value.userFullname.trim(),
this.userForm.markAllAsTouched(); email: this.userForm.value.email.trim(),
return; role: this.userForm.value.userRole,
porOrgacode: this.storageService.getItem('POR_ORGACODE'),
password: this.userForm.value.defaultPassword
};
this.isLoading = true;
this.httpService.requestPOST<SetupUser>(URIKey.CREATE_USER, newUser).subscribe({
next: (response) => {
if (!(response instanceof HttpErrorResponse)) {
this.i18nService.success(SuccessMessages.USER_CREATED_SUCCESS, []);
this.resetForm();
this.loadUsersDirect();
}
this.isLoading = false;
},
error: (error) => {
console.error('Error creating user:', error);
this.isLoading = false;
} }
});
}
const updatedUser: any = { // Update existing user
userId: this.selectedUserIdForEdit, onUpdate() {
userFullname: this.userForm.value.userFullname.trim(), // Clear any pattern errors if password is empty in edit mode
email: this.userForm.value.email.trim(), const passwordControl = this.userForm.get('defaultPassword');
role: this.userForm.value.userRole, if (passwordControl && !passwordControl.value && this.mode === 'edit') {
porOrgacode: this.storageService.getItem('POR_ORGACODE') passwordControl.setErrors(null); // Clear errors for empty password in edit mode
}; }
// Only include password if it was provided
if (this.userForm.value.defaultPassword && this.userForm.value.defaultPassword.trim()) {
updatedUser.password = this.userForm.value.defaultPassword;
}
let params = new HttpParams().set('userId', this.selectedUserIdForEdit!); if (this.userForm.invalid) {
this.userForm.markAllAsTouched();
return;
}
this.isLoading = true; const updatedUser: any = {
this.httpService.requestPUT<SetupUser>(URIKey.UPDATE_USER, updatedUser, undefined, params).subscribe({ userId: this.selectedUserIdForEdit,
next: (response) => { userFullname: this.userForm.value.userFullname.trim(),
if (!(response instanceof HttpErrorResponse)) { email: this.userForm.value.email.trim(),
this.i18nService.success(SuccessMessages.USER_UPDATED_SUCCESS, []); role: this.userForm.value.userRole,
this.resetForm(); porOrgacode: this.storageService.getItem('POR_ORGACODE')
this.loadUsersDirect(); };
}
this.isLoading = false; // Only include password if it was provided AND is valid
}, if (this.userForm.value.defaultPassword &&
error: (error) => { this.userForm.value.defaultPassword.trim() &&
console.error('Error updating user:', error); this.userForm.get('defaultPassword')?.valid) {
this.isLoading = false; updatedUser.password = this.userForm.value.defaultPassword.trim();
}
});
} }
let params = new HttpParams().set('userId', this.selectedUserIdForEdit!);
this.isLoading = true;
this.httpService.requestPUT<SetupUser>(URIKey.UPDATE_USER, updatedUser, undefined, params).subscribe({
next: (response) => {
if (!(response instanceof HttpErrorResponse)) {
this.i18nService.success(SuccessMessages.USER_UPDATED_SUCCESS, []);
this.resetForm();
this.loadUsersDirect();
}
this.isLoading = false;
},
error: (error) => {
console.error('Error updating user:', error);
this.isLoading = false;
}
});
}
// Cancel edit mode // Cancel edit mode
cancelEdit() { cancelEdit() {
this.resetForm(); this.resetForm();
@ -234,43 +251,60 @@ export class SetupUserComponent implements OnInit {
this.loadUsersDirect(); this.loadUsersDirect();
} }
initializeForm(): void { initializeForm(): void {
this.userForm = this.fb.group({ this.userForm = this.fb.group({
userId: ['', [ userId: ['', [
Validators.required, Validators.required,
Validators.minLength(3), Validators.minLength(3),
Validators.pattern('^[a-zA-Z0-9]*$') Validators.pattern('^[a-zA-Z0-9]*$')
]], ]],
userFullname: ['', [ userFullname: ['', [
Validators.required, Validators.required,
Validators.minLength(3), Validators.minLength(3),
Validators.maxLength(500) Validators.maxLength(500)
]], ]],
defaultPassword: ['', [ defaultPassword: ['', [
// Make password optional for edit mode, required for create // For edit mode, password is optional
(control: AbstractControl) => { // For create mode, handle required validation separately
if (this.mode === 'create' && !control.value) { this.passwordValidator.bind(this)
return { required: true }; ]],
} email: ['', [Validators.required, Validators.email]],
return null; userRole: [null, Validators.required]
}, });
Validators.pattern( }
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/
)
]],
email: ['', [Validators.required, Validators.email]],
userRole: [null, Validators.required]
});
// Update password validation when mode changes // Custom validator for password
this.userForm.get('defaultPassword')?.valueChanges.subscribe(() => { private passwordValidator(control: AbstractControl): { [key: string]: any } | null {
const passwordControl = this.userForm.get('defaultPassword'); const value = control.value;
if (passwordControl) {
passwordControl.updateValueAndValidity(); // If empty and we're in edit mode, it's valid (optional)
} if (!value || value.trim() === '') {
}); if (this.mode === 'edit') {
return null; // Password is optional in edit mode
}
// For create mode, we'll handle required validation in onSubmit
return null; // Don't show pattern error for empty field
} }
// If there's a value, check the pattern
const pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/;
if (!pattern.test(value)) {
return { pattern: true };
}
return null;
}
// Separate validator function
private createPasswordValidator(mode: 'create' | 'edit'): Validators {
return (control: AbstractControl) => {
if (mode === 'create' && !control.value) {
return { required: true };
}
return null;
};
}
loadUsersDirect(): void { loadUsersDirect(): void {
this.isLoading = true; this.isLoading = true;
let params = new HttpParams() let params = new HttpParams()

Loading…
Cancel
Save