diff --git a/HRM.BO/User/UserAccessType.cs b/HRM.BO/User/UserAccessType.cs index dc46290..6cab01e 100644 --- a/HRM.BO/User/UserAccessType.cs +++ b/HRM.BO/User/UserAccessType.cs @@ -13,6 +13,8 @@ namespace HRM.BO PayrollTypeID = 0; UserID = 0; UserObj = null; + // A row nobody approved yet is never live access (see UserAccessTypeMakerChecker_DB_Changes.sql). + AccessTypeStatus = EnumAuthStatus.NewNotYetApprove; } #endregion @@ -23,9 +25,13 @@ namespace HRM.BO public string Description { get; set; } public int UserID { get; set; } public User UserObj { get; set; } - public EnumAuthStatus accessTypeStatus; - public int? ApprovedBy; - public DateTime? ApprovedDate; + /// + /// UserAccessType.Status: Approved (5) = live; NewNotYetApprove (2) = requested, not live yet; + /// DeletedNotYetApprove (3) = removal requested, still live until approved. + /// + public EnumAuthStatus AccessTypeStatus { get; set; } + public int? ApprovedBy { get; set; } + public DateTime? ApprovedDate { get; set; } #endregion } @@ -41,6 +47,14 @@ namespace HRM.BO int Save(UserAccessType item); void Save(List userAccessTypes); void Delete(int id); + + // Maker-checker (Authentication > User Access Type) + /// Maker: records the wanted payroll types of a user as pending changes. Returns how many rows changed. + int RequestChange(int userID, List payrollTypeIDs, int makerID); + /// Checker: makes every pending change of the user live. + void Approve(int userID, int approverID); + /// Checker: drops every pending change of the user; access stays as it was. + void Reject(int userID); } #endregion diff --git a/HRM.DA/DA/Basic/PayrollTypeDA.cs b/HRM.DA/DA/Basic/PayrollTypeDA.cs index 5eaf345..610de00 100644 --- a/HRM.DA/DA/Basic/PayrollTypeDA.cs +++ b/HRM.DA/DA/Basic/PayrollTypeDA.cs @@ -56,8 +56,11 @@ namespace HRM.DA internal static IDataReader GetUserPayrollType(TransactionContext tc, string loginID) { - string sql = SQLParser.MakeSQL(@"SELECT p.* FROM PayrollType p, UserAccessType ua,Users u - where p.PayrollTypeID==ua.PayrollTypeID and u.UserID =ua.UserID and u.LoginID=%s", loginID); + // Live access only: a requested access (Status 2) is not live until approved; a requested + // removal (Status 3) stays live until approved. + string sql = SQLParser.MakeSQL(@"SELECT p.* FROM PayrollType p, UserAccessType ua,Users u + where p.PayrollTypeID==ua.PayrollTypeID and u.UserID =ua.UserID and u.LoginID=%s and ua.Status<>%n", + loginID, (int)EnumAuthStatus.NewNotYetApprove); return tc.ExecuteReader(sql); } @@ -68,7 +71,8 @@ namespace HRM.DA string sql = SQLParser.MakeSQL(@"SELECT * FROM PAYROLLTYPE WHERE PAYROLLTYPEID IN (SELECT DISTINCT ua.PAYROLLTYPEID FROM USERS u JOIN USERACCESSTYPE ua ON u.USERID = ua.UserId - WHERE u.EMPLOYEEID=%n AND u.USERTYPE=%n)", employeeId, userType); + WHERE u.EMPLOYEEID=%n AND u.USERTYPE=%n AND ua.Status<>%n)", + employeeId, userType, (int)EnumAuthStatus.NewNotYetApprove); return tc.ExecuteReader(sql); } diff --git a/HRM.DA/DA/Users/UserAccessTypeDA.cs.cs b/HRM.DA/DA/Users/UserAccessTypeDA.cs.cs index 2f14dad..3d1e5c3 100644 --- a/HRM.DA/DA/Users/UserAccessTypeDA.cs.cs +++ b/HRM.DA/DA/Users/UserAccessTypeDA.cs.cs @@ -18,8 +18,14 @@ namespace HRM.DA internal static void Insert(TransactionContext tc, UserAccessType item) { - tc.ExecuteNonQuery("INSERT INTO UserAccessType(UserAccessTypeID, PayrollTypeID, UserID)" + - " VALUES(%n, %n, %n)", item.ID, item.PayrollTypeID, item.UserID); + tc.ExecuteNonQuery("INSERT INTO UserAccessType(UserAccessTypeID, PayrollTypeID, UserID, Status," + + " CreatedBy, CreatedDate, ApprovedBy, ApprovedDate)" + + " VALUES(%n, %n, %n, %n, %n, %D, %n, %D)", + item.ID, item.PayrollTypeID, item.UserID, (int)item.AccessTypeStatus, + item.CreatedBy == 0 ? null : item.CreatedBy, + item.CreatedDate == System.DateTime.MinValue ? null : item.CreatedDate, + item.ApprovedBy == 0 ? null : item.ApprovedBy, + item.ApprovedDate == System.DateTime.MinValue ? null : item.ApprovedDate); } #endregion @@ -32,6 +38,33 @@ namespace HRM.DA " WHERE UserAccessTypeID=%n", item.PayrollTypeID, item.UserID, item.ID); } + // Maker asks to take a live access away: it stays live (Status 3) until approved. + internal static void RequestRemoval(TransactionContext tc, int userAccessTypeID, int makerID, System.DateTime requestDate) + { + tc.ExecuteNonQuery("UPDATE UserAccessType SET Status=%n, ModifiedBy=%n, ModifiedDate=%D" + + " WHERE UserAccessTypeID=%n", + (int)EnumAuthStatus.DeletedNotYetApprove, makerID, requestDate, userAccessTypeID); + } + + // Checker approves: requested removals go, requested accesses become live. + internal static void Approve(TransactionContext tc, int userID, int approverID, System.DateTime approveDate) + { + tc.ExecuteNonQuery("DELETE FROM UserAccessType WHERE UserID=%n AND Status=%n", + userID, (int)EnumAuthStatus.DeletedNotYetApprove); + tc.ExecuteNonQuery("UPDATE UserAccessType SET Status=%n, ApprovedBy=%n, ApprovedDate=%D" + + " WHERE UserID=%n AND Status=%n", + (int)EnumAuthStatus.Approved, approverID, approveDate, userID, (int)EnumAuthStatus.NewNotYetApprove); + } + + // Checker rejects: requested accesses go, requested removals stay live as before. + internal static void Reject(TransactionContext tc, int userID) + { + tc.ExecuteNonQuery("DELETE FROM UserAccessType WHERE UserID=%n AND Status=%n", + userID, (int)EnumAuthStatus.NewNotYetApprove); + tc.ExecuteNonQuery("UPDATE UserAccessType SET Status=%n WHERE UserID=%n AND Status=%n", + (int)EnumAuthStatus.Approved, userID, (int)EnumAuthStatus.DeletedNotYetApprove); + } + #endregion #region Get Function @@ -46,14 +79,21 @@ namespace HRM.DA return tc.ExecuteReader("SELECT * FROM UserAccessType WHERE UserAccessTypeID=%n", id); } - + // Get internal static IDataReader GetByUserID(TransactionContext tc, int UserID) { return tc.ExecuteReader("SELECT * FROM UserAccessType WHERE UserID=%n", UserID); } - + // Names of the payroll types a pending approval of this user will newly give access to. + internal static IDataReader GetPendingNewDescriptions(TransactionContext tc, int userID) + { + return tc.ExecuteReader(@"SELECT p.Description FROM UserAccessType ua + JOIN PayrollType p ON p.PayrollTypeID = ua.PayrollTypeID + WHERE ua.UserID=%n AND ua.Status=%n", + userID, (int)EnumAuthStatus.NewNotYetApprove); + } #endregion @@ -67,4 +107,4 @@ namespace HRM.DA #endregion } -} \ No newline at end of file +} diff --git a/HRM.DA/DA/Users/UserDA.cs b/HRM.DA/DA/Users/UserDA.cs index fe504d8..d2ae142 100644 --- a/HRM.DA/DA/Users/UserDA.cs +++ b/HRM.DA/DA/Users/UserDA.cs @@ -243,8 +243,8 @@ namespace HRM.DA { return tc.ExecuteReader(@"SELECT u.* FROM Users u WHERE u.UserType=%n AND u.UserID IN - (SELECT ua.UserID FROM UserAccessType ua WHERE ua.PayrollTypeID=%n)", - type, payrollTypeID); + (SELECT ua.UserID FROM UserAccessType ua WHERE ua.PayrollTypeID=%n AND ua.Status<>%n)", + type, payrollTypeID, (int)EnumAuthStatus.NewNotYetApprove); } internal static IDataReader GetAll(TransactionContext tc) diff --git a/HRM.DA/Service/Users/UserAccessTypeService.cs b/HRM.DA/Service/Users/UserAccessTypeService.cs index 1e4eae3..6635024 100644 --- a/HRM.DA/Service/Users/UserAccessTypeService.cs +++ b/HRM.DA/Service/Users/UserAccessTypeService.cs @@ -19,6 +19,13 @@ namespace HRM.DA base.SetObjectID(oUserAccessType, oReader.GetInt32("UserAccessTypeID").Value); oUserAccessType.PayrollTypeID = oReader.GetInt32("PayrollTypeID").Value; oUserAccessType.UserID = oReader.GetInt32("UserID", 0); + oUserAccessType.AccessTypeStatus = (EnumAuthStatus)oReader.GetInt32("Status", (int)EnumAuthStatus.Approved); + oUserAccessType.CreatedBy = oReader.GetInt32("CreatedBy", 0); + oUserAccessType.CreatedDate = oReader.GetDateTime("CreatedDate", DateTime.MinValue); + oUserAccessType.ModifiedBy = oReader.GetInt32("ModifiedBy"); + oUserAccessType.ModifiedDate = oReader.GetDateTime("ModifiedDate"); + oUserAccessType.ApprovedBy = oReader.GetInt32("ApprovedBy"); + oUserAccessType.ApprovedDate = oReader.GetDateTime("ApprovedDate"); this.SetObjectState(oUserAccessType, Ease.Core.ObjectState.Saved); } @@ -212,6 +219,138 @@ namespace HRM.DA } } + #region Maker-checker + + public int RequestChange(int userID, List payrollTypeIDs, int makerID) + { + TransactionContext tc = null; + int changed = 0; + try + { + tc = TransactionContext.Begin(true); + DataReader dr = new DataReader(UserAccessTypeDA.GetByUserID(tc, userID)); + List current = this.CreateObjects(dr); + dr.Close(); + + if (current.Any(x => x.AccessTypeStatus == EnumAuthStatus.NewNotYetApprove + || x.AccessTypeStatus == EnumAuthStatus.DeletedNotYetApprove)) + { + throw new InvalidOperationException("This user already has an access change waiting for approval."); + } + + DateTime now = DateTime.Now; + List wanted = (payrollTypeIDs ?? new List()).Distinct().ToList(); + + // Newly ticked payroll type: requested, not live until approved. + foreach (int payrollTypeID in wanted.Where(p => !current.Any(c => c.PayrollTypeID == p))) + { + UserAccessType item = new UserAccessType(); + item.UserID = userID; + item.PayrollTypeID = payrollTypeID; + item.AccessTypeStatus = EnumAuthStatus.NewNotYetApprove; + item.CreatedBy = makerID; + item.CreatedDate = now; + item.ApprovedBy = null; + item.ApprovedDate = null; + this.Save(tc, item); + changed++; + } + + // Unticked live access: removal requested, still live until approved. + foreach (UserAccessType item in current.Where(c => !wanted.Contains(c.PayrollTypeID))) + { + UserAccessTypeDA.RequestRemoval(tc, item.ID, makerID, now); + changed++; + } + + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + #endregion + } + return changed; + } + + public void Approve(int userID, int approverID) + { + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(true); + User oUser = new UserService().Get(tc, userID); + + // Read before approving: the payroll types this approval newly gives access to. + List newAccessNames = new List(); + DataReader dr = new DataReader(UserAccessTypeDA.GetPendingNewDescriptions(tc, userID)); + while (dr.Read()) + { + string name = dr.GetString("Description"); + if (!string.IsNullOrWhiteSpace(name) && !newAccessNames.Contains(name)) + newAccessNames.Add(name); + } + dr.Close(); + + UserAccessTypeDA.Approve(tc, userID, approverID, DateTime.Now); + + // The "access granted" notification now goes out when the access is really live. + if (oUser != null && oUser.EmployeeID.HasValue && newAccessNames.Any()) + { + var notification = new EmployeeNotification + { + EmployeeID = oUser.EmployeeID.Value, + Header = "New Access Permission Granted", + Description = $"You have been granted access to: {string.Join(", ", newAccessNames)}.", + Link = "", + CreatedDate = DateTime.Now, + CreatedBy = approverID, + ReferenceID = oUser.ID, + IsRead = 0, + ReadDate = null, + ReadBy = null + }; + new EmployeeNotificationService().Insert(tc, notification); + } + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + #endregion + } + } + + public void Reject(int userID) + { + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(true); + UserAccessTypeDA.Reject(tc, userID); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + #endregion + } + } + + #endregion + internal int Save(TransactionContext tc, UserAccessType oUserAccessType) { try diff --git a/HRM.UI/ClientApp/src/app/_models/Authentication/UserAccessType.ts b/HRM.UI/ClientApp/src/app/_models/Authentication/UserAccessType.ts index 195f549..32923fd 100644 --- a/HRM.UI/ClientApp/src/app/_models/Authentication/UserAccessType.ts +++ b/HRM.UI/ClientApp/src/app/_models/Authentication/UserAccessType.ts @@ -14,5 +14,8 @@ export class UserAccessType extends BaseObject public description: string = ""; public userID: number; public payrollTypeNameview: string; + /** Approved (5) = live; New_Not_Yet_Approve (2) = requested, not live yet; Deleted_Not_Yet_Approve (3) = removal requested, still live. */ public accessTypeStatus: EnumAuthStatus; + public approvedBy?: number; + public approvedDate?: Date; } diff --git a/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts b/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts index c179a57..163b9ec 100644 --- a/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts @@ -231,6 +231,12 @@ export class AuthService { return this.apiService.httpPost('/Authentication/SaveUserAccessType', acesssTypes); } + ApproveUserAccessType(userID: number) { + return this.apiService.httpPost('/Authentication/ApproveUserAccessType/' + userID, {}); + } + RejectUserAccessType(userID: number) { + return this.apiService.httpPost('/Authentication/RejectUserAccessType/' + userID, {}); + } changePassword(userData: any) { return this.apiService.httpPost('/Authentication/changePassword', userData); } diff --git a/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.css b/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.css index e02abfc..c758efd 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.css +++ b/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.css @@ -1 +1,52 @@ - +/* This component uses ViewEncapsulation.None, so every rule carries the uat- prefix. */ + +/* Banner shown while the selected user has an access change waiting for approval */ +.uat-pending { + margin-bottom: 12px; + padding: 10px 14px; + border: 1px solid #F5D9A8; + border-radius: 8px; + background: #FFF2DB; + color: #8A5300; + font-size: 13px; +} + +.uat-pending__note { + display: block; + margin-top: 4px; + font-weight: 600; +} + +.uat-action { + margin-left: 6px; +} + +/* While a change waits for approval the ticks show the requested state and cannot be changed */ +.uat-locked .k-checkbox { + pointer-events: none; + opacity: 0.6; +} + +/* Status badge, same look as the User and Role pages */ +.uat-badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 2px 10px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + line-height: 20px; + white-space: nowrap; +} + +.uat-badge__dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: currentColor; +} + +.uat-badge--success { background: #E6F4EC; color: #137A4B; } +.uat-badge--warning { background: #FFF2DB; color: #8A5300; } +.uat-badge--neutral { background: #EEEEF2; color: #5B5B6B; } diff --git a/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.html b/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.html index 9503bee..322a2d2 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.html +++ b/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.html @@ -1,4 +1,5 @@ +
@@ -23,9 +24,18 @@
+ @if (hasPending) { +
+ This user has an access change waiting for approval. The user keeps the current access until it is approved. + @if (isMakerOfPending) { + You made this change, so another user must approve or reject it. + } +
+ }
+ + + @if (_selectedUserID) { + + {{ statusOf(dataItem.id).text }} + + } + +
- + + @if (hasPending) { + + + }
diff --git a/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.ts b/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.ts index b4dc10a..a428c3f 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.ts +++ b/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.ts @@ -9,6 +9,7 @@ import {EnumUserType, EnumAuthStatus} from '../../_models/enums'; import {SelectableSettings} from '@progress/kendo-angular-grid'; import {ApiService} from '../../app.api.service'; import {HRMNotificationService} from '../../app.notification.service'; +import {loadingPanelService} from '../../hrm-loding panel/loding.panel.service'; import { ButtonModule } from '@progress/kendo-angular-buttons'; import { DropDownListModule } from '@progress/kendo-angular-dropdowns'; @@ -38,14 +39,23 @@ export class UserAccessTypeComponent implements OnInit { _selectedUserID: number; _selectedPayrollTypes: number[]=[]; public selectableSettings: SelectableSettings; + /** Logged-in user's ID: the maker of a pending change cannot approve or reject it. */ + currentUserID: number; - constructor(public notificationService: HRMNotificationService, public useService: AuthService, public apiService: ApiService) { + constructor(public notificationService: HRMNotificationService, public useService: AuthService, public apiService: ApiService, + public loadingPanel: loadingPanelService) { this.apiService.selectedMenuName = ' User Access-Type Entry'; } ngOnInit(): void { this._selectedUserID = undefined; this._selectedPayrollTypes = []; + this._userAcessTypes = []; + this.useService.GetCurrentUser().subscribe( + (resp: any) => { + this.currentUserID = resp?.userID; + }, + ); this.useService.GetUsers(EnumUserType.User) .subscribe( (resp: any) => { @@ -85,12 +95,82 @@ export class UserAccessTypeComponent implements OnInit { }; } + // ---------- maker-checker ---------- + + private isPendingStatus(status: EnumAuthStatus): boolean { + return status == EnumAuthStatus.New_Not_Yet_Approve || status == EnumAuthStatus.Deleted_Not_Yet_Approve; + } + + /** The selected user has an access change waiting for approval. */ + get hasPending(): boolean { + return (this._userAcessTypes ?? []).some(x => this.isPendingStatus(x.accessTypeStatus)); + } + + /** The logged-in user made (part of) the pending change, so cannot approve or reject it. */ + get isMakerOfPending(): boolean { + return (this._userAcessTypes ?? []).some(x => { + const row: any = x; + const maker = x.accessTypeStatus == EnumAuthStatus.Deleted_Not_Yet_Approve ? row.modifiedBy : row.createdBy; + return this.isPendingStatus(x.accessTypeStatus) && maker == this.currentUserID; + }); + } + + /** Status column: the access the user has, or what is waiting for approval. */ + statusOf(payrollTypeID: number): { text: string, tone: string } { + const row = (this._userAcessTypes ?? []).find(x => x.payrollTypeID == payrollTypeID); + if (row == undefined) { + return { text: 'No access', tone: 'neutral' }; + } + switch (row.accessTypeStatus) { + case EnumAuthStatus.New_Not_Yet_Approve: + return { text: 'New - Not Yet Approved', tone: 'warning' }; + case EnumAuthStatus.Deleted_Not_Yet_Approve: + return { text: 'Removal - Not Yet Approved', tone: 'warning' }; + default: + return { text: 'Active', tone: 'success' }; + } + } + + onApprove(): void { + this.decide(true); + } + + onReject(): void { + this.decide(false); + } + + private decide(approve: boolean): void { + const userID = this._selectedUserID; + if (userID == undefined || !this.hasPending) { + return; + } + const call = approve ? this.useService.ApproveUserAccessType(userID) : this.useService.RejectUserAccessType(userID); + 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 Successfully.' : 'Rejected Successfully.'); + this.RefreshGrid(userID); + } + ); + } + RefreshGrid(selectedUser: any) { this._selectedPayrollTypes = []; + this._userAcessTypes = []; + this.setSelectableSettings(); + if (selectedUser == undefined || selectedUser == null) { + return; + } this.useService.GetUserAccessType(selectedUser) .subscribe( (resp: any) => { - this._userAcessTypes = resp; + this._userAcessTypes = resp ?? []; }, (err: any) => { //ON ERROR @@ -98,16 +178,20 @@ export class UserAccessTypeComponent implements OnInit { () => { this._userAcessTypes.forEach(x => { - + // A removal waiting for approval shows unticked: the ticks show the requested state. + if (x.accessTypeStatus == EnumAuthStatus.Deleted_Not_Yet_Approve) { + return; + } var ptype: PayrollType = this._payrollTypes.find(y => y.id == x.payrollTypeID); if (ptype != undefined) { this._selectedPayrollTypes.push(ptype.id); } }); this._selectedPayrollTypes = [... this._selectedPayrollTypes]; + this.setSelectableSettings(); } ); - + } public onSelectionPayrollChange(event: any): void { @@ -119,55 +203,46 @@ export class UserAccessTypeComponent implements OnInit { public onSave(): void { this._userAcessTypesforSave= []; - if (this._selectedPayrollTypes.length <= 0) { + if (this._selectedUserID == undefined || this._selectedUserID == null) { + this.notificationService.showWarning('Select a user.'); return; } - // New Item + if (this.hasPending) { + this.notificationService.showWarning('This user already has an access change waiting for approval. Approve or reject it first.'); + return; + } + if (this._selectedPayrollTypes.length <= 0) { + this.notificationService.showWarning('Select at least one payroll type.'); + return; + } + // The ticked payroll types are sent as they are; the server works out what is new + // (New - Not Yet Approved) and what was unticked (Removal - Not Yet Approved). this._selectedPayrollTypes.forEach(x => { - - var ptype: UserAccessType = this._userAcessTypes.find(y => x == y.payrollTypeID); - if (ptype == undefined) { - var newItem: UserAccessType = new UserAccessType(); - newItem.userID = this._selectedUserID; - newItem.payrollTypeID = x; - this._userAcessTypes.push(newItem); - - ptype = new UserAccessType(); - ptype.userID = this._selectedUserID; - ptype.payrollTypeID = x; + var ptype: UserAccessType = new UserAccessType(); + ptype.userID = this._selectedUserID; + ptype.payrollTypeID = x; + let payrollType = this._payrollTypes.find(p => p.id === x); + if (payrollType) { + ptype.description = payrollType.description; } this._userAcessTypesforSave.push(ptype); }); - - - - // Modify Existing which unchecked - this._userAcessTypes.forEach(x => { - - var ptype: number = this._selectedPayrollTypes.find(y => x.payrollTypeID == y); - if (ptype == undefined) { - x.accessTypeStatus = EnumAuthStatus.Deleted_Not_Yet_Approve; - } - }); - this._userAcessTypesforSave.forEach(x =>{ - let payrollType = this._payrollTypes.find(p => p.id === x.payrollTypeID); - if(payrollType){ - x.description = payrollType.description; - } - }); + this.loadingPanel.ShowLoadingPanel = true; this.useService.SaveUserAccessType(this._userAcessTypesforSave) .subscribe( (resp: any) => { }, (err: any) => { - this.notificationService.showError(err); + this.loadingPanel.ShowLoadingPanel = false; + this.notificationService.showError(err?.error ?? err); //ON ERROR }, () => { //ON Success - this.notificationService.showSuccess('Saved Successfully.'); + this.loadingPanel.ShowLoadingPanel = false; + this.notificationService.showSuccess('Saved. The change is waiting for approval.'); // this.loadGrid(); this.RefreshGrid(this._userAcessTypesforSave[0].userID); } diff --git a/HRM.UI/ClientApp/src/app/ess/user-ssdashboard/user-ssdashboard.component.html b/HRM.UI/ClientApp/src/app/ess/user-ssdashboard/user-ssdashboard.component.html index b24a957..2d35e51 100644 --- a/HRM.UI/ClientApp/src/app/ess/user-ssdashboard/user-ssdashboard.component.html +++ b/HRM.UI/ClientApp/src/app/ess/user-ssdashboard/user-ssdashboard.component.html @@ -673,23 +673,25 @@
@if (showModal) { - - Access Types -
-
-
-
- @for (type of payrollTypes; track type) { - - } -
-
+
+ + Access Types +
+
+
+
+ @for (type of payrollTypes; track type) { + + } +
+
+
-
- + +
} @if (showAttachment) { diff --git a/HRM.UI/Controllers/Auth/AuthController.cs b/HRM.UI/Controllers/Auth/AuthController.cs index 5af03ad..cf8ca05 100644 --- a/HRM.UI/Controllers/Auth/AuthController.cs +++ b/HRM.UI/Controllers/Auth/AuthController.cs @@ -424,6 +424,12 @@ namespace HRM.UI.Controllers { return BadRequest("Access Type and process date is not valid."); } + else if (userFromRepo.UserType == EnumUserType.User + && !this._payrollTypeService.GetPayrollTypes(userFromRepo.LoginID).Any(p => p.ID == userForLoginDto.payrollTypeid)) + { + // Only an approved (live) access type may be used to sign in; a requested one is not live yet. + return BadRequest("You do not have approved access to the selected Access Type."); + } else if (userFromRepo.UserType == EnumUserType.Employee) { DateTime eocd= _userService.GetEndofContractDate(userForLoginDto.Username); @@ -847,6 +853,11 @@ namespace HRM.UI.Controllers { PayrollType optype = new PayrollTypeService().Get(payrollTypeId); User oempUser = new UserService().Get(ouser.ID); + // Only an approved (live) access type may be switched to. + if (oempUser == null || !this._payrollTypeService.GetPayrollTypes(oempUser.LoginID).Any(p => p.ID == payrollTypeId)) + { + return BadRequest("You do not have approved access to this Access Type."); + } token = this.CreateToten(oempUser, optype.ID, optype.NextPayProcessDate); } catch (Exception e) @@ -917,6 +928,21 @@ namespace HRM.UI.Controllers return BadRequest("Your account is now locked. Please contact with your Line Manager."); } + // Only an approved (live) access type may be switched to: the same list the ESS + // switch shows (getAdminPayrollTypes). + List liveAccessTypes = this._payrollTypeService.GetUsersAdminPayrollTypes((int)currentUser.EmployeeID); + if (!liveAccessTypes.Any(p => p.ID == payrollTypeId)) + { + if (item["payrollTypeId"] != null || liveAccessTypes.Count == 0) + { + return BadRequest("You do not have approved access to this Access Type."); + } + // No type was chosen and the employee's own one is not an approved access: + // use the first approved one instead. + payrollTypeId = liveAccessTypes[0].ID; + optype = new PayrollTypeService().Get(payrollTypeId); + } + #region Save User Login History if (guser != null) { @@ -1526,20 +1552,129 @@ namespace HRM.UI.Controllers return Ok(items); } + // Maker-checker for User Access Type. The page is in the super-user menu only + // (WebMenu.AdminMenus, given to SuperUser / SISU users), so only they may request or decide. + private bool CanManageUserAccessType(CurrentUser currentUser) + { + User actingUser = this._userService.Get(currentUser.UserID); + return actingUser != null && (actingUser.UserType == EnumUserType.SuperUser || actingUser.SISU == true); + } + + private static bool IsPendingAccess(UserAccessType x) + { + return x.AccessTypeStatus == EnumAuthStatus.NewNotYetApprove + || x.AccessTypeStatus == EnumAuthStatus.DeletedNotYetApprove; + } + + // Who made a pending row: the requester of a new access, or of a removal. + private static int AccessMakerID(UserAccessType x) + { + return x.AccessTypeStatus == EnumAuthStatus.DeletedNotYetApprove ? (x.ModifiedBy ?? 0) : x.CreatedBy; + } + + // Maker: the ticked payroll types become pending changes; nothing is live until approved. [HttpPost("SaveUserAccessType")] public ActionResult SaveUserAccessType(List userAccessTypes) { try { CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); - userAccessTypes.ForEach(x => + if (!CanManageUserAccessType(currentUser)) { - x.CreatedBy = currentUser.UserID; - x.CreatedDate = DateTime.Today; - x.ApprovedBy = currentUser.UserID; - x.ApprovedDate = DateTime.Today; - }); - this._userAccessTypeService.Save(userAccessTypes); + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to change user access types."); + } + if (userAccessTypes == null || userAccessTypes.Count == 0) + { + return BadRequest("Select at least one payroll type."); + } + + int userID = userAccessTypes[0].UserID; + if (userID <= 0 || userAccessTypes.Any(x => x.UserID != userID)) + { + return BadRequest("Select a user."); + } + + List payrollTypeIDs = userAccessTypes.Select(x => x.PayrollTypeID).Distinct().ToList(); + List allPayrollTypes = this._payrollTypeService.Get(); + if (payrollTypeIDs.Any(id => !allPayrollTypes.Any(p => p.ID == id))) + { + return BadRequest("Invalid payroll type."); + } + + if (this._userAccessTypeService.GetByUserID(userID).Any(IsPendingAccess)) + { + return BadRequest("This user already has an access change waiting for approval. Approve or reject it first."); + } + + int changed = this._userAccessTypeService.RequestChange(userID, payrollTypeIDs, currentUser.UserID); + if (changed == 0) + { + return BadRequest("Nothing changed."); + } + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + + return Ok(true); + } + + // Checker: makes the user's pending access changes live. The maker cannot approve. + [HttpPost("ApproveUserAccessType/{userID}")] + public ActionResult ApproveUserAccessType(int userID) + { + try + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (!CanManageUserAccessType(currentUser)) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to approve user access types."); + } + + List pending = this._userAccessTypeService.GetByUserID(userID).Where(IsPendingAccess).ToList(); + if (pending.Count == 0) + { + return BadRequest("This user has no access change waiting for approval."); + } + if (pending.Any(x => AccessMakerID(x) == currentUser.UserID)) + { + return BadRequest("You cannot approve a change you made yourself. Another user must approve it."); + } + + this._userAccessTypeService.Approve(userID, currentUser.UserID); + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + + return Ok(true); + } + + // Checker: drops the user's pending access changes; access stays as it was. The maker cannot reject. + [HttpPost("RejectUserAccessType/{userID}")] + public ActionResult RejectUserAccessType(int userID) + { + try + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (!CanManageUserAccessType(currentUser)) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to reject user access types."); + } + + List pending = this._userAccessTypeService.GetByUserID(userID).Where(IsPendingAccess).ToList(); + if (pending.Count == 0) + { + return BadRequest("This user has no access change waiting for approval."); + } + if (pending.Any(x => AccessMakerID(x) == currentUser.UserID)) + { + return BadRequest("You cannot reject a change you made yourself. Another user must reject it."); + } + + this._userAccessTypeService.Reject(userID); } catch (Exception e) {