From 47657f6f75c9842c449784aa7f8afaa30c558f14 Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Tue, 17 Nov 2026 12:32:27 +0600 Subject: [PATCH] User Role Permission --- HRM.BO/User/UserRole.cs | 103 +++ HRM.DA/DA/Users/RoleDA.cs | 7 +- HRM.DA/DA/Users/RolePermissionDA.cs | 5 +- HRM.DA/DA/Users/UserDA.cs | 7 + HRM.DA/DA/Users/UserRoleDA.cs | 85 ++- HRM.DA/Service/Users/UserRoleService.cs | 386 +++++++++++ .../app/_models/Authentication/UserRole.ts | 56 ++ .../src/app/_services/auth/auth.service.ts | 27 +- .../user-role-entry.component.css | 408 ++++++++++- .../user-role-entry.component.html | 297 +++++--- .../user-role-entry.component.ts | 646 +++++++++--------- .../user-role-list.component.css | 464 ++++++++++++- .../user-role-list.component.html | 265 +++++-- .../user-role-list.component.ts | 395 ++++++++--- .../user-role/user-role.component.html | 5 +- HRM.UI/Controllers/Auth/AuthController.cs | 264 +++++++ 16 files changed, 2821 insertions(+), 599 deletions(-) diff --git a/HRM.BO/User/UserRole.cs b/HRM.BO/User/UserRole.cs index b8cbda5..5bbf392 100644 --- a/HRM.BO/User/UserRole.cs +++ b/HRM.BO/User/UserRole.cs @@ -68,6 +68,109 @@ namespace HRM.BO void Save(List userRoles, int payrolltypeid); void Delete(int id); + + // Maker-checker (Authentication > User Role Permission). See UserRoleMakerChecker_DB_Changes.sql. + /// The person's live roles of the subject's role type, and any change waiting for approval. + UserRoleState GetRoleState(UserRoleSubject subject); + /// Maker: records the wanted roles as pending requests. Returns how many requests were made. + int RequestChange(UserRoleChangeRequest request, int makerID); + /// Checker: makes the subject's pending requests live (creates the login first if needed). + void Approve(UserRoleSubject subject, int approverID); + /// Checker: drops the subject's pending requests; live roles stay as they were. + void Reject(UserRoleSubject subject, int approverID); + /// Every request waiting for approval, of everyone, with names for display. + List GetPending(); + } + + #endregion + + #region User role maker-checker + + /// What a UserRoleRequest asks for. + public enum EnumUserRoleRequestType + { + Add = 1, + Remove = 2, + } + + /// + /// Whose roles: an Admin user (RoleType Admin, UserID) or a Self Service employee + /// (RoleType Self_Service, EmployeeID + PayrollTypeID; UserID only once the employee has a login). + /// + public class UserRoleSubject + { + public EnumRoleType RoleType { get; set; } + public int? UserID { get; set; } + public int? EmployeeID { get; set; } + public int? PayrollTypeID { get; set; } + } + + /// Maker's request: the roles (of the subject's role type) the person should have. + public class UserRoleChangeRequest : UserRoleSubject + { + public UserRoleChangeRequest() + { + RoleIDs = new List(); + } + + public List RoleIDs { get; set; } + } + + /// + /// One UserRole row as the maker-checker screens show it (not a table of its own). A row waiting for + /// approval is a request: UserRole.Status 2 = give the role (RequestType Add, maker = CreatedBy), + /// Status 3 = take it away (RequestType Remove, maker = ModifiedBy). ID is the UserRoleID. + /// + public class UserRoleRequest : BasicBaseObject + { + public UserRoleRequest() + { + Status = EnumAuthStatus.NewNotYetApprove; + } + + public EnumUserRoleRequestType RequestType { get; set; } + public int RoleID { get; set; } + public EnumRoleType RoleType { get; set; } + public int? UserID { get; set; } + public int? EmployeeID { get; set; } + public int? PayrollTypeID { get; set; } + /// NewNotYetApprove (2) = waiting, Approved (5), Rejected (10). + public EnumAuthStatus Status { get; set; } + public int? ApprovedBy { get; set; } + public DateTime? ApprovedDate { get; set; } + + // Not database properties: filled for display. + public string RoleName { get; set; } + public string LoginID { get; set; } + public string PersonName { get; set; } + public string EmployeeNo { get; set; } + public string MakerLoginID { get; set; } + } + + /// A person's roles of one role type, as the User Role Permission page shows them. + public class UserRoleState + { + public UserRoleState() + { + LiveRoleIDs = new List(); + Pending = new List(); + } + + public EnumRoleType RoleType { get; set; } + public int? UserID { get; set; } + public int? EmployeeID { get; set; } + /// Self Service: the employee's payroll type. + public int? PayrollTypeID { get; set; } + public string LoginID { get; set; } + public string PersonName { get; set; } + /// False for a Self Service employee who has no login yet (one is made when a change is sent). + public bool HasLogin { get; set; } + /// The login was made for a change still waiting for approval (Users.Status 2): it cannot sign in yet. + public bool LoginWaiting { get; set; } + /// Roles of this role type the person has now (live). + public List LiveRoleIDs { get; set; } + /// Requests waiting for approval. + public List Pending { get; set; } } #endregion diff --git a/HRM.DA/DA/Users/RoleDA.cs b/HRM.DA/DA/Users/RoleDA.cs index 38223de..5ce8ccf 100644 --- a/HRM.DA/DA/Users/RoleDA.cs +++ b/HRM.DA/DA/Users/RoleDA.cs @@ -137,8 +137,10 @@ namespace HRM.DA //" WHERE r.RoleID= u.roleid and u.userid=%n order by PermissionCode", //useridID); + // u.Status<>2: a role given but not approved yet is not live (UserRoleMakerChecker_DB_Changes.sql). return tc.ExecuteReader(@"SELECT distinct r.*, CAST(REPLACE(r.PermissionCode, '.', '') AS int) pcode FROM RolePermission r, UserRole u - WHERE r.RoleID = u.roleid and u.userid = %n order by pcode",useridID); + WHERE r.RoleID = u.roleid and u.userid = %n and u.Status <> %n order by pcode", + useridID, (int)EnumAuthStatus.NewNotYetApprove); } internal static IDataReader GetRolePermissionByUserID(TransactionContext tc, int userID, int employeeID) @@ -157,7 +159,8 @@ namespace HRM.DA //useridID); return tc.ExecuteReader(@"SELECT distinct r.*, CAST(REPLACE(r.PermissionCode, '.', '') AS int) pcode FROM RolePermission r, UserRole u - WHERE (r.RoleID = u.roleid or r.ROLEID = 12) and u.userid = %n order by pcode", useridID); + WHERE (r.RoleID = u.roleid or r.ROLEID = 12) and u.userid = %n and u.Status <> %n order by pcode", + useridID, (int)EnumAuthStatus.NewNotYetApprove); } internal static IDataReader GetRoleActionPermissionByRoleID(TransactionContext tc, int roleID) diff --git a/HRM.DA/DA/Users/RolePermissionDA.cs b/HRM.DA/DA/Users/RolePermissionDA.cs index 9d8f374..e23733f 100644 --- a/HRM.DA/DA/Users/RolePermissionDA.cs +++ b/HRM.DA/DA/Users/RolePermissionDA.cs @@ -131,8 +131,9 @@ namespace HRM.DA return tc.ExecuteDataSet( @"select distinct rp.PERMISSIONCODE MenuKey, rp.roleid RoleID from RolePermission rp inner join UserRole ur on rp.roleID = ur.RoleID - where ur.UserID=%n and rp.STATUS=%n", - userID, (int)EnumAuthStatus.Approved); + where ur.UserID=%n and rp.STATUS=%n and ur.Status<>%n", + userID, (int)EnumAuthStatus.Approved, (int)EnumAuthStatus.NewNotYetApprove); + // ur.Status<>2: a role given but not approved yet is not live (UserRoleMakerChecker_DB_Changes.sql). } } } \ No newline at end of file diff --git a/HRM.DA/DA/Users/UserDA.cs b/HRM.DA/DA/Users/UserDA.cs index d2ae142..2e92e0d 100644 --- a/HRM.DA/DA/Users/UserDA.cs +++ b/HRM.DA/DA/Users/UserDA.cs @@ -95,6 +95,13 @@ namespace HRM.DA item.ParentID, item.UserStatus, item.ApprovedBy, item.ApprovedDate, item.ComputerName, item.ApprovedComputerName, DataReader.GetNullValue(item.ExpireDate),item.UserStatus, item.ID); } + // User Role Permission maker-checker: switches a waiting employee login on (or records its status). + internal static void UpdateStatus(TransactionContext tc, int userID, EnumAuthStatus status, int approvedBy, DateTime approvedDate) + { + tc.ExecuteNonQuery("UPDATE Users SET Status = %n, ApprovedBy=%n, ApprovedDate=%D WHERE UserID = %n", + (int)status, approvedBy, approvedDate, userID); + } + internal static void Approve(TransactionContext tc, User item) { tc.ExecuteNonQuery("UPDATE Users SET Status = %n, ApprovedBy=%n, ApprovedDate=%D,ComputerName=%s,ApprovedComputerName=%s," + diff --git a/HRM.DA/DA/Users/UserRoleDA.cs b/HRM.DA/DA/Users/UserRoleDA.cs index dc24593..9f48769 100644 --- a/HRM.DA/DA/Users/UserRoleDA.cs +++ b/HRM.DA/DA/Users/UserRoleDA.cs @@ -72,7 +72,7 @@ namespace HRM.DA } return tc.ExecuteReader( - @"SELECT ur.*, u.LOGINID LoginID, u.USERNAME UserName,R.Name RoleName FROM UserRole ur,[Users] u, Role R + @"SELECT ur.*, u.LOGINID LoginID, u.USERNAME UserName,R.Name RoleName, u.EmployeeID employeeID FROM UserRole ur,[Users] u, Role R WHERE ur.RoleID=r.RoleID and u.UserID =ur.UserID %q order by u.LoginID,R.Name", sqlClause); } @@ -144,6 +144,89 @@ namespace HRM.DA tc.ExecuteNonQuery("DELETE FROM UserRole WHERE UserID=%n", nUserID); } + #region Maker-checker (Authentication > User Role Permission, UserRoleMakerChecker_DB_Changes.sql) + + // UserRole.Status: Approved (5) = live; NewNotYetApprove (2) = given, not live until approved; + // DeletedNotYetApprove (3) = being taken away, still live until approved. + + // Maker gives a role: it waits for approval (Status 2). CreatedBy is the maker. + internal static void InsertPending(TransactionContext tc, int userRoleID, int roleID, int userID, + int makerID, DateTime requestDate) + { + tc.ExecuteNonQuery( + "INSERT INTO UserRole(UserRoleID, RoleID, UserID, EventDate, CreatedBy, Status, ComputerName, ApprovedComputerName)" + + " VALUES(%n, %n, %n, %D, %n, %n, %s, %s)", + userRoleID, roleID, userID, requestDate, makerID, (int)EnumAuthStatus.NewNotYetApprove, "", ""); + } + + // Every change below touches ONE UserRole row (by UserRoleID): the audit trigger dbo.truserrole + // handles a single row only, and a multi-row UPDATE fails inside it (Msg 512). + + // Maker takes a live role away: it stays live (Status 3) until approved. ModifiedBy is the maker. + internal static void RequestRemoval(TransactionContext tc, int userRoleID, int makerID, DateTime requestDate) + { + tc.ExecuteNonQuery( + "UPDATE UserRole SET Status=%n, ModifiedBy=%n, ModifiedDate=%D WHERE UserRoleID=%n", + (int)EnumAuthStatus.DeletedNotYetApprove, makerID, requestDate, userRoleID); + } + + // Checker approves a given role: it becomes live. AuthorizedBy / AuthorizedDate are the checker. + internal static void ApproveRow(TransactionContext tc, int userRoleID, int approverID, DateTime approveDate) + { + tc.ExecuteNonQuery( + "UPDATE UserRole SET Status=%n, AuthorizedBy=%n, AuthorizedDate=%D WHERE UserRoleID=%n", + (int)EnumAuthStatus.Approved, approverID, approveDate, userRoleID); + } + + // Checker rejects a removal: the role stays live as before. + internal static void RestoreRow(TransactionContext tc, int userRoleID) + { + tc.ExecuteNonQuery("UPDATE UserRole SET Status=%n WHERE UserRoleID=%n", + (int)EnumAuthStatus.Approved, userRoleID); + } + + // Checker approves a removal, or rejects a given role: the row goes. + internal static void DeleteRow(TransactionContext tc, int userRoleID) + { + tc.ExecuteNonQuery("DELETE FROM UserRole WHERE UserRoleID=%n", userRoleID); + } + + internal static int CountByUser(TransactionContext tc, int userID) + { + object o = tc.ExecuteScalar("SELECT COUNT(*) FROM UserRole WHERE UserID=%n", userID); + return o == null || o == DBNull.Value ? 0 : Convert.ToInt32(o); + } + + // UserRole rows with role, person and maker for the maker-checker screens. pendingOnly: only rows + // waiting for approval (Status 2 / 3). userID / roleType narrow it to one person's roles of one type. + internal static IDataReader GetForMakerChecker(TransactionContext tc, bool pendingOnly, int? userID, EnumRoleType? roleType) + { + string clause = ""; + if (pendingOnly) + clause += SQLParser.MakeSQL(" AND ur.Status IN (%n, %n)", + (int)EnumAuthStatus.NewNotYetApprove, (int)EnumAuthStatus.DeletedNotYetApprove); + if (userID.HasValue) + clause += SQLParser.MakeSQL(" AND ur.UserID=%n", userID.Value); + if (roleType.HasValue) + clause += SQLParser.MakeSQL(" AND r.RoleType=%n", (int)roleType.Value); + + return tc.ExecuteReader( + @"SELECT ur.UserRoleID, ur.RoleID, ur.UserID, ur.Status, ur.CreatedBy, ur.EventDate, + ur.ModifiedBy, ur.ModifiedDate, r.Name RoleName, r.RoleType, + u.LoginID, COALESCE(e.Name, u.UserName) PersonName, u.EmployeeID, + e.EmployeeNo, e.PayrollTypeID, mk.LoginID MakerLoginID + FROM UserRole ur + JOIN Role r ON r.RoleID = ur.RoleID + JOIN Users u ON u.UserID = ur.UserID + LEFT JOIN Employee e ON e.EmployeeID = u.EmployeeID + LEFT JOIN Users mk ON mk.UserID = CASE WHEN ur.Status = %n THEN ur.ModifiedBy ELSE ur.CreatedBy END + WHERE 1 = 1 %q + ORDER BY PersonName, r.Name", + (int)EnumAuthStatus.DeletedNotYetApprove, clause); + } + + #endregion + internal static void Update(TransactionContext tc, int id, EnumStatus status) { tc.ExecuteNonQuery("UPDATE UserRole SET Status = %n,AuthorizedBy=%n,AuthorizedDate=%D WHERE UserID = %n", diff --git a/HRM.DA/Service/Users/UserRoleService.cs b/HRM.DA/Service/Users/UserRoleService.cs index 4030992..4917b2a 100644 --- a/HRM.DA/Service/Users/UserRoleService.cs +++ b/HRM.DA/Service/Users/UserRoleService.cs @@ -437,6 +437,392 @@ namespace HRM.DA // #endregion // } //} + #region Maker-checker (Authentication > User Role Permission) + + // UserRole.Status (UserRoleMakerChecker_DB_Changes.sql): Approved (5) = live; NewNotYetApprove (2) = + // given, not live until approved; DeletedNotYetApprove (3) = being taken away, still live until approved. + + private static bool IsSelfService(UserRoleSubject subject) + { + return subject.RoleType == EnumRoleType.Self_Service; + } + + private static bool IsPendingStatus(EnumAuthStatus status) + { + return status == EnumAuthStatus.NewNotYetApprove || status == EnumAuthStatus.DeletedNotYetApprove; + } + + // The Self Service employee's login, if there is one: by EmployeeID first, then by + // LoginID = EmployeeNo (how older employee logins were made). + private User FindEmployeeLogin(int employeeID, string employeeNo) + { + UserService userService = new UserService(); + User user = userService.Get(employeeID, EnumUserType.Employee); + if (user == null && !string.IsNullOrWhiteSpace(employeeNo)) + { + User byLogin = userService.Get(employeeNo); + if (byLogin != null && byLogin.UserType == EnumUserType.Employee) + user = byLogin; + } + return user; + } + + // UserRole rows as the maker-checker screens show them. A row waiting for approval becomes a request: + // Status 2 = give the role (maker CreatedBy, asked on EventDate), Status 3 = take it away (maker + // ModifiedBy, asked on ModifiedDate). + private List ReadRows(TransactionContext tc, bool pendingOnly, int? userID, EnumRoleType? roleType) + { + List items = new List(); + DataReader dr = new DataReader(UserRoleDA.GetForMakerChecker(tc, pendingOnly, userID, roleType)); + while (dr.Read()) + { + UserRoleRequest item = new UserRoleRequest(); + base.SetObjectID(item, dr.GetInt32("UserRoleID", 0)); + item.Status = (EnumAuthStatus)dr.GetInt32("Status", (int)EnumAuthStatus.Approved); + bool isRemoval = item.Status == EnumAuthStatus.DeletedNotYetApprove; + item.RequestType = isRemoval ? EnumUserRoleRequestType.Remove : EnumUserRoleRequestType.Add; + item.RoleID = dr.GetInt32("RoleID", 0); + item.RoleType = (EnumRoleType)dr.GetInt32("RoleType", 0); + item.UserID = dr.GetInt32("UserID"); + item.EmployeeID = dr.GetInt32("EmployeeID"); + item.PayrollTypeID = dr.GetInt32("PayrollTypeID"); + item.CreatedBy = isRemoval ? dr.GetInt32("ModifiedBy", 0) : dr.GetInt32("CreatedBy", 0); + item.CreatedDate = isRemoval + ? dr.GetDateTime("ModifiedDate", DateTime.MinValue) + : dr.GetDateTime("EventDate", DateTime.MinValue); + item.RoleName = dr.GetString("RoleName"); + item.LoginID = dr.GetString("LoginID"); + item.PersonName = dr.GetString("PersonName"); + item.EmployeeNo = dr.GetString("EmployeeNo"); + item.MakerLoginID = dr.GetString("MakerLoginID"); + this.SetObjectState(item, Ease.Core.ObjectState.Saved); + items.Add(item); + } + dr.Close(); + return items; + } + + public UserRoleState GetRoleState(UserRoleSubject subject) + { + UserRoleState state = new UserRoleState(); + state.RoleType = subject.RoleType; + try + { + User login = null; + if (IsSelfService(subject)) + { + int employeeID = subject.EmployeeID ?? 0; + if (employeeID <= 0 && (subject.UserID ?? 0) > 0) + employeeID = new UserService().Get(subject.UserID.Value)?.EmployeeID ?? 0; + Employee emp = new EmployeeService().Get(employeeID); + if (emp == null || emp.ID <= 0) + throw new InvalidOperationException("Employee not found."); + state.EmployeeID = emp.ID; + state.PayrollTypeID = emp.PayrollTypeID; + state.PersonName = emp.Name; + state.LoginID = emp.EmployeeNo; + login = FindEmployeeLogin(emp.ID, emp.EmployeeNo); + } + else + { + login = new UserService().Get(subject.UserID ?? 0); + if (login == null) + throw new InvalidOperationException("User not found."); + state.PersonName = login.UserName; + } + + if (login != null) + { + state.UserID = login.ID; + state.LoginID = login.LoginID; + state.HasLogin = true; + state.LoginWaiting = login.UserStatus == EnumAuthStatus.NewNotYetApprove; + } + + if (state.HasLogin) + { + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + List rows = ReadRows(tc, false, state.UserID, subject.RoleType); + tc.End(); + state.LiveRoleIDs = rows.Where(r => r.Status != EnumAuthStatus.NewNotYetApprove) + .Select(r => r.RoleID).Distinct().ToList(); + state.Pending = rows.Where(r => IsPendingStatus(r.Status)).ToList(); + } + catch + { + if (tc != null) + tc.HandleError(); + throw; + } + } + } + catch (Exception e) + { + #region Handle Exception + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + #endregion + } + return state; + } + + public int RequestChange(UserRoleChangeRequest request, int makerID) + { + TransactionContext tc = null; + int changed = 0; + try + { + UserRoleState state = this.GetRoleState(request); + if (state.Pending.Count > 0) + throw new InvalidOperationException("This person already has a role change waiting for approval."); + + List live = state.LiveRoleIDs; + List wanted = (request.RoleIDs ?? new List()).Distinct().ToList(); + List adds = wanted.Where(r => !live.Contains(r)).ToList(); + List removes = live.Where(r => !wanted.Contains(r)).ToList(); + if (adds.Count == 0 && removes.Count == 0) + return 0; + + // A Self Service employee with no login gets one now, switched off (Status 2) until approved. + User newLogin = null; + if (IsSelfService(request) && !state.HasLogin) + { + Employee emp = new EmployeeService() + .GetByEmpIDs(state.EmployeeID.ToString(), request.PayrollTypeID ?? 0).FirstOrDefault(); + if (emp == null) + throw new InvalidOperationException("Employee not found in the selected payroll type."); + newLogin = this.NewEmployeeLogin(emp, makerID); + } + + DateTime now = DateTime.Now; + tc = TransactionContext.Begin(true); + + int userID = state.UserID ?? 0; + if (newLogin != null) + userID = new UserService().Save(tc, newLogin); + + foreach (int roleID in adds) + { + UserRoleDA.InsertPending(tc, tc.GenerateID("UserRole", "UserRoleID"), roleID, userID, makerID, now); + changed++; + } + if (removes.Count > 0) + { + // One row at a time (see UserRoleDA): every live row of each role being taken away. + foreach (UserRoleRequest row in ReadRows(tc, false, userID, request.RoleType) + .Where(r => r.Status != EnumAuthStatus.NewNotYetApprove && removes.Contains(r.RoleID))) + { + UserRoleDA.RequestRemoval(tc, row.ID, makerID, now); + } + changed += removes.Count; + } + 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(UserRoleSubject subject, int approverID) + { + TransactionContext tc = null; + Employee loginToMail = null; + try + { + UserRoleState state = this.GetRoleState(subject); + if (state.Pending.Count == 0) + throw new InvalidOperationException("No role change is waiting for approval."); + int userID = state.UserID.Value; + + // A login made by the maker for a Self Service employee is switched on now, and mailed as before. + if (IsSelfService(subject) && state.LoginWaiting) + { + loginToMail = new EmployeeService().Get(state.EmployeeID ?? 0); + } + + int? notifyEmployeeID = IsSelfService(subject) ? state.EmployeeID : new UserService().Get(userID)?.EmployeeID; + DateTime now = DateTime.Now; + + tc = TransactionContext.Begin(true); + // One row at a time (see UserRoleDA): removals go, given roles become live. + foreach (UserRoleRequest row in state.Pending) + { + if (row.RequestType == EnumUserRoleRequestType.Remove) + UserRoleDA.DeleteRow(tc, row.ID); + else + UserRoleDA.ApproveRow(tc, row.ID, approverID, now); + } + if (loginToMail != null) + UserDA.UpdateStatus(tc, userID, EnumAuthStatus.Approved, approverID, now); + + foreach (UserRoleRequest req in state.Pending.Where(p => p.RequestType == EnumUserRoleRequestType.Add)) + this.NotifyRoleGranted(tc, subject.RoleType, notifyEmployeeID, req.RoleName, req.ID, approverID); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + #endregion + } + + if (loginToMail != null && loginToMail.ID > 0) + this.MailNewLogin(new List { loginToMail }); + } + + public void Reject(UserRoleSubject subject, int approverID) + { + TransactionContext tc = null; + try + { + UserRoleState state = this.GetRoleState(subject); + if (state.Pending.Count == 0) + throw new InvalidOperationException("No role change is waiting for approval."); + int userID = state.UserID.Value; + + tc = TransactionContext.Begin(true); + // One row at a time (see UserRoleDA): given roles go, removals stay live. + foreach (UserRoleRequest row in state.Pending) + { + if (row.RequestType == EnumUserRoleRequestType.Remove) + UserRoleDA.RestoreRow(tc, row.ID); + else + UserRoleDA.DeleteRow(tc, row.ID); + } + // A login the maker made for this change, never switched on and now without any role, goes too. + if (IsSelfService(subject) && state.LoginWaiting && UserRoleDA.CountByUser(tc, userID) == 0) + UserDA.Delete(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 + } + } + + public List GetPending() + { + List items = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + items = ReadRows(tc, true, null, null); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + #endregion + } + return items; + } + + // The employee login the old Save created (same values), but switched off (Status 2) until the + // role change is approved. + private User NewEmployeeLogin(Employee emp, int parentUserID) + { + User userObject = new User(); + userObject.LoginID = emp.EmployeeNo; + userObject.UserName = emp.Name; + userObject.Password = MakePassWord(emp.BirthDate); + userObject.ParentID = parentUserID; + userObject.PasswordHints = MakePassWord(emp.BirthDate); + userObject.EmployeeID = emp.ID; + userObject.Email = string.IsNullOrWhiteSpace(emp.EmailAddress) ? null : emp.EmailAddress.Trim(); + userObject.UserStatus = EnumAuthStatus.NewNotYetApprove; + userObject.ChangePasswordAtNextLogon = true; + userObject.SISU = false; + userObject.CreatedDate = DateTime.Now; + userObject.UserType = EnumUserType.Employee; + return userObject; + } + + // The "role assigned" notification the old Save sent, now sent when the role is really live. + private void NotifyRoleGranted(TransactionContext tc, EnumRoleType roleType, int? employeeID, string roleName, + int userRoleID, int approverID) + { + if (!employeeID.HasValue || (roleType != EnumRoleType.Self_Service && roleType != EnumRoleType.Admin)) + return; + + bool hasRoleName = !string.IsNullOrWhiteSpace(roleName); + string description = roleType == EnumRoleType.Admin + ? (hasRoleName ? $"You have been granted Admin access with the role: {roleName}." : "You have been granted a new Admin role.") + : (hasRoleName ? $"You have been assigned to the Self Service role: {roleName}." : "You have been assigned a new Self Service role."); + + var notification = new EmployeeNotification + { + EmployeeID = employeeID.Value, + Header = roleType == EnumRoleType.Admin ? "New Admin Role Assigned" : "New Self Service Role Assigned", + Description = description, + Link = "", + CreatedDate = DateTime.Now, + CreatedBy = approverID, + ReferenceID = userRoleID, + IsRead = 0, + ReadDate = null, + ReadBy = null + }; + new EmployeeNotificationService().Insert(tc, notification); + } + + // The login e-mail the old Save sent to newly created employee logins (now sent on approval). + private void MailNewLogin(List oemps) + { + try + { + EmailSettings st = new EmailSettings(); + var builder = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json"); + IConfiguration Configuration = builder.Build(); + Configuration.GetSection("EmailSettings").Bind(st); + foreach (Employee emp in oemps) + { + if (!string.IsNullOrWhiteSpace(emp.EmailAddress)) + { + string password = MakePassWord(emp.BirthDate); + MailSender mailSender = new MailSender(); + mailSender.AddTo(emp.EmailAddress); + mailSender.Subject = "Your HR software Login information"; + mailSender.Body = @"Your HR software Login information are following. +

Log-in ID : " + emp.EmployeeNo + "

"; + mailSender.Body += "

Password : " + password.Trim() + "

"; + mailSender.ThreadSendMail(st); + } + } + } + catch (Exception e) + { + // The roles are already approved; a mail failure must not undo that. + ExceptionLog.Write(e); + } + } + + #endregion + internal int Save(TransactionContext tc, UserRole oUserRole, int userRoleID) { try diff --git a/HRM.UI/ClientApp/src/app/_models/Authentication/UserRole.ts b/HRM.UI/ClientApp/src/app/_models/Authentication/UserRole.ts index 5a374be..9833bd5 100644 --- a/HRM.UI/ClientApp/src/app/_models/Authentication/UserRole.ts +++ b/HRM.UI/ClientApp/src/app/_models/Authentication/UserRole.ts @@ -48,3 +48,59 @@ export class UserRole extends BaseObject { } + +// ---------- Maker-checker (Authentication > User Role Permission) ---------- + +/** What a role request asks for (EnumUserRoleRequestType on the server). */ +export enum EnumUserRoleRequestType { + Add = 1, + Remove = 2, +} + +/** Whose roles: an Admin user (userID) or a Self Service employee (employeeID + payrollTypeID). */ +export class UserRoleSubject { + roleType: EnumRoleType; + userID?: number; + employeeID?: number; + payrollTypeID?: number; +} + +/** Maker's request: the roles (of the subject's role type) the person should have. */ +export class UserRoleChangeRequest extends UserRoleSubject { + roleIDs: number[] = []; +} + +/** One UserRole row waiting for approval (Status 2 = give, 3 = take away); id is the UserRoleID. */ +export class UserRoleRequest { + id: number; + requestType: EnumUserRoleRequestType; + roleID: number; + roleType: EnumRoleType; + userID?: number; + employeeID?: number; + payrollTypeID?: number; + status: EnumAuthStatus; + createdBy: number; + createdDate: Date; + roleName: string; + loginID: string; + personName: string; + employeeNo: string; + makerLoginID: string; +} + +/** A person's roles of one role type, as the page shows them. */ +export class UserRoleState { + roleType: EnumRoleType; + userID?: number; + employeeID?: number; + payrollTypeID?: number; + loginID: string; + personName: string; + /** False for a Self Service employee who has no login yet (one is made when a change is sent). */ + hasLogin: boolean; + /** The login was made for a change still waiting for approval: it cannot sign in yet. */ + loginWaiting: boolean; + liveRoleIDs: number[] = []; + pending: UserRoleRequest[] = []; +} 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 53125cd..2b79fc3 100644 --- a/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts @@ -9,7 +9,7 @@ import { HRMNotificationService } from '../../app.notification.service'; import { Role, RolePermission } from '../../_models/Authentication/role'; import { SearchEmployee } from '../../_models/Employee/searchEmployee'; import { PayrollType } from '../../_models/Authentication/payrollType'; -import { UserRole } from '../../_models/Authentication/UserRole'; +import { UserRole, UserRoleChangeRequest, UserRoleRequest, UserRoleState, UserRoleSubject } from '../../_models/Authentication/UserRole'; import { UserAccessType } from '../../_models/Authentication/UserAccessType'; import { PasswordHistory } from '../../_models/Authentication/passwordHistory'; import { UserLogInInfo, BadLoginAttemptInfo } from '../../_models/Authentication/auditTrail'; @@ -205,6 +205,31 @@ export class AuthService { saveUserRole(params: any) { return this.apiService.httpPost('/Authentication/saveUserRole', params); } + // ---------- User Role Permission maker-checker ---------- + GetUserRoleState(roleType: EnumRoleType, userID?: number, employeeID?: number) { + return this.apiService.httpGet('/Authentication/GetUserRoleState/' + roleType + '/' + + (userID ?? 0) + '/' + (employeeID ?? 0)); + } + SaveUserRoleRequest(request: UserRoleChangeRequest) { + return this.apiService.httpPost('/Authentication/SaveUserRoleRequest', request); + } + ApproveUserRole(subject: UserRoleSubject) { + return this.apiService.httpPost('/Authentication/ApproveUserRole', subject); + } + RejectUserRole(subject: UserRoleSubject) { + return this.apiService.httpPost('/Authentication/RejectUserRole', subject); + } + /** Returns { done: number, failed: { index, message }[] } (index into the list sent). */ + ApproveUserRoles(subjects: UserRoleSubject[]) { + return this.apiService.httpPost('/Authentication/ApproveUserRoles', subjects); + } + /** Returns { done: number, failed: { index, message }[] } (index into the list sent). */ + RejectUserRoles(subjects: UserRoleSubject[]) { + return this.apiService.httpPost('/Authentication/RejectUserRoles', subjects); + } + GetPendingUserRoles() { + return this.apiService.httpGet('/Authentication/GetPendingUserRoles'); + } GetAllPayrollTypes() { return this.apiService.httpGet('/Authentication/GetAllPayrollTypes'); } diff --git a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.css b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.css index e02abfc..a42ad1e 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.css +++ b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.css @@ -1 +1,407 @@ - +/* User-Role Assignment dialog. Scoped to this component (default emulated encapsulation). + Same look as the User Access Type page (user-access-type.component.css). */ + +.ura { + display: flex; + flex-direction: column; + gap: 14px; +} + +.ura-layout { + display: grid; + grid-template-columns: 330px minmax(0, 1fr); + gap: 14px; + align-items: start; +} + +.ura-side { + display: flex; + flex-direction: column; + gap: 14px; + min-width: 0; +} + +.ura-card { + background: #FFFFFF; + border: 1px solid #E3E3EC; + border-radius: 12px; + padding: 16px; +} + +.ura-card__title { + margin: 0 0 2px; + font-size: 15px; + font-weight: 600; + color: #1a1a1a; +} + +.ura-label { + display: block; + margin-bottom: 8px; + font-size: 12px; + font-weight: 600; + color: #888888; + text-transform: uppercase; + letter-spacing: 0.05em; +} + +.ura-label--gap { + margin-top: 14px; +} + +.ura-muted { + color: #888888; + font-size: 12px; +} + +.ura-select { + width: 100%; +} + +.ura-option { + display: flex; + flex-direction: column; + line-height: 1.3; +} + +/* Admin / Self Service switch */ +.ura-switch { + display: flex; + gap: 4px; + padding: 4px; + border: 1px solid #E3E3EC; + border-radius: 10px; +} + +.ura-switch__btn { + flex: 1; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + height: 32px; + border: none; + border-radius: 8px; + background: transparent; + color: #424242; + font: inherit; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: background-color 0.15s, color 0.15s; +} + +.ura-switch__btn:hover:not(:disabled) { + background: #F3F3FF; +} + +.ura-switch__btn.is-active { + background: #52527A; + color: #FFFFFF; +} + +.ura-switch__btn:disabled:not(.is-active) { + opacity: 0.45; + cursor: default; +} + +/* Person */ +.ura-person { + display: flex; + align-items: center; + gap: 12px; + margin-top: 16px; +} + +.ura-avatar { + width: 40px; + height: 40px; + border-radius: 50%; + background: #52527A; + color: #FFFFFF; + display: flex; + align-items: center; + justify-content: center; + font-weight: 600; + flex-shrink: 0; +} + +.ura-person__info { + display: flex; + flex-direction: column; + min-width: 0; +} + +.ura-person__name { + font-weight: 600; + color: #1a1a1a; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.ura-stats { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-top: 14px; + padding: 10px 12px; + border-radius: 10px; + background: #F7F7FB; +} + +.ura-stat { + display: flex; + align-items: baseline; + gap: 6px; +} + +.ura-stat__value { + font-size: 20px; + font-weight: 700; + color: #414278; +} + +.ura-stat__label { + font-size: 12px; + color: #666666; +} + +.ura-note { + margin: 12px 0 0; + padding: 8px 10px; + border-radius: 8px; + background: #E8EEFC; + color: #2F4FB5; + font-size: 12px; +} + +/* Pending change */ +.ura-pending { + border-color: #F5D9A8; + background: #FFFAF0; + color: #8A5300; +} + +.ura-pending__head { + display: flex; + gap: 12px; + align-items: flex-start; +} + +.ura-pending__head > .pi { + font-size: 20px; + margin-top: 2px; +} + +.ura-pending__title { + margin: 0 0 2px; + font-weight: 600; + font-size: 15px; +} + +.ura-pending__text { + margin: 0; + font-size: 13px; +} + +.ura-change__label { + display: block; + margin: 12px 0 6px; + font-size: 12px; + font-weight: 600; +} + +.ura-pending__note { + margin: 12px 0 0; + font-size: 13px; + font-weight: 600; +} + +/* Chips */ +.ura-chips { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.ura-chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 10px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + line-height: 20px; +} + +.ura-chip .pi { + font-size: 10px; +} + +.ura-chip--add { background: #E6F4EC; color: #137A4B; } +.ura-chip--remove { background: #FDE8EA; color: #D11A2A; } + +/* Buttons */ +.ura-btns { + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +.ura-btns--full { + margin-top: 14px; +} + +.ura-btns--full > button { + flex: 1; +} + +/* Roles list */ +.ura-main { + min-width: 0; +} + +.ura-list__head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-bottom: 12px; +} + +.ura-list__tools { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} + +.ura-search { + width: 200px; +} + +.ura-count { + display: inline-block; + margin-left: 8px; + padding: 0 10px; + border-radius: 999px; + background: #DEDEFF; + color: #414278; + font-size: 12px; + font-weight: 600; + line-height: 22px; + vertical-align: middle; +} + +.ura-list { + border: 1px solid #E3E3EC; + border-radius: 10px; + max-height: 550px; + overflow-y: auto; +} + +.ura-row { + display: flex; + align-items: center; + gap: 12px; + margin: 0; + padding: 10px 14px; + border-bottom: 1px solid #F0F0F4; + cursor: pointer; + transition: background-color 0.15s; +} + +.ura-row:last-child { + border-bottom: none; +} + +.ura-row:hover { + background: #F7F7FB; +} + +.ura-row.is-ticked { + background: #F3F3FF; +} + +.ura-row__name { + flex: 1; + min-width: 0; + color: #1a1a1a; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.ura-list--locked .ura-row { + cursor: default; +} + +.ura-list--locked .ura-row:hover { + background: inherit; +} + +.ura-list--locked .ura-row.is-ticked:hover { + background: #F3F3FF; +} + +.ura-list__empty { + padding: 24px 16px; + text-align: center; +} + +/* Footer */ +.ura-footer { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px; + padding-top: 14px; + border-top: 1px solid #F0F0F4; +} + +.ura-footer__summary { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: center; +} + +/* Badges (same look as the User, Role and User Access Type pages) */ +.ura-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; +} + +.ura-badge__dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: currentColor; +} + +.ura-badge--success { background: #E6F4EC; color: #137A4B; } +.ura-badge--warning { background: #FFF2DB; color: #8A5300; } +.ura-badge--neutral { background: #EEEEF2; color: #5B5B6B; } +.ura-badge--info { background: #E8EEFC; color: #2F4FB5; } + +@media (max-width: 900px) { + .ura-layout { + grid-template-columns: 1fr; + } + + .ura-search { + width: 100%; + } +} diff --git a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.html b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.html index 44fbed8..340deab 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.html +++ b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.html @@ -1,123 +1,196 @@ - -
-
- -
-
+ - - -
-
-
-
-@if (_selectedRoleType == roletypeEnum.Admin) { -
-
-
- +
+
+ + +
+
+ Role type +
+ + +
+ + @if (roleType == roletypeEnum.Admin) { + + + + + {{ dataItem?.userName }} + @if (dataItem?.loginID) { {{ dataItem.loginID }} } + + + + } + + @if (roleType == roletypeEnum.Self_Service) { + + + + + @if (!openFor) { + + @if (selectedPayrollTypeID) { + + } @else { +

Select a payroll type first.

+ } + } + } + + @if (state) { +
+
{{ (state.personName || '?').charAt(0) | uppercase }}
+
+ {{ state.personName }} + {{ state.loginID }} +
+
+
+
+ {{ state.liveRoleIDs.length }} + {{ state.liveRoleIDs.length == 1 ? 'role' : 'roles' }} now +
+ @if (hasPending) { + Waiting for approval + } @else { + Up to date + } +
+ @if (!state.hasLogin) { +

No login yet. Sending this change creates one, switched off; it can sign in, and the login details are e-mailed, only after approval.

+ } @else if (state.loginWaiting) { +

The login is waiting for this change to be approved and cannot sign in yet.

+ } + }
-
- - + + + @if (state && hasPending) { +
+
+ +
+

Change waiting for approval

+

+ Requested by {{ pendingMaker || '-' }} + @if (pendingDate) { on {{ pendingDate | date: 'dd MMM yyyy, h:mm a' }} }. + Until it is approved, {{ state.personName }} keeps the current roles. +

+
+
+ @if (pendingAddNames.length > 0) { + Will get +
+ @for (n of pendingAddNames; track n) { {{ n }} } +
+ } + @if (pendingRemoveNames.length > 0) { + Will lose +
+ @for (n of pendingRemoveNames; track n) { {{ n }} } +
+ } + @if (isMakerOfPending) { +

You made this change, so another administrator must approve or reject it.

+ } +
+ + +
+
+ } +
+ + +
+
+
+

+ Roles + @if (state) { {{ selectedRoleIDs.length }} of {{ rolesForType.length }} selected } +

+

+ @if (!state) { Select {{ roleType == roletypeEnum.Admin ? 'a user' : 'an employee' }} to see and change their roles. } + @else if (hasPending) { Locked while the change waits for approval. } + @else { Tick the roles this person should have. Only approved roles can be given. } +

+
+
+ + @if (state && !hasPending) { + + + } +
-
- + +
+ @for (r of visibleRoles; track r.id) { + + } @empty { +
No role matches.
+ }
-} -@if (_selectedRoleType == roletypeEnum.Self_Service) { -
-
-
- -
-
- - -
-
- -
-
- -
- -
-
-} -
-
-
- - - - - + + -
-
- - +
+ + @if (state && !hasPending) { + + + }
- - diff --git a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.ts b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.ts index fc5a2fa..c2350d9 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.ts +++ b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.ts @@ -1,370 +1,352 @@ import {Component, EventEmitter, OnInit, Output, Input, ChangeDetectionStrategy} from '@angular/core'; -import {FormControl, FormGroup} from '@angular/forms'; 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 {ActivatedRoute, Router} from '@angular/router'; -import {EnumExtension, EnumRoleType, EnumUserType, EnumAuthStatus} from '../../../_models/enums'; -import {SelectableSettings} from '@progress/kendo-angular-grid'; -import {UserRole} from '../../../_models/Authentication/UserRole'; +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 { EmployeeServices } from '../../../_services/employee/employee.service'; -import { UntilityHandlerService } from '../../../utility.hanldler.service'; - -import { LoadingPanelComponent } from 'src/app/hrm-loding panel/loading-panel.component'; -import { ButtonModule } from '@progress/kendo-angular-buttons'; -import { DropDownListModule } from '@progress/kendo-angular-dropdowns'; -import { ReactiveFormsModule } from '@angular/forms'; -import { FormsModule } from '@angular/forms'; - -import { KENDO_GRID } from '@progress/kendo-angular-grid'; -import { DatePickerModule } from '@progress/kendo-angular-dateinputs'; 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, + standalone: false, }) - export class UserRoleEntryComponent implements OnInit { - userRolePermissionForm: FormGroup; - public active = false; - _userRoles: UserRole[]; - _allroles: Role[]; - _gridRoles: Role[]; - _users: User[]; - _gridUsers: User[]; - _selectedUserID: number; - _previousRoles: number[] = []; - _selectedRoles: number[] = []; - _selectedRoleType: EnumRoleType ; - roletypeEnum: typeof EnumRoleType = EnumRoleType; - _payrollTypes: PayrollType[]; - _selectedPayrollTypeid: number; - roleTypes: any = EnumExtension.getNamesAndValues(EnumRoleType); - public selectableSettings: SelectableSettings; - @Output() saveCompleted: EventEmitter = new EventEmitter(); - _selectedEmployees: SearchEmployee[]; - _selectedLoginIDs: string[]; - _initializeValue : boolean; - constructor(public userService: AuthService, - public apiService: ApiService, - public notificationService: HRMNotificationService, - public router: Router, - public route: ActivatedRoute, public employeeService: EmployeeServices, - public utilityService: UntilityHandlerService) { + 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(); + } } - @Input() public set InitializeForm(initializeValue: boolean) { - this._initializeValue = initializeValue; - if (this._initializeValue == true) { - this._gridRoles = []; - this._gridUsers = []; - this._selectedEmployees = []; - this._selectedLoginIDs = []; - this._selectedPayrollTypeid = undefined; - this._selectedRoleType = undefined; - } + /** 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.utilityService.ShowLoadingPanel = true; - this._selectedRoleType = null; - this._gridUsers = []; - this._gridRoles = []; - this._selectedUserID = 0; - this._selectedLoginIDs = []; - this.userRolePermissionForm = new FormGroup({ - selectedUsers: new FormControl() + 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 ?? []; }); - this.userService.GetUsers(EnumUserType.User) - .subscribe( - (resp: any) => { - this._users = resp; - }, - (err: any) => { - // ON ERROR - }, - () => { - // ON Success - // this.loadGrid(); - } - ); - - - this.userService.getAllRoles() - .subscribe( - (resp: any) => { - this._allroles = resp; - }, - (err: any) => { - // ON ERROR - }, - () => { - this.pageLoaded(); - } - ); - - - this.userService.GetAllPayrollTypes() - .subscribe( - (resp: any) => { - this._payrollTypes = resp; - }, - (err: any) => { - //ON ERROR - }, - () => { - - } - ); - - this.setSelectableSettings(); - } - pageLoaded() { - this.utilityService.ShowLoadingPanel = false; - } - - setSelectableSettings(): void { - this.selectableSettings = { - checkboxOnly: true, - mode: 'multiple', // this.mode - }; - } - - onRoleChange(value: any) { - this._gridRoles = []; - this._selectedRoles = []; - this._gridUsers = []; - this._gridRoles = this._allroles.filter(x => x.roleType === this._selectedRoleType); - } - - SearchUnAssingedEmp() { - this.utilityService.ShowLoadingPanel = true; - this.employeeService.GetEmployeeNotYetUser(this._selectedPayrollTypeid) - .subscribe( - (resp: any) => { - this._selectedEmployees = resp; - }, - (err: any) => { - //ON ERROR - this.utilityService.ShowLoadingPanel = false; - }, - () => { - this.utilityService.ShowLoadingPanel = false; - - this._selectedEmployees.forEach(x => { - var ouser: User = new User(); - ouser.loginID = x.employeeNo; - ouser.userName = x.name; - ouser.employeeID = x.employeeID; - var Item = this._gridUsers.find(u => u.employeeID == x.employeeID); - if (Item == undefined) - this._gridUsers.push(ouser) - }); - } - ); - } - - public onSelectionRoleChange(event: any): void { - // this._selectedRoles = event.selectedRows.map(r => r.dataItem.id); - } - - public Remove(nIndex:number) { - this._gridUsers.splice(nIndex, 1); - } - - public onSave(): void { - if (this._gridUsers.length == 0) { - this.notificationService.showError("There is no user/employee selected"); - return; - } - if (this._selectedRoles.length == 0) { - this.notificationService.showError("please select a role"); - return; - - } - - let userRoles: UserRole[] = []; - this._gridUsers.forEach(u => { - this._selectedRoles.forEach(r => { - var userRole: UserRole = new UserRole(); - if (this._selectedRoleType == EnumRoleType.Self_Service) { - userRole.payrollTypeID = this._selectedPayrollTypeid; - userRole.employeeID = u.employeeID; - userRole.roleType = EnumRoleType.Self_Service; - } - if (this._selectedRoleType == EnumRoleType.Admin) - { - userRole.userID = u.id; - userRole.roleType = EnumRoleType.Admin; - } - userRole.loginIDView = u.loginID; - userRole.roleID = r; - userRoles.push(userRole); - }); - - }); - this.utilityService.ShowLoadingPanel = true; - if(userRoles && userRoles.length > 0) - { - userRoles.forEach(x=> { - let isFind = this._previousRoles.some(y => y === x.roleID); - if(!isFind){ - x.isOld = false; - let role = this._gridRoles.find(z => z.id === x.roleID); - if(role && role.id > 0){ - x.newRoleName = role.name; - } - } - }); - } - this.userService.saveUserRole(userRoles) - .subscribe( - (resp: any) => { - }, - (err: any) => { - //ON ERROR - this.notificationService.showSuccess(err.error); - this.utilityService.ShowLoadingPanel = false; - }, - () => { - this.saveCompleted.emit(true); - this.utilityService.ShowLoadingPanel = false; - this.notificationService.showSuccess("Data Saved Successfully."); - } - ); - - - } - - public GetSelectedEmployee(childData) { - this._selectedEmployees = childData; - if (this._selectedEmployees == undefined) { - return; - } - - this._selectedEmployees.forEach(x => { - - var ouser: User = new User(); - ouser.loginID = x.employeeNo; - ouser.userName = x.name; - ouser.employeeID = x.employeeID; - - var Item = this._gridUsers.find(u => u.employeeID == x.employeeID); - if (Item == undefined) - this._gridUsers.push(ouser); - - - - }); - this.AddEmployeeAsUser(); -} - AddUser() { - this.userService.getUserRoles(EnumRoleType.Admin, this._selectedUserID); - let oUser: User = this._users.find(x => x.id === this._selectedUserID); - let userRole: UserRole[]; - this.userService.getUserRoles(EnumRoleType.Admin, this._selectedUserID) - - .subscribe( - (resp: any) => { - this._userRoles = resp; - }, - (err: any) => { - // ON ERROR - }, - () => { - - const Users: User[] = []; - Users.push(oUser); - var uRole: UserRole = new UserRole(); - - var Item = this._gridUsers.find(u => u.id == oUser.id); - if (Item == undefined) - this._gridUsers.push(oUser); - - this.setPrviousRole(); - } - ); - } - private setPrviousRole() { - this._gridUsers.forEach(x => { - var empUseRoles: UserRole[] = this._userRoles.filter(t => t.loginIDView == x.loginID) - if (empUseRoles != undefined) { - empUseRoles.forEach(u => { - if (x.roleNames == undefined) x.roleNames = ''; - x.roleNames = x.roleNames + u.roleNameView + ", "; - x.id = u.userID; - - if (this._selectedRoles.findIndex(r => r == u.roleID) == -1) { - this._selectedRoles.push(u.roleID); - } - }) + 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._selectedRoles = [...this._selectedRoles]; - this._previousRoles = [...this._selectedRoles]; + this.loadState(this.openFor.userID, this.openFor.employeeID); + } } - AddEmployeeAsUser() { - this.userService.GetEmpUserRole(this._selectedEmployees).subscribe( - (resp: any) => { - this._userRoles = resp; + // ---------- 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.setPrviousRole(); + this.loadingPanel.ShowLoadingPanel = false; } ); - - return; - - this._users = []; - this._selectedEmployees.forEach(x => { - var ouser: User = new User(); - ouser.loginID = x.employeeNo; - ouser.userName = x.name; - oUser.userStatus = EnumAuthStatus.New_Not_Yet_Approve; - this._users.push(oUser); - }); - this.userService.getUserRoles(EnumRoleType.Admin, this._selectedUserID); - let oUser: User = this._users.find(x => x.id === this._selectedUserID); - let userRole: UserRole[]; - this.userService.getUserRoles(EnumRoleType.Admin, this._selectedUserID) - - .subscribe( - (resp: any) => { - userRole = resp; - }, - (err: any) => { - // ON ERROR - }, - () => { - - const Users: User[] = []; - Users.push(oUser); - /*var uRole: UserRole = new UserRole(); - uRole.getRoleNames(Users, this.userRoles);*/ - var uRole: UserRole = new UserRole(); - // uRole.getRoleNames(Users, userRole); - this._gridUsers.push(oUser); - } - ); } - public onCancel(e): void { + // ---------- 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); } - - private closeForm(): void { - } - } diff --git a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.css b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.css index e02abfc..5c06e6f 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.css +++ b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.css @@ -1 +1,463 @@ - +/* User Role Permission page. This component uses ViewEncapsulation.None, so every rule carries the + url- prefix (grid rules sit under .url-grid). Same look as User Access Type / Role / User pages. */ + +.url-page { + display: flex; + flex-direction: column; + gap: 14px; +} + +/* ---------- header ---------- */ + +.url-header { + display: flex; + align-items: center; + gap: 14px; +} + +.url-header__icon { + width: 44px; + height: 44px; + border-radius: 10px; + background: #DEDEFF; + color: #414278; + display: flex; + align-items: center; + justify-content: center; + font-size: 20px; + flex-shrink: 0; +} + +.url-title { + margin: 0 0 2px; + font-size: 18px; + font-weight: 600; + color: #1a1a1a; +} + +.url-subtitle { + margin: 0; + font-size: 13px; + color: #888888; +} + +.url-muted { + color: #888888; + font-size: 12px; +} + +.url-block { + display: block; +} + +/* ---------- view switch ---------- */ + +.url-views { + display: inline-flex; + gap: 4px; + padding: 4px; + border: 1px solid #E3E3EC; + border-radius: 10px; + background: #FFFFFF; + align-self: flex-start; +} + +.url-view { + display: inline-flex; + align-items: center; + gap: 8px; + height: 34px; + padding: 0 14px; + border: none; + border-radius: 8px; + background: transparent; + color: #424242; + font: inherit; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: background-color 0.15s, color 0.15s; +} + +.url-view:hover { + background: #F3F3FF; +} + +.url-view.is-active { + background: #52527A; + color: #FFFFFF; +} + +.url-view__count { + min-width: 20px; + padding: 0 6px; + border-radius: 999px; + background: #EEEEF2; + color: #5B5B6B; + font-size: 12px; + line-height: 18px; + text-align: center; +} + +.url-view__count.has-items { + background: #FFF2DB; + color: #8A5300; +} + +.url-view.is-active .url-view__count { + background: rgba(255, 255, 255, 0.22); + color: #FFFFFF; +} + +/* ---------- grid toolbar ---------- */ + +.url-grid .k-grid-toolbar { + padding: 8px 12px; +} + +.url-grid .k-grid-table td { + padding-top: 6px; + padding-bottom: 6px; + vertical-align: middle; +} + +.url-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 12px; + width: 100%; + padding: 4px 0; +} + +.url-toolbar__filters, +.url-toolbar__actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.url-search { + width: 240px; +} + +.url-switch { + display: inline-flex; + gap: 2px; + padding: 3px; + border: 1px solid #E3E3EC; + border-radius: 8px; + background: #FFFFFF; +} + +.url-switch__btn { + height: 28px; + padding: 0 12px; + border: none; + border-radius: 6px; + background: transparent; + color: #424242; + font: inherit; + font-size: 13px; + font-weight: 600; + cursor: pointer; +} + +.url-switch__btn:hover { + background: #F3F3FF; +} + +.url-switch__btn.is-active { + background: #52527A; + color: #FFFFFF; +} + +/* Status chips (same as the User and Role pages) */ +.url-chips { + display: inline-flex; + flex-wrap: wrap; + gap: 6px; +} + +.url-chip { + display: inline-flex; + align-items: center; + gap: 6px; + height: 30px; + padding: 0 12px; + border: 1px solid #E3E3EC; + border-radius: 999px; + background: #FFFFFF; + color: #424242; + font: inherit; + font-size: 13px; + cursor: pointer; + transition: background-color 0.15s, border-color 0.15s, color 0.15s; +} + +.url-chip:hover { + border-color: #52527A; +} + +.url-chip.is-selected { + background: #52527A; + border-color: #52527A; + color: #FFFFFF; +} + +.url-chip__count { + min-width: 20px; + padding: 0 6px; + border-radius: 999px; + background: #F1F1F1; + color: #666666; + font-size: 12px; + line-height: 18px; + text-align: center; +} + +.url-chip.is-selected .url-chip__count { + background: rgba(255, 255, 255, 0.22); + color: #FFFFFF; +} + +.url-chip--pending:not(.is-selected) .url-chip__count { + background: #FFF2DB; + color: #8A5300; +} + +/* ---------- grid cells ---------- */ + +.url-login { + font-weight: 600; + color: #424242; +} + +.url-roles { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.url-role { + display: inline-block; + padding: 1px 8px; + border-radius: 999px; + background: #F3F3FF; + color: #414278; + font-size: 12px; + font-weight: 600; + line-height: 20px; + white-space: nowrap; +} + +.url-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; +} + +.url-badge__dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: currentColor; +} + +.url-badge--success { background: #E6F4EC; color: #137A4B; } +.url-badge--warning { background: #FFF2DB; color: #8A5300; } +.url-badge--neutral { background: #EEEEF2; color: #5B5B6B; } + +.url-empty { + padding: 32px 16px; + color: #888888; + text-align: center; +} + +.url-empty--big { + padding: 48px 16px; +} + +.url-empty__icon { + font-size: 32px; + color: #C9C9D6; +} + +.url-empty__title { + margin: 10px 0 4px; + font-weight: 600; + color: #424242; +} + +/* ---------- pending approvals ---------- */ + +.url-card { + background: #FFFFFF; + border: 1px solid #E3E3EC; + border-radius: 12px; + padding: 16px; +} + +.url-card__head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-bottom: 12px; +} + +.url-card__title { + margin: 0 0 2px; + font-size: 15px; + font-weight: 600; + color: #1a1a1a; +} + +.url-table-wrap { + border: 1px solid #E3E3EC; + border-radius: 10px; + overflow: auto; + max-height: 560px; +} + +.url-table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +.url-table th { + position: sticky; + top: 0; + z-index: 1; + background: #F7F7FB; + color: #666666; + font-size: 12px; + font-weight: 600; + text-align: left; + padding: 10px 12px; + border-bottom: 1px solid #E3E3EC; + white-space: nowrap; +} + +.url-table td { + padding: 10px 12px; + border-bottom: 1px solid #F0F0F4; + vertical-align: top; +} + +.url-table tbody tr:last-child td { + border-bottom: none; +} + +.url-table tbody tr:hover { + background: #F7F7FB; +} + +.url-table tbody tr.is-selected { + background: #F3F3FF; +} + +.url-table tbody tr.is-mine { + color: #888888; +} + +.url-table__check { + width: 40px; + text-align: center; +} + +.url-table__open { + width: 70px; + text-align: right; +} + +.url-person { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} + +.url-type { + padding: 0 8px; + border-radius: 999px; + background: #E8EEFC; + color: #2F4FB5; + font-size: 11px; + font-weight: 600; + line-height: 18px; +} + +.url-type--ess { + background: #F1EAFB; + color: #6B3FA0; +} + +.url-chips-inline { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.url-mini { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 1px 8px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + line-height: 20px; +} + +.url-mini .pi { + font-size: 9px; +} + +.url-mini--add { background: #E6F4EC; color: #137A4B; } +.url-mini--remove { background: #FDE8EA; color: #D11A2A; } + +.url-requested { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px 10px; +} + +.url-savebar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-top: 14px; + padding-top: 14px; + border-top: 1px solid #F0F0F4; +} + +.url-btns { + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +@media (max-width: 768px) { + .url-toolbar__actions { + width: 100%; + justify-content: flex-end; + } + + .url-search { + width: 100%; + } +} diff --git a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.html b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.html index 17c9ae0..1c239c3 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.html +++ b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.html @@ -1,67 +1,220 @@ -
-
-
- -
-
+ - - -
-
- -
-
+
+ + +
+
+
+

User Role Permission

+

Give users and employees their roles. Every change is approved by another administrator before it takes effect.

-
-
- - - - - - - - - - - - - - - +
+ + +
+ + + @if (activeView === 'assignments') { + + +
+
+
+ + +
+ +
+ + + +
+
+
+ + + + +
+
- - --> -
-
+ + + + + + + + +
+ @for (r of dataItem.roles; track r) { {{ r }} } +
+
+
+ + + + {{ dataItem.statusText }} + + + + + + + + -
+ +
+ @if (rows.length === 0) { No {{ listRoleType == roletypeEnum.Admin ? 'admin user' : 'self service user' }} has a role yet. } + @else { No one matches the current search or filters. } +
+
- - @if (showModal) { - - - User-Role Assignment - - - - + + + + + + + + + + + + + } + + @if (activeView === 'pending') { +
+
+
+

Pending approvals

+

Everyone whose role change is waiting for approval. Select several and approve or reject them at once.

+
+ +
+ + @if (pendingGroups.length === 0) { +
+ +

Nothing to approve

+

No role change is waiting for approval.

+
+ } @else { +
+ + + + + + + + + + + + + @for (g of pendingGroups; track g.key) { + + + + + + + + + } + +
+ + PersonWill getWill loseRequested by
+ + +
+ + + {{ g.roleType == roletypeEnum.Self_Service ? 'Self Service' : 'Admin' }} + +
+ {{ g.loginID }} +
+
+ @for (n of g.adds; track n) { {{ n }} } + @if (g.adds.length === 0) { - } +
+
+
+ @for (n of g.removes; track n) { {{ n }} } + @if (g.removes.length === 0) { - } +
+
+
+ {{ g.makers.join(', ') || '-' }} + @if (g.requestDate) { {{ g.requestDate | date: 'dd MMM yyyy, h:mm a' }} } + @if (g.isMine) { Your change } +
+
+ +
+
+ +
+ {{ selectedPendingKeys.length }} of {{ selectablePending.length }} selected +
+ + +
+
+ } +
+ }
+ + +@if (showModal) { +
+ + + + +
+} diff --git a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.ts b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.ts index 170595f..0e5944e 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.ts +++ b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.ts @@ -1,122 +1,343 @@ import { Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy } from '@angular/core'; import { HRMNotificationService } from '../../../app.notification.service'; -import { DataTransferService } from '../../../data.transfer.service'; -import { UntilityHandlerService } from '../../../utility.hanldler.service'; import { AuthService } from '../../../_services/auth/auth.service'; -import { EnumRoleType, EnumUserType, EnumExtension, EnumAuthStatus } from '../../../_models/enums'; -import { User } from '../../../_models/Authentication/user'; -import { DataStateChangeEvent, GridDataResult } from '@progress/kendo-angular-grid'; -import { process, State } from '@progress/kendo-data-query'; +import { EnumAuthStatus, EnumRoleType } from '../../../_models/enums'; +import { ExcelExportData } from '@progress/kendo-angular-excel-export'; +import { process } from '@progress/kendo-data-query'; import { ApiService } from '../../../app.api.service'; +import { loadingPanelService } from '../../../hrm-loding panel/loding.panel.service'; +import { EnumUserRoleRequestType, UserRoleSubject } from '../../../_models/Authentication/UserRole'; -import { ButtonModule } from '@progress/kendo-angular-buttons'; -import { DropDownListModule } from '@progress/kendo-angular-dropdowns'; -import { ReactiveFormsModule } from '@angular/forms'; -import { FormsModule } from '@angular/forms'; +/** One person in the All assignments grid (one row per person, roles as chips). */ +interface AssignmentRow { + key: string; + userID: number; + employeeID: number; + loginID: string; + userName: string; + roles: string[]; + rolesText: string; + pending: boolean; + statusText: string; +} -import { KENDO_GRID } from '@progress/kendo-angular-grid'; -import { DatePickerModule } from '@progress/kendo-angular-dateinputs'; +/** One person with a role change waiting for approval. */ +interface PendingGroup { + key: string; + roleType: EnumRoleType; + userID: number; + employeeID: number; + payrollTypeID: number; + personName: string; + loginID: string; + adds: string[]; + removes: string[]; + makers: string[]; + makerIDs: number[]; + requestDate: Date; + isMine: boolean; +} +/** + * Authentication > User Role Permission: who has which roles (All assignments), the role changes + * waiting for approval (Pending approvals, many at once), and the User-Role Assignment dialog. + */ @Component({ selector: 'app-user-role-list', templateUrl: './user-role-list.component.html', + styleUrls: ['./user-role-list.component.css'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.Eager, - standalone: false, - + standalone: false, }) -/** user-role-list component*/ export class UserRoleListComponent implements OnInit { - public isNew: boolean; - userRole: any; - users: User[]; - userRoles: any[]; - showModal = false; - _selectedRoleType: EnumRoleType; - roleTypes: any = EnumExtension.getNamesAndValues(EnumRoleType); - initializeEntryFrom: boolean; - gridView: GridDataResult; - public state: State = { - skip: 0, - take: 10 - }; + readonly roletypeEnum: typeof EnumRoleType = EnumRoleType; + + activeView: 'assignments' | 'pending' = 'assignments'; + listRoleType: EnumRoleType = EnumRoleType.Admin; + currentUserID: number; + + // All assignments + rows: AssignmentRow[] = []; + gridView: AssignmentRow[] = []; + searchText = ''; + statusFilter: 'all' | 'pending' | 'uptodate' = 'all'; + + // Pending approvals + pendingGroups: PendingGroup[] = []; + selectedPendingKeys: string[] = []; + + // Dialog + showModal = false; + initializeEntryFrom = false; + openFor: UserRoleSubject; - /** user-role-list ctor */ constructor(public userService: AuthService, - public notificationService: HRMNotificationService, - public datatransferservice: DataTransferService, - public utilityHandlerService: UntilityHandlerService, public apiService: ApiService,) { - this.apiService.selectedMenuName="User Role Permission Entry" + public notificationService: HRMNotificationService, + public apiService: ApiService, + public loadingPanel: loadingPanelService) { + this.apiService.selectedMenuName = 'User Role Permission Entry'; + this.allData = this.allData.bind(this); } public ngOnInit(): void { - this.showModal = false; - this.initializeEntryFrom = false; + this.userService.GetCurrentUser().subscribe((resp: any) => { + this.currentUserID = resp?.userID; + this.loadPending(); + }); + this.RefreshControl(); } - public RefreshControl() { - this.userService.getUserRoles(this._selectedRoleType) - .subscribe( - (resp: any) => { - this.userRoles = resp; - }, - (err: any) => { - //ON ERROR - }, - () => { - this.gridView = process(this.userRoles, this.state); + // ---------- All assignments ---------- + + setListRoleType(type: EnumRoleType): void { + if (this.listRoleType == type) { + return; + } + this.listRoleType = type; + this.RefreshControl(); + } + + /** Loads who has which roles of the selected role type. */ + public RefreshControl(): void { + this.loadingPanel.ShowLoadingPanel = true; + this.userService.getUserRoles(this.listRoleType).subscribe( + (resp: any[]) => { + const byUser = new Map(); + (resp ?? []).forEach(r => { + let row = byUser.get(r.userID); + if (!row) { + row = { + key: 'u' + r.userID, userID: r.userID, employeeID: r.employeeID, loginID: r.loginIDView, + userName: r.userNameView, roles: [], rolesText: '', pending: false, statusText: '', + }; + byUser.set(r.userID, row); + } + // Only live roles are shown: a role given but not approved yet (Status 2) is not live. + if (r.userRoleStatus != EnumAuthStatus.New_Not_Yet_Approve + && r.roleNameView && !row.roles.includes(r.roleNameView)) { + row.roles.push(r.roleNameView); + } + }); + this.rows = Array.from(byUser.values()); + this.rows.forEach(r => r.rolesText = r.roles.join(', ')); + this.markPendingRows(); + }, + (err: any) => { + this.loadingPanel.ShowLoadingPanel = false; + this.notificationService.showError(err?.error ?? err); + }, + () => { + this.loadingPanel.ShowLoadingPanel = false; + } + ); + } + + private pendingFor(row: AssignmentRow): PendingGroup { + return this.pendingGroups.find(g => g.roleType == this.listRoleType && g.userID == row.userID); + } + + private markPendingRows(): void { + this.rows.forEach(r => { + r.pending = !!this.pendingFor(r); + r.statusText = r.pending ? 'Waiting for approval' : 'Up to date'; + }); + this.applyView(); + } + + get counts() { + const pending = this.rows.filter(r => r.pending).length; + return { all: this.rows.length, pending, uptodate: this.rows.length - pending }; + } + + onSearch(value: string): void { + this.searchText = value ?? ''; + this.applyView(); + } + + setStatusFilter(filter: 'all' | 'pending' | 'uptodate'): void { + this.statusFilter = filter; + this.applyView(); + } + + private applyView(): void { + const t = this.searchText.trim().toLowerCase(); + this.gridView = this.rows.filter(r => + (this.statusFilter === 'all' || (this.statusFilter === 'pending') === r.pending) && + (!t || (r.loginID ?? '').toLowerCase().includes(t) || (r.userName ?? '').toLowerCase().includes(t) + || r.rolesText.toLowerCase().includes(t))); + } + + /** Excel export: every row the grid shows (all pages). */ + public allData(): ExcelExportData { + return { data: process(this.gridView, {}).data }; + } + + // ---------- Pending approvals ---------- + + /** Every pending row has a login (made with the change for a new Self Service employee). */ + private subjectKey(roleType: EnumRoleType, userID: number): string { + return (roleType == EnumRoleType.Self_Service ? 's' : 'a') + userID; + } + + loadPending(): void { + this.userService.GetPendingUserRoles().subscribe( + (items: any[]) => { + const groups = new Map(); + (items ?? []).forEach(p => { + const key = this.subjectKey(p.roleType, p.userID); + let g = groups.get(key); + if (!g) { + g = { + key, roleType: p.roleType, userID: p.userID, employeeID: p.employeeID, + payrollTypeID: p.payrollTypeID, personName: p.personName, loginID: p.loginID, + adds: [], removes: [], makers: [], makerIDs: [], requestDate: null, isMine: false, + }; + groups.set(key, g); + } + (p.requestType == EnumUserRoleRequestType.Remove ? g.removes : g.adds).push(p.roleName); + if (p.makerLoginID && !g.makers.includes(p.makerLoginID)) { + g.makers.push(p.makerLoginID); + } + if (p.createdBy && !g.makerIDs.includes(p.createdBy)) { + g.makerIDs.push(p.createdBy); + } + const d = p.createdDate ? new Date(p.createdDate) : null; + if (d && (!g.requestDate || d > g.requestDate)) { + g.requestDate = d; + } + }); + this.pendingGroups = Array.from(groups.values()); + this.pendingGroups.forEach(g => g.isMine = g.makerIDs.includes(this.currentUserID)); + this.selectedPendingKeys = this.selectedPendingKeys.filter(k => + this.pendingGroups.some(g => g.key == k && !g.isMine)); + this.markPendingRows(); + }, + () => { + this.pendingGroups = []; + } + ); + } + + get selectablePending(): PendingGroup[] { + return this.pendingGroups.filter(g => !g.isMine); + } + + isPendingSelected(key: string): boolean { + return this.selectedPendingKeys.includes(key); + } + + togglePendingSelection(g: PendingGroup): void { + if (g.isMine) { + return; + } + this.selectedPendingKeys = this.isPendingSelected(g.key) + ? this.selectedPendingKeys.filter(k => k != g.key) + : [...this.selectedPendingKeys, g.key]; + } + + get allPendingSelected(): boolean { + return this.selectablePending.length > 0 && this.selectablePending.every(g => this.isPendingSelected(g.key)); + } + + toggleAllPending(): void { + this.selectedPendingKeys = this.allPendingSelected ? [] : this.selectablePending.map(g => g.key); + } + + private toSubject(g: PendingGroup): UserRoleSubject { + const s = new UserRoleSubject(); + s.roleType = g.roleType; + s.userID = g.userID ?? undefined; + s.employeeID = g.employeeID ?? undefined; + s.payrollTypeID = g.payrollTypeID ?? undefined; + return s; + } + + bulkApprove(): void { + this.bulkDecide(true); + } + + bulkReject(): void { + this.bulkDecide(false); + } + + private bulkDecide(approve: boolean): void { + const groups = this.pendingGroups.filter(g => this.isPendingSelected(g.key)); + if (groups.length == 0) { + this.notificationService.showWarning('Select at least one person.'); + return; + } + const subjects = groups.map(g => this.toSubject(g)); + const call = approve ? this.userService.ApproveUserRoles(subjects) : this.userService.RejectUserRoles(subjects); + let result: any; + this.loadingPanel.ShowLoadingPanel = true; + call.subscribe( + (resp: any) => { result = resp; }, + (err: any) => { + this.loadingPanel.ShowLoadingPanel = false; + this.notificationService.showError(err?.error ?? err); + }, + () => { + this.loadingPanel.ShowLoadingPanel = false; + const done = result?.done ?? 0; + const failed: any[] = result?.failed ?? []; + if (done > 0) { + this.notificationService.showSuccess( + (approve ? 'Approved' : 'Rejected') + ' for ' + done + (done == 1 ? ' person.' : ' people.')); } - ); - } - public dataStateChange(state: DataStateChangeEvent): void { - this.state = state; - this.gridView = process(this.userRoles, this.state); - } - public onFilter(inputValue: string): void { - } - onRoleChange() { - this.userRoles = []; + if (failed.length > 0) { + this.notificationService.showError(failed.map(f => + (groups[f.index]?.personName ?? 'Person ' + (f.index + 1)) + ': ' + f.message).join(' | ')); + } + this.selectedPendingKeys = []; + this.loadPending(); + this.RefreshControl(); + } + ); } - public addHandler() { + // ---------- User-Role Assignment dialog ---------- + + /** New assignment: pick the person in the dialog. */ + public addHandler(): void { + this.openFor = undefined; + this.openDialog(); + } + + /** Change one person's roles from the All assignments grid. */ + openRow(row: AssignmentRow): void { + const s = new UserRoleSubject(); + s.roleType = this.listRoleType; + if (this.listRoleType == EnumRoleType.Self_Service && row.employeeID) { + s.employeeID = row.employeeID; + } else { + s.userID = row.userID; + } + this.openFor = s; + this.openDialog(); + } + + /** Review one person's pending change in the dialog. */ + openPending(g: PendingGroup): void { + this.openFor = this.toSubject(g); + this.openDialog(); + } + + private openDialog(): void { this.initializeEntryFrom = true; this.showModal = true; } - public editHandler({ dataItem }) { - } - - onPopUpClose() { + onPopUpClose(): void { this.initializeEntryFrom = false; this.showModal = false; - } - statusString(roleStatus: number): string { - var str = ""; - var status: EnumAuthStatus = roleStatus; - switch (status) { - case EnumAuthStatus.Active: { str = "Active"; break }; - default: str = "In-Active" + saveCompleted(changed: boolean): void { + this.onPopUpClose(); + if (changed === true) { + this.loadPending(); + this.RefreshControl(); } - return str; - } - saveCompleted(faction: any) { - if (faction !== undefined) { - if (faction === true) { - this.RefreshControl(); - } - } - this.showModal = false; - this.initializeEntryFrom = false; - } - - cancelHandler() { - } - - saveHandler(userRole: any) { - } - - removeHandler({ dataItem }) { } } diff --git a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role.component.html b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role.component.html index 3c3e42c..4310223 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role.component.html +++ b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role.component.html @@ -1,4 +1 @@ - -
- -
+ \ No newline at end of file diff --git a/HRM.UI/Controllers/Auth/AuthController.cs b/HRM.UI/Controllers/Auth/AuthController.cs index 7aec0e7..c584379 100644 --- a/HRM.UI/Controllers/Auth/AuthController.cs +++ b/HRM.UI/Controllers/Auth/AuthController.cs @@ -1536,6 +1536,270 @@ namespace HRM.UI.Controllers return Ok(); } + #region User Role Permission maker-checker + + // Only super users manage role assignments (the page is in WebMenu.AdminMenus only), the same + // rule as User Access Type. + private bool CanManageUserRole(CurrentUser currentUser) + { + return CanManageUserAccessType(currentUser); + } + + // Admin requests are about a User-type login; Self Service requests about an employee + payroll type. + private static string CheckUserRoleSubject(UserRoleSubject subject) + { + if (subject == null) + return "Select a user or an employee."; + if (subject.RoleType == EnumRoleType.Admin) + return (subject.UserID ?? 0) > 0 ? null : "Select a user."; + if (subject.RoleType == EnumRoleType.Self_Service) + return (subject.EmployeeID ?? 0) > 0 || (subject.UserID ?? 0) > 0 ? null : "Select an employee."; + return "Select Admin or Self Service."; + } + + // Who made the pending change (the same maker for every request of one change). + private static bool IsUserRoleMaker(UserRoleState state, int userID) + { + return state.Pending.Any(p => p.CreatedBy == userID); + } + + // The person's live roles of one role type, and any change waiting for approval. + [HttpGet("GetUserRoleState/{roleType}/{userID}/{employeeID}")] + public ActionResult GetUserRoleState(EnumRoleType roleType, int userID, int employeeID) + { + try + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (!CanManageUserRole(currentUser)) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to manage user roles."); + } + UserRoleSubject subject = new UserRoleSubject + { + RoleType = roleType, + UserID = userID > 0 ? userID : (int?)null, + EmployeeID = employeeID > 0 ? employeeID : (int?)null, + }; + string problem = CheckUserRoleSubject(subject); + if (problem != null) + { + return BadRequest(problem); + } + return Ok(this._userRoleService.GetRoleState(subject)); + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + } + + // Maker: the ticked roles become pending requests; nothing is live until approved. + [HttpPost("SaveUserRoleRequest")] + public ActionResult SaveUserRoleRequest(UserRoleChangeRequest request) + { + try + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (!CanManageUserRole(currentUser)) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to change user roles."); + } + string problem = CheckUserRoleSubject(request); + if (problem != null) + { + return BadRequest(problem); + } + if (request.RoleType == EnumRoleType.Admin) + { + User target = this._userService.Get(request.UserID.Value); + if (target == null || target.UserType != EnumUserType.User) + { + return BadRequest("Select a valid admin user."); + } + } + + UserRoleState state = this._userRoleService.GetRoleState(request); + if (state.Pending.Count > 0) + { + return BadRequest("This person already has a role change waiting for approval. Approve or reject it first."); + } + // A Self Service employee with no login gets one with this change: it needs the payroll type. + if (request.RoleType == EnumRoleType.Self_Service && !state.HasLogin && (request.PayrollTypeID ?? 0) <= 0) + { + return BadRequest("Select a payroll type."); + } + + // Every wanted role must be of this role type; a role the person does not have yet must + // also be approved (a role still waiting for its own approval cannot be given). + List wanted = (request.RoleIDs ?? new List()).Distinct().ToList(); + List allRoles = this._roleService.GetAllRole(); + foreach (int roleID in wanted) + { + Role role = allRoles.FirstOrDefault(r => r.ID == roleID); + if (role == null || role.RoleType != request.RoleType) + { + return BadRequest("Invalid role for this role type."); + } + bool live = state.LiveRoleIDs.Contains(roleID); + bool approved = role.RoleStatus == EnumAuthStatus.Approved || role.RoleStatus == EnumAuthStatus.Active; + if (!live && !approved) + { + return BadRequest("Role '" + role.Name + "' is not approved yet, so it cannot be given."); + } + } + + request.RoleIDs = wanted; + int changed = this._userRoleService.RequestChange(request, currentUser.UserID); + if (changed == 0) + { + return BadRequest("Nothing changed."); + } + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + return Ok(true); + } + + // Checker: makes the person's pending role change live. The maker cannot approve. + [HttpPost("ApproveUserRole")] + public ActionResult ApproveUserRole(UserRoleSubject subject) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + string problem; + try + { + if (!CanManageUserRole(currentUser)) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to approve user roles."); + } + problem = DecideUserRole(subject, true, currentUser); + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + return problem == null ? Ok(true) : BadRequest(problem); + } + + // Checker: drops the person's pending role change; live roles stay as they were. The maker cannot reject. + [HttpPost("RejectUserRole")] + public ActionResult RejectUserRole(UserRoleSubject subject) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + string problem; + try + { + if (!CanManageUserRole(currentUser)) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to reject user roles."); + } + problem = DecideUserRole(subject, false, currentUser); + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + return problem == null ? Ok(true) : BadRequest(problem); + } + + // Checker, many people at once: each one is decided on its own, with the same checks, so one + // that cannot be decided does not stop the rest. Returns { done, failed: [{ index, message }] }. + [HttpPost("ApproveUserRoles")] + public ActionResult ApproveUserRoles(List subjects) + { + return DecideUserRoles(subjects, true); + } + + [HttpPost("RejectUserRoles")] + public ActionResult RejectUserRoles(List subjects) + { + return DecideUserRoles(subjects, false); + } + + // Every role change waiting for approval, of everyone (Pending approvals list). + [HttpGet("GetPendingUserRoles")] + public ActionResult GetPendingUserRoles() + { + try + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (!CanManageUserRole(currentUser)) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see user role approvals."); + } + return Ok(this._userRoleService.GetPending()); + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + } + + private ActionResult DecideUserRoles(List subjects, bool approve) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + try + { + if (!CanManageUserRole(currentUser)) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to approve or reject user roles."); + } + if (subjects == null || subjects.Count == 0) + { + return BadRequest("Select at least one person."); + } + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + + int done = 0; + var failed = new List(); + for (int i = 0; i < subjects.Count; i++) + { + try + { + string problem = DecideUserRole(subjects[i], approve, currentUser); + if (problem == null) + done++; + else + failed.Add(new { index = i, message = problem }); + } + catch (Exception e) + { + failed.Add(new { index = i, message = e.Message }); + } + } + return Ok(new { done, failed }); + } + + // Returns null when decided, or why it could not be. + private string DecideUserRole(UserRoleSubject subject, bool approve, CurrentUser currentUser) + { + string problem = CheckUserRoleSubject(subject); + if (problem != null) + return problem; + + UserRoleState state = this._userRoleService.GetRoleState(subject); + if (state.Pending.Count == 0) + return "No role change is waiting for approval."; + if (IsUserRoleMaker(state, currentUser.UserID)) + return approve + ? "You cannot approve a change you made yourself. Another user must approve it." + : "You cannot reject a change you made yourself. Another user must reject it."; + + if (approve) + this._userRoleService.Approve(subject, currentUser.UserID); + else + this._userRoleService.Reject(subject, currentUser.UserID); + return null; + } + + #endregion + [HttpGet("GetUserAccessType/{userid}")] public ActionResult GetUserAccessType(int userid) {