import {Component, EventEmitter, OnInit, Output, Input, ChangeDetectionStrategy} from '@angular/core'; import {Role} from '../../../_models/Authentication/role'; import {User} from '../../../_models/Authentication/user'; import {AuthService} from '../../../_services/auth/auth.service'; import {HRMNotificationService} from '../../../app.notification.service'; import {EnumAuthStatus, EnumRoleType, EnumUserType} from '../../../_models/enums'; import { EnumUserRoleRequestType, UserRoleChangeRequest, UserRoleState, UserRoleSubject, } from '../../../_models/Authentication/UserRole'; import { SearchEmployee } from '../../../_models/Employee/searchEmployee'; import { PayrollType } from '../../../_models/Authentication/payrollType'; import { ApiService } from 'src/app/app.api.service'; import { loadingPanelService } from '../../../hrm-loding panel/loding.panel.service'; /** * User-Role Assignment dialog (Authentication > User Role Permission). * Pick whose roles (an Admin user, or a Self Service employee), tick the roles they should have and * send the change for approval; a change waiting for approval is shown, and another administrator * approves or rejects it here. Nothing is live until it is approved (server-side maker-checker). */ @Component({ selector: 'app-user-role-entry', templateUrl: './user-role-entry.component.html', styleUrls: ['./user-role-entry.component.css'], changeDetection: ChangeDetectionStrategy.Eager, standalone: false, }) export class UserRoleEntryComponent implements OnInit { readonly roletypeEnum: typeof EnumRoleType = EnumRoleType; /** Emits true when something changed (sent, approved or rejected), false on cancel. */ @Output() saveCompleted: EventEmitter = new EventEmitter(); /** Kept for the list page: true when the dialog is opened. */ @Input() public set InitializeForm(initializeValue: boolean) { if (initializeValue === true) { this.resetPerson(); } } /** Open the dialog on this person (from the list or the Pending approvals view). */ @Input() openFor: UserRoleSubject; roleType: EnumRoleType = EnumRoleType.Admin; users: User[] = []; filteredUsers: User[] = []; payrollTypes: PayrollType[] = []; allRoles: Role[] = []; currentUserID: number; selectedUserID: number; selectedPayrollTypeID: number; selectedEmployee: SearchEmployee; state: UserRoleState; selectedRoleIDs: number[] = []; roleSearch = ''; constructor(public userService: AuthService, public apiService: ApiService, public notificationService: HRMNotificationService, public loadingPanel: loadingPanelService) { } ngOnInit() { this.userService.GetCurrentUser().subscribe((resp: any) => { this.currentUserID = resp?.userID; }); this.userService.GetUsers(EnumUserType.User).subscribe((resp: any) => { this.users = resp ?? []; this.filteredUsers = this.users.slice(); }); this.userService.GetAllPayrollTypes().subscribe((resp: any) => { this.payrollTypes = resp ?? []; }); this.userService.getAllRoles().subscribe((resp: any) => { this.allRoles = resp ?? []; }); if (this.openFor) { this.roleType = this.openFor.roleType; if (this.roleType == EnumRoleType.Self_Service) { this.selectedPayrollTypeID = this.openFor.payrollTypeID; } else { this.selectedUserID = this.openFor.userID; } this.loadState(this.openFor.userID, this.openFor.employeeID); } } // ---------- whose roles ---------- setRoleType(type: EnumRoleType): void { if (this.roleType == type) { return; } this.roleType = type; this.resetPerson(); } private resetPerson(): void { this.selectedUserID = undefined; this.selectedEmployee = undefined; this.state = undefined; this.selectedRoleIDs = []; this.roleSearch = ''; } onUserFilter(term: string): void { const t = (term ?? '').trim().toLowerCase(); this.filteredUsers = this.users.filter(u => !t || (u.userName ?? '').toLowerCase().includes(t) || (u.loginID ?? '').toLowerCase().includes(t)); } onUserChange(userID: number): void { this.state = undefined; this.selectedRoleIDs = []; if (userID) { this.loadState(userID, undefined); } } onPayrollTypeChange(): void { this.selectedEmployee = undefined; this.state = undefined; this.selectedRoleIDs = []; } onEmployeeSelected(emp: any): void { this.selectedEmployee = emp && !Array.isArray(emp) ? emp : undefined; this.state = undefined; this.selectedRoleIDs = []; if (this.selectedEmployee?.employeeID) { this.loadState(undefined, this.selectedEmployee.employeeID); } } private loadState(userID: number, employeeID: number): void { this.loadingPanel.ShowLoadingPanel = true; this.userService.GetUserRoleState(this.roleType, userID, employeeID).subscribe( (resp: UserRoleState) => { this.state = resp; if (this.roleType == EnumRoleType.Self_Service && !this.selectedPayrollTypeID) { this.selectedPayrollTypeID = resp?.payrollTypeID; } this.resetSelection(); }, (err: any) => { this.loadingPanel.ShowLoadingPanel = false; this.notificationService.showError(err?.error ?? err); }, () => { this.loadingPanel.ShowLoadingPanel = false; } ); } // ---------- roles ---------- private isApprovedRole(r: Role): boolean { return r.roleStatus == EnumAuthStatus.Approved || r.roleStatus == EnumAuthStatus.Active; } /** Roles of the selected role type: approved ones, plus any the person has or has asked for. */ get rolesForType(): Role[] { const live = this.state?.liveRoleIDs ?? []; const pending = (this.state?.pending ?? []).map(p => p.roleID); return this.allRoles .filter(r => r.roleType == this.roleType && (this.isApprovedRole(r) || live.includes(r.id) || pending.includes(r.id))) .sort((a, b) => (a.name ?? '').localeCompare(b.name ?? '')); } get visibleRoles(): Role[] { const t = this.roleSearch.trim().toLowerCase(); return this.rolesForType.filter(r => !t || (r.name ?? '').toLowerCase().includes(t) || ((r as any).code ?? '').toString().toLowerCase().includes(t)); } isTicked(roleID: number): boolean { return this.selectedRoleIDs.includes(roleID); } get locked(): boolean { return !this.state || this.hasPending; } toggle(roleID: number): void { if (this.locked) { return; } this.selectedRoleIDs = this.isTicked(roleID) ? this.selectedRoleIDs.filter(x => x != roleID) : [...this.selectedRoleIDs, roleID]; } selectAllVisible(): void { if (this.locked) { return; } const ids = this.visibleRoles.map(r => r.id).filter(id => !this.isTicked(id)); this.selectedRoleIDs = [...this.selectedRoleIDs, ...ids]; } clearAllVisible(): void { if (this.locked) { return; } const ids = this.visibleRoles.map(r => r.id); this.selectedRoleIDs = this.selectedRoleIDs.filter(x => !ids.includes(x)); } /** Ticks show what the person has now, or what is asked for while a change waits for approval. */ resetSelection(): void { const live = this.state?.liveRoleIDs ?? []; const pending = this.state?.pending ?? []; const removing = pending.filter(p => p.requestType == EnumUserRoleRequestType.Remove).map(p => p.roleID); const adding = pending.filter(p => p.requestType == EnumUserRoleRequestType.Add).map(p => p.roleID); this.selectedRoleIDs = [...live.filter(id => !removing.includes(id)), ...adding.filter(id => !live.includes(id))]; } roleName(roleID: number): string { return this.allRoles.find(r => r.id == roleID)?.name ?? ''; } /** Badge of one role row. */ roleBadge(roleID: number): { text: string, tone: string } { const live = (this.state?.liveRoleIDs ?? []).includes(roleID); const pending = (this.state?.pending ?? []).find(p => p.roleID == roleID); if (pending) { return pending.requestType == EnumUserRoleRequestType.Remove ? { text: 'Removal - Not Yet Approved', tone: 'warning' } : { text: 'New - Not Yet Approved', tone: 'warning' }; } if (!this.hasPending && this.state) { if (!live && this.isTicked(roleID)) { return { text: 'To be added', tone: 'info' }; } if (live && !this.isTicked(roleID)) { return { text: 'To be removed', tone: 'info' }; } } return live ? { text: 'Active', tone: 'success' } : { text: 'Not assigned', tone: 'neutral' }; } // ---------- maker-checker ---------- get hasPending(): boolean { return (this.state?.pending ?? []).length > 0; } get isMakerOfPending(): boolean { return (this.state?.pending ?? []).some(p => p.createdBy == this.currentUserID); } get pendingAddNames(): string[] { return (this.state?.pending ?? []).filter(p => p.requestType == EnumUserRoleRequestType.Add).map(p => p.roleName); } get pendingRemoveNames(): string[] { return (this.state?.pending ?? []).filter(p => p.requestType == EnumUserRoleRequestType.Remove).map(p => p.roleName); } get pendingMaker(): string { const p = (this.state?.pending ?? [])[0]; return p ? (p.makerLoginID || '') : ''; } get pendingDate(): Date { const p = (this.state?.pending ?? [])[0]; return p?.createdDate ? new Date(p.createdDate) : null; } get draftAddNames(): string[] { const live = this.state?.liveRoleIDs ?? []; return this.selectedRoleIDs.filter(id => !live.includes(id)).map(id => this.roleName(id)); } get draftRemoveNames(): string[] { return (this.state?.liveRoleIDs ?? []).filter(id => !this.isTicked(id)).map(id => this.roleName(id)); } get hasDraftChanges(): boolean { return !this.hasPending && (this.draftAddNames.length > 0 || this.draftRemoveNames.length > 0); } private subject(): UserRoleSubject { const s = new UserRoleSubject(); s.roleType = this.roleType; s.userID = this.state?.userID ?? (this.roleType == EnumRoleType.Admin ? this.selectedUserID : undefined); s.employeeID = this.state?.employeeID; s.payrollTypeID = this.state?.payrollTypeID ?? this.selectedPayrollTypeID; return s; } sendForApproval(): void { if (!this.state) { this.notificationService.showWarning(this.roleType == EnumRoleType.Admin ? 'Select a user.' : 'Select an employee.'); return; } if (!this.hasDraftChanges) { this.notificationService.showWarning('Nothing changed.'); return; } const request = Object.assign(new UserRoleChangeRequest(), this.subject()); request.roleIDs = this.selectedRoleIDs.slice(); this.loadingPanel.ShowLoadingPanel = true; this.userService.SaveUserRoleRequest(request).subscribe( () => { }, (err: any) => { this.loadingPanel.ShowLoadingPanel = false; this.notificationService.showError(err?.error ?? err); }, () => { this.loadingPanel.ShowLoadingPanel = false; this.notificationService.showSuccess('Sent for approval. Nothing changes until another administrator approves it.'); this.saveCompleted.emit(true); } ); } onApprove(): void { this.decide(true); } onReject(): void { this.decide(false); } private decide(approve: boolean): void { if (!this.hasPending) { return; } const call = approve ? this.userService.ApproveUserRole(this.subject()) : this.userService.RejectUserRole(this.subject()); this.loadingPanel.ShowLoadingPanel = true; call.subscribe( () => { }, (err: any) => { this.loadingPanel.ShowLoadingPanel = false; this.notificationService.showError(err?.error ?? err); }, () => { this.loadingPanel.ShowLoadingPanel = false; this.notificationService.showSuccess(approve ? 'Approved. The roles are now live.' : 'Rejected. The roles stay as they were.'); this.saveCompleted.emit(true); } ); } public onCancel(): void { this.saveCompleted.emit(false); } }