From 7ef18abce56114edc1ee5141a7512ee919fd2b44 Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Tue, 17 Nov 2026 16:18:50 +0600 Subject: [PATCH] System Audit Log --- HRM.BO/User/SystemAuditHistory.cs | 67 +++ HRM.BO/User/UserAccessType.cs | 2 +- HRM.DA/DA/Users/SystemAuditHistoryDA.cs | 121 ++++++ HRM.DA/DA/Users/UserAccessTypeDA.cs.cs | 10 + .../Users/SystemAuditHistoryService.cs | 147 +++++++ HRM.DA/Service/Users/UserAccessTypeService.cs | 5 +- .../app/_models/Authentication/auditTrail.ts | 28 ++ .../src/app/_services/auth/auth.service.ts | 6 +- .../system.audittrail.component.html | 382 +++++++++++------- .../system.audittrail.component.scss | 252 +++++++++++- .../system.audittrail.component.ts | 138 ++++++- .../DI/ServiceCollectionExtensions.cs | 1 + HRM.UI/Controllers/Auth/AuthController.cs | 41 +- SystemAuditHistory_DB_Changes.sql | 172 ++++++++ 14 files changed, 1205 insertions(+), 167 deletions(-) create mode 100644 HRM.BO/User/SystemAuditHistory.cs create mode 100644 HRM.DA/DA/Users/SystemAuditHistoryDA.cs create mode 100644 HRM.DA/Service/Users/SystemAuditHistoryService.cs create mode 100644 SystemAuditHistory_DB_Changes.sql diff --git a/HRM.BO/User/SystemAuditHistory.cs b/HRM.BO/User/SystemAuditHistory.cs new file mode 100644 index 0000000..fc92f47 --- /dev/null +++ b/HRM.BO/User/SystemAuditHistory.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using Ease.Core.Model; + +namespace HRM.BO +{ + #region SystemAuditHistory + + /// Which change history the System Audit Log page asks for (one tab each). + public enum EnumSystemAuditHistory + { + Role = 1, + RolePermission = 2, + User = 3, + UserRole = 4, + UserAccessType = 5 + } + + /// + /// One row of a change history, read from the Z_ table of that page + /// (Z_ROLE, Z_ROLEPERMISSION, Z_USERS, Z_USERROLE, Z_USERACCESSTYPE - see + /// SystemAuditHistory_DB_Changes.sql). Fields a history does not have stay null. + /// + public class SystemAuditHistory : ObjectTemplate + { + #region Constructor + + public SystemAuditHistory() + { + } + + #endregion + + #region Properties + + /// What happened, e.g. "User created", "Role modified", "Access type removed". + public string AuditType { get; set; } + public DateTime? AuditDate { get; set; } + public string LoginID { get; set; } + public string Name { get; set; } + public string Code { get; set; } + public string UserType { get; set; } + public string RoleName { get; set; } + public string RoleType { get; set; } + public string MenuKey { get; set; } + public string MenuName { get; set; } + public string AccessType { get; set; } + public string Activities { get; set; } + public int? ActionBy { get; set; } + public string ActionByLoginID { get; set; } + public string ActionByName { get; set; } + + #endregion + } + + #endregion + + #region ISystemAuditHistory Service + + public interface ISystemAuditHistoryService + { + /// The change history of one page in a date range (both days inclusive), newest first. + List Get(EnumSystemAuditHistory type, DateTime dtFrom, DateTime dtTo); + } + + #endregion +} diff --git a/HRM.BO/User/UserAccessType.cs b/HRM.BO/User/UserAccessType.cs index 84605c7..b73cb3a 100644 --- a/HRM.BO/User/UserAccessType.cs +++ b/HRM.BO/User/UserAccessType.cs @@ -63,7 +63,7 @@ namespace HRM.BO /// Checker: makes every pending change of the user live. void Approve(int userID, int approverID); /// Checker: drops every pending change of the user; access stays as it was. - void Reject(int userID); + void Reject(int userID, int rejecterID); /// Every row waiting for approval, of every user, with user, payroll type and maker for display. List GetPending(); } diff --git a/HRM.DA/DA/Users/SystemAuditHistoryDA.cs b/HRM.DA/DA/Users/SystemAuditHistoryDA.cs new file mode 100644 index 0000000..7a83150 --- /dev/null +++ b/HRM.DA/DA/Users/SystemAuditHistoryDA.cs @@ -0,0 +1,121 @@ +using System; +using System.Data; +using Ease.Core.DataAccess; +using HRM.BO; + +namespace HRM.DA +{ + // Change history of the Authentication pages, read from their Z_ tables + // (SystemAuditHistory_DB_Changes.sql). Every query returns the same columns, so one + // MapObject reads them all: AuditType, AuditDate, LoginID, Name, Code, UserType, RoleName, + // RoleType, MenuKey, MenuName, AccessType, Status, Activities, ActionBy, ActionByLoginID, + // ActionByName. Date range: both days inclusive, newest first. + internal class SystemAuditHistoryDA + { + #region Constructor + + private SystemAuditHistoryDA() + { + } + + #endregion + + #region Get Function + + // Z_ROLE keeps a copy of the row. "Update (before)" rows are left out (the "after" row + // shows the change). Who did it: the approver on an approval, else the editor, else the creator. + internal static IDataReader GetRole(TransactionContext tc, DateTime dtFrom, DateTime dtTo) + { + string sql = SQLParser.MakeSQL( + @"SELECT CASE z.AUDITTYPE WHEN 'Inserted' THEN 'Role created' + WHEN 'Deleted' THEN 'Role deleted' + ELSE 'Role modified' END AuditType, + z.AUDITDATE AuditDate, NULL LoginID, z.NAME Name, z.CODE Code, NULL UserType, + NULL RoleName, z.ROLETYPE RoleType, NULL MenuKey, NULL MenuName, NULL AccessType, + z.STATUS Status, NULL Activities, a.ActionBy, u.LoginID ActionByLoginID, u.UserName ActionByName + FROM Z_ROLE z + CROSS APPLY (SELECT CASE WHEN z.AUDITTYPE = 'Deleted' THEN NULL + WHEN z.AUDITTYPE = 'Inserted' THEN z.CREATEDBY + WHEN z.STATUS = %n AND z.APPROVEBY IS NOT NULL THEN z.APPROVEBY + ELSE COALESCE(z.AUTHORIZEDBY, z.CREATEDBY) END ActionBy) a + LEFT JOIN Users u ON u.UserID = a.ActionBy + WHERE z.AUDITTYPE <> 'Update (before)' + AND z.AUDITDATE >= %d AND z.AUDITDATE < %d + ORDER BY z.AUDITDATE DESC", + (int)EnumAuthStatus.Approved, dtFrom.Date, dtTo.Date.AddDays(1)); + return tc.ExecuteReader(sql); + } + + // Z_ROLEPERMISSION (trigger trRolePermission). Menu name from the uploaded menu + // (ConfigurationAttribute), the same lookup RolePermissionDA.GetRolePerAudit uses. + internal static IDataReader GetRolePermission(TransactionContext tc, DateTime dtFrom, DateTime dtTo) + { + string sql = SQLParser.MakeSQL( + @"SELECT z.audittype AuditType, z.auditdate AuditDate, NULL LoginID, NULL Name, r.Code Code, NULL UserType, + r.Name RoleName, r.RoleType RoleType, z.menukey MenuKey, + (SELECT TOP 1 ca.Value FROM ConfigurationAttribute ca + WHERE ca.AttributeName = 'name' + AND ca.ParentID = (SELECT MAX(ck.ParentID) FROM ConfigurationAttribute ck + WHERE ck.Value = z.menukey AND ck.AttributeName = 'key')) MenuName, + NULL AccessType, z.status Status, z.activities Activities, + z.actionby ActionBy, u.LoginID ActionByLoginID, u.UserName ActionByName + FROM Z_ROLEPERMISSION z + LEFT JOIN Role r ON r.RoleID = z.roleid + LEFT JOIN Users u ON u.UserID = z.actionby + WHERE z.auditdate >= %d AND z.auditdate < %d + ORDER BY z.auditdate DESC", + dtFrom.Date, dtTo.Date.AddDays(1)); + return tc.ExecuteReader(sql); + } + + // Z_USERS (trigger trUsers). + internal static IDataReader GetUser(TransactionContext tc, DateTime dtFrom, DateTime dtTo) + { + string sql = SQLParser.MakeSQL( + @"SELECT z.audittype AuditType, z.auditdate AuditDate, z.loginid LoginID, z.name Name, NULL Code, + z.usertype UserType, NULL RoleName, NULL RoleType, NULL MenuKey, NULL MenuName, NULL AccessType, + NULL Status, z.activities Activities, + z.actionby ActionBy, u.LoginID ActionByLoginID, u.UserName ActionByName + FROM Z_USERS z + LEFT JOIN Users u ON u.UserID = z.actionby + WHERE z.auditdate >= %d AND z.auditdate < %d + ORDER BY z.auditdate DESC", + dtFrom.Date, dtTo.Date.AddDays(1)); + return tc.ExecuteReader(sql); + } + + // Z_USERROLE (trigger truserrole): Code / name are the role's. + internal static IDataReader GetUserRole(TransactionContext tc, DateTime dtFrom, DateTime dtTo) + { + string sql = SQLParser.MakeSQL( + @"SELECT z.audittype AuditType, z.auditdate AuditDate, NULL LoginID, NULL Name, z.Code Code, NULL UserType, + z.name RoleName, NULL RoleType, NULL MenuKey, NULL MenuName, NULL AccessType, + NULL Status, z.activities Activities, + z.actionby ActionBy, u.LoginID ActionByLoginID, u.UserName ActionByName + FROM Z_USERROLE z + LEFT JOIN Users u ON u.UserID = z.actionby + WHERE z.auditdate >= %d AND z.auditdate < %d + ORDER BY z.auditdate DESC", + dtFrom.Date, dtTo.Date.AddDays(1)); + return tc.ExecuteReader(sql); + } + + // Z_USERACCESSTYPE (trigger trUserAccessType). + internal static IDataReader GetUserAccessType(TransactionContext tc, DateTime dtFrom, DateTime dtTo) + { + string sql = SQLParser.MakeSQL( + @"SELECT z.audittype AuditType, z.auditdate AuditDate, z.loginid LoginID, z.name Name, NULL Code, + NULL UserType, NULL RoleName, NULL RoleType, NULL MenuKey, NULL MenuName, z.payrolltype AccessType, + NULL Status, z.activities Activities, + z.actionby ActionBy, u.LoginID ActionByLoginID, u.UserName ActionByName + FROM Z_USERACCESSTYPE z + LEFT JOIN Users u ON u.UserID = z.actionby + WHERE z.auditdate >= %d AND z.auditdate < %d + ORDER BY z.auditdate DESC", + dtFrom.Date, dtTo.Date.AddDays(1)); + return tc.ExecuteReader(sql); + } + + #endregion + } +} diff --git a/HRM.DA/DA/Users/UserAccessTypeDA.cs.cs b/HRM.DA/DA/Users/UserAccessTypeDA.cs.cs index 62e2b65..da6ebce 100644 --- a/HRM.DA/DA/Users/UserAccessTypeDA.cs.cs +++ b/HRM.DA/DA/Users/UserAccessTypeDA.cs.cs @@ -56,6 +56,16 @@ namespace HRM.DA (int)EnumAuthStatus.Approved, approverID, approveDate, userID, (int)EnumAuthStatus.NewNotYetApprove); } + // Tells trigger trUserAccessType who is making the change (SystemAuditHistory_DB_Changes.sql), + // for the rows it cannot tell from the row itself (a reject, a deleted row). Lasts for this + // connection only; a pooled connection is reset before it is used again. Skipped on a + // SQL Server older than 2016, which has no session context. + internal static void SetAuditUser(TransactionContext tc, int userID) + { + tc.ExecuteNonQuery("IF OBJECT_ID('sys.sp_set_session_context') IS NOT NULL" + + " EXEC sp_set_session_context @key = N'AuditUserID', @value = %n", userID); + } + // Checker rejects: requested accesses go, requested removals stay live as before. internal static void Reject(TransactionContext tc, int userID) { diff --git a/HRM.DA/Service/Users/SystemAuditHistoryService.cs b/HRM.DA/Service/Users/SystemAuditHistoryService.cs new file mode 100644 index 0000000..986f242 --- /dev/null +++ b/HRM.DA/Service/Users/SystemAuditHistoryService.cs @@ -0,0 +1,147 @@ +using Ease.Core.DataAccess; +using Ease.Core.Model; +using Ease.Core.Utility; +using System; +using System.Collections.Generic; +using System.Data; +using HRM.BO; + +namespace HRM.DA +{ + public class SystemAuditHistoryService : ServiceTemplate, ISystemAuditHistoryService + { + public SystemAuditHistoryService() + { + } + + private void MapObject(SystemAuditHistory oItem, DataReader oReader) + { + oItem.AuditType = oReader.GetString("AuditType"); + oItem.AuditDate = oReader.GetDateTime("AuditDate"); + oItem.LoginID = oReader.GetString("LoginID"); + oItem.Name = oReader.GetString("Name"); + oItem.Code = oReader.GetString("Code"); + oItem.UserType = UserTypeText(oReader.GetString("UserType")); + oItem.RoleName = oReader.GetString("RoleName"); + oItem.RoleType = RoleTypeText(oReader.GetInt32("RoleType")); + oItem.MenuKey = oReader.GetString("MenuKey"); + oItem.MenuName = oReader.GetString("MenuName"); + oItem.AccessType = oReader.GetString("AccessType"); + oItem.Activities = oReader.GetString("Activities"); + oItem.ActionBy = oReader.GetInt32("ActionBy"); + oItem.ActionByLoginID = oReader.GetString("ActionByLoginID"); + oItem.ActionByName = oReader.GetString("ActionByName"); + + // Z_ROLE has no activities column: show the role's status, as the other triggers write it. + int? status = oReader.GetInt32("Status"); + if (string.IsNullOrWhiteSpace(oItem.Activities) && status.HasValue) + oItem.Activities = StatusText(status.Value); + } + + protected override T CreateObject(DataReader oReader) + { + SystemAuditHistory oItem = new SystemAuditHistory(); + MapObject(oItem, oReader); + return oItem as T; + } + + // Same words the Z_ triggers write into "activities". + private static string StatusText(int status) + { + switch (status) + { + case 1: return "Active"; + case 2: return "New Not Yet Approve"; + case 3: return "Deleted Not Yet Approve"; + case 4: return "Edited Not Yet Approve"; + case 5: return "Approved"; + case 6: return "Locked"; + case 7: return "Archived"; + case 8: return "Inactive"; + case 9: return "Inactive Not Yet Approve"; + case 10: return "Rejected"; + default: return "None"; + } + } + + private static string RoleTypeText(int? roleType) + { + if (!roleType.HasValue) + return null; + switch ((EnumRoleType)roleType.Value) + { + case EnumRoleType.Admin: return "Admin"; + case EnumRoleType.Self_Service: return "Self Service"; + case EnumRoleType.Mobile: return "Mobile"; + default: return roleType.Value.ToString(); + } + } + + // Z_USERS.usertype is the Users.UserType number as text. + private static string UserTypeText(string userType) + { + int value; + if (string.IsNullOrWhiteSpace(userType) || !int.TryParse(userType.Trim(), out value)) + return userType; + switch ((EnumUserType)value) + { + case EnumUserType.SuperUser: return "Super User"; + case EnumUserType.User: return "User"; + case EnumUserType.Employee: return "Employee"; + default: return userType; + } + } + + #region Service implementation + + public List Get(EnumSystemAuditHistory type, DateTime dtFrom, DateTime dtTo) + { + List items = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + IDataReader reader; + switch (type) + { + case EnumSystemAuditHistory.Role: + reader = SystemAuditHistoryDA.GetRole(tc, dtFrom, dtTo); + break; + case EnumSystemAuditHistory.RolePermission: + reader = SystemAuditHistoryDA.GetRolePermission(tc, dtFrom, dtTo); + break; + case EnumSystemAuditHistory.User: + reader = SystemAuditHistoryDA.GetUser(tc, dtFrom, dtTo); + break; + case EnumSystemAuditHistory.UserRole: + reader = SystemAuditHistoryDA.GetUserRole(tc, dtFrom, dtTo); + break; + case EnumSystemAuditHistory.UserAccessType: + reader = SystemAuditHistoryDA.GetUserAccessType(tc, dtFrom, dtTo); + break; + default: + throw new ArgumentException("Unknown audit history."); + } + DataReader dr = new DataReader(reader); + items = this.CreateObjects(dr); + dr.Close(); + 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; + } + + #endregion + } +} diff --git a/HRM.DA/Service/Users/UserAccessTypeService.cs b/HRM.DA/Service/Users/UserAccessTypeService.cs index da868c6..42af735 100644 --- a/HRM.DA/Service/Users/UserAccessTypeService.cs +++ b/HRM.DA/Service/Users/UserAccessTypeService.cs @@ -240,6 +240,7 @@ namespace HRM.DA DateTime now = DateTime.Now; List wanted = (payrollTypeIDs ?? new List()).Distinct().ToList(); + UserAccessTypeDA.SetAuditUser(tc, makerID); // Newly ticked payroll type: requested, not live until approved. foreach (int payrollTypeID in wanted.Where(p => !current.Any(c => c.PayrollTypeID == p))) @@ -296,6 +297,7 @@ namespace HRM.DA } dr.Close(); + UserAccessTypeDA.SetAuditUser(tc, approverID); UserAccessTypeDA.Approve(tc, userID, approverID, DateTime.Now); // The "access granted" notification now goes out when the access is really live. @@ -366,12 +368,13 @@ namespace HRM.DA return items; } - public void Reject(int userID) + public void Reject(int userID, int rejecterID) { TransactionContext tc = null; try { tc = TransactionContext.Begin(true); + UserAccessTypeDA.SetAuditUser(tc, rejecterID); UserAccessTypeDA.Reject(tc, userID); tc.End(); } diff --git a/HRM.UI/ClientApp/src/app/_models/Authentication/auditTrail.ts b/HRM.UI/ClientApp/src/app/_models/Authentication/auditTrail.ts index d2ec992..4284daa 100644 --- a/HRM.UI/ClientApp/src/app/_models/Authentication/auditTrail.ts +++ b/HRM.UI/ClientApp/src/app/_models/Authentication/auditTrail.ts @@ -47,3 +47,31 @@ export class BadLoginAttemptInfo extends BaseObject { this.userName = ''; } } + +/** Which change history the System Audit Log page asks for (HRM.BO EnumSystemAuditHistory). */ +export enum EnumSystemAuditHistory { + Role = 1, + RolePermission = 2, + User = 3, + UserRole = 4, + UserAccessType = 5 +} + +/** One row of a page's change history (Z_ table), as returned by api/Authentication/getSystemAuditHistory. */ +export interface SystemAuditHistory { + auditType: string; + auditDate: Date; + loginID: string; + name: string; + code: string; + userType: string; + roleName: string; + roleType: string; + menuKey: string; + menuName: string; + accessType: string; + activities: string; + actionBy: number; + actionByLoginID: string; + actionByName: string; +} 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 2b79fc3..f2f7504 100644 --- a/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts @@ -12,7 +12,7 @@ import { PayrollType } from '../../_models/Authentication/payrollType'; 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'; +import { UserLogInInfo, BadLoginAttemptInfo, EnumSystemAuditHistory, SystemAuditHistory } from '../../_models/Authentication/auditTrail'; import { Router } from '@angular/router'; import { Bookmark } from '../../_models/Basic/bookmark'; import { Subject } from 'rxjs'; @@ -146,6 +146,10 @@ export class AuthService { return this.apiService.httpGet('/Authentication/getBadLoginAuditTrail/' + this.apiService.getApiDateString(fromDate) + '/' + this.apiService.getApiDateString(toDate)); } + getSystemAuditHistory(type: EnumSystemAuditHistory, fromDate: Date, toDate: Date) { + return this.apiService.httpGet('/Authentication/getSystemAuditHistory/' + type + '/' + + this.apiService.getApiDateString(fromDate) + '/' + this.apiService.getApiDateString(toDate)); + } getBookmarks() { return this.apiService.httpGet('/Authentication/getBookmarks'); } diff --git a/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.html b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.html index a0c3b56..b3ea3fc 100644 --- a/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.html +++ b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.html @@ -1,169 +1,269 @@ - +
+ -
- + +
+ +
+

System Audit Log

+

Who signed in, failed logins, and every change made on the Role, Role Permission, User, User Role and User Access Type pages.

+
+
+ + - + + User Audit Trail -
-
- +
+
+
+ + +
+
+ + +
+
-
- -
-
- -
-
- -
-
- -
-
- + - - - - {{ userGrid.filteredCount | number }} of {{ userGrid.rows.length | number }} records - - - - - + + + + + + + {{ userGrid.filteredCount | number }} of {{ userGrid.rows.length | number }} records + + + + + - - - - - - + + + + + + - - {{ userGrid.loaded ? 'No login found for this date range.' : 'Select a date range and press Load.' }} - + +
+ + {{ userGrid.loaded ? 'No login found for this date range.' : 'Select a date range and press Load.' }} +
+
- - - - - - - - + + + + + + + + - - - -
+ + + +
+ - + + Bad Login Attempt -
-
- +
+
+
+ + +
+
+ + +
+
-
- -
-
- -
-
- -
-
- -
-
- + - - - - {{ badGrid.filteredCount | number }} of {{ badGrid.rows.length | number }} records - - - - - + + + + + + + {{ badGrid.filteredCount | number }} of {{ badGrid.rows.length | number }} records + + + + + - - - - - + + + + + - - {{ badGrid.loaded ? 'No bad login attempt found for this date range.' : 'Select a date range and press Load.' }} - + +
+ + {{ badGrid.loaded ? 'No bad login attempt found for this date range.' : 'Select a date range and press Load.' }} +
+
- - - - - - - + + + + + + + - - - -
+ + + +
+ + + @for (tab of historyTabs; track tab.type) { + + {{ tab.title }} + +
+
+
+ + +
+
+ + +
+ +
+ + + + + + + + + + {{ tab.grid.filteredCount | number }} of {{ tab.grid.rows.length | number }} records + + + + + + + @for (col of tab.allColumns; track col.field) { + @if (col.isDate) { + + } @else { + + } + } + + +
+ + {{ tab.grid.loaded ? 'No change found for this date range.' : 'Select a date range and press Load.' }} +
+
+ + + @for (col of tab.allColumns; track col.field) { + @if (col.isDate) { + + } @else { + + } + } + + + + + +
+
+
+
+ } +
diff --git a/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.scss b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.scss index 16ce36b..246bf3d 100644 --- a/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.scss +++ b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.scss @@ -1,18 +1,252 @@ -.audit-trail-filter { - margin: 0.5rem 0 0.75rem; +@use '../../../styles/abstracts/tokens' as *; + +// Tab colours: the same boxed tabs as Employee Bulk Upload (employee-bulk-upload.component.scss). +$sal-tab-text: #2C4A6B; +$sal-tab-bg: #F4F8FC; +$sal-tab-hover: #D8E4F0; +$sal-tab-border: #C9D8E8; +$sal-tab-active-border: #9DB4CC; + +:host { + @include empcard-host-vars; +} + +.sal-page { + position: relative; + display: flex; + flex-direction: column; + gap: 10px; + + // The loading panel is not a card: keep it out of the flex gap (its overlay is absolute). + > app-loading-panel { + display: contents; + } +} + +/* ── card shell ─────────────────────────────────────────────────── */ +.sal-card { + background: var(--brand-card-bg); + border: 1px solid var(--brand-card-border); + border-radius: 20px; + box-shadow: var(--brand-card-shadow); + padding: 18px 20px; + position: relative; +} + +/* ── page header ────────────────────────────────────────────────── */ +.sal-header { + display: flex; align-items: center; + gap: 14px; } -.audit-trail-label { - margin: auto; +.sal-header-ico { + flex: 0 0 auto; + width: 44px; + height: 44px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + background: $sal-tab-hover; + color: $sal-tab-text; + + i { + font-size: 1.35rem; + } } -.audit-trail-search { +.sal-header-text { + min-width: 0; + + h2 { + margin: 0; + font-size: 1.2rem; + font-weight: 700; + color: var(--brand-text); + } + + p { + margin: 2px 0 0; + font-size: 0.85rem; + color: var(--brand-text-sub); + } +} + +/* ── tabs ───────────────────────────────────────────────────────── */ +/* + * Each tab a bordered box, the open one white with a blue top edge. The tab items are rendered + * by kendo-tabstrip, hence ::ng-deep. + */ +:host ::ng-deep kendo-tabstrip.sal-tabs { + border: 0; + background: transparent; + + > .k-tabstrip-items-wrapper { + border-bottom: 1px solid #E2E8F0; + background: transparent; + } + + > .k-tabstrip-items-wrapper .k-tabstrip-item { + display: inline-flex; + align-items: center; + margin: 0 6px -1px 0; + padding: 10px 16px; + border: 1px solid $sal-tab-border; + border-radius: 10px 10px 0 0; + background: $sal-tab-bg; + color: $sal-tab-text; + font-weight: 700; + white-space: nowrap; + transition: background .15s ease, border-color .15s ease; + + &:hover { + background: $sal-tab-hover; + } + + &.k-active { + background: #FFFFFF; + border-color: $sal-tab-active-border; + border-bottom-color: #FFFFFF; + box-shadow: inset 0 3px 0 $sal-tab-text; + } + + .k-link { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 0; + color: inherit; + } + } + + // Scroll arrows when the tabs do not fit. + > .k-tabstrip-items-wrapper .k-tabstrip-prev, + > .k-tabstrip-items-wrapper .k-tabstrip-next { + color: $sal-tab-text; + } + + > .k-tabstrip-content { + padding: 10px 0 0; + border: 0; + background: transparent; + + &:focus, + &.k-focus { + outline: none; + box-shadow: none; + } + } +} + +/* ── tab body: filter bar + grid ────────────────────────────────── */ +.sal-body { + display: flex; + flex-direction: column; + gap: 14px; +} + +.sal-filter { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 12px 16px; + padding: 12px 14px; + border: 1px solid var(--brand-card-border); + border-radius: 14px; + background: $sal-tab-bg; +} + +.sal-field { + display: flex; + flex-direction: column; + gap: 4px; + width: 220px; + + label { + font-size: 0.78rem; + font-weight: 600; + letter-spacing: .02em; + text-transform: uppercase; + color: var(--brand-text-sub); + } + + kendo-datepicker { + width: 100%; + } + + @media (max-width: 576px) { + width: 100%; + } +} + +.sal-load { + min-width: 120px; + + @media (max-width: 576px) { + width: 100%; + } +} + +:host ::ng-deep kendo-grid.sal-grid { + border-radius: 12px; + overflow: hidden; + + .k-grid-toolbar { + gap: 10px; + padding: 10px 12px; + } + + .k-grid-header .k-header { + font-weight: 700; + } +} + +.sal-search { + position: relative; + display: inline-flex; + align-items: center; width: 280px; + max-width: 100%; + + i { + position: absolute; + left: 10px; + z-index: 1; + font-size: 0.85rem; + color: var(--brand-text-muted); + pointer-events: none; + } + + input { + width: 100%; + padding-left: 30px; + } } -.audit-trail-count { - margin-left: 0.5rem; - font-size: 0.875rem; - opacity: 0.75; +.sal-count { + padding: 3px 10px; + border-radius: 999px; + background: $sal-tab-bg; + border: 1px solid $sal-tab-border; + font-size: 0.8rem; + color: $sal-tab-text; + white-space: nowrap; + + strong { + font-weight: 700; + } +} + +.sal-empty { + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + padding: 28px 0; + color: var(--brand-text-muted); + + i { + font-size: 1.6rem; + } } diff --git a/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.ts b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.ts index 88a2187..73f8b63 100644 --- a/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.ts +++ b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.ts @@ -6,7 +6,7 @@ import { ApiService } from '../../app.api.service'; import { AuthService } from '../../_services/auth/auth.service'; import { HRMNotificationService } from '../../app.notification.service'; import { loadingPanelService } from '../../hrm-loding panel/loding.panel.service'; -import { UserLogInInfo, BadLoginAttemptInfo } from '../../_models/Authentication/auditTrail'; +import { UserLogInInfo, BadLoginAttemptInfo, EnumSystemAuditHistory, SystemAuditHistory } from '../../_models/Authentication/auditTrail'; /** Rows per virtual "page" - enough to fill the grid viewport a few times over. */ const PAGE_SIZE = 60; @@ -24,22 +24,48 @@ export interface AuditTrailRow { deviceId: string; } +/** One row of a change-history grid (Z_ tables), the same shape for every history tab. */ +export interface AuditHistoryRow { + auditDate: Date; + auditType: string; + loginID: string; + name: string; + code: string; + userType: string; + roleName: string; + roleType: string; + menu: string; + accessType: string; + activities: string; + actionBy: string; +} + +/** A column of a change-history tab. */ +export interface AuditHistoryColumn { + field: keyof AuditHistoryRow; + title: string; + width: number; + isDate?: boolean; +} + /** * State of one audit-trail grid: all loaded rows, the toolbar search, and the * grid's sort / filter / virtual-scroll state. Everything is done client side over * the rows of the selected date range. */ -export class AuditTrailGrid { - rows: AuditTrailRow[] = []; - private searched: AuditTrailRow[] = []; +export class AuditTrailGrid { + rows: T[] = []; + private searched: T[] = []; searchText = ''; loaded = false; - state: State = { skip: 0, take: PAGE_SIZE, sort: [{ field: 'punchTime', dir: 'desc' }], filter: { logic: 'and', filters: [] } }; + state: State; view: GridDataResult = { data: [], total: 0 }; - constructor(private searchFields: (keyof AuditTrailRow)[]) { } + constructor(private searchFields: (keyof T)[], sortField: string = 'punchTime') { + this.state = { skip: 0, take: PAGE_SIZE, sort: [{ field: sortField, dir: 'desc' }], filter: { logic: 'and', filters: [] } }; + } - setRows(rows: AuditTrailRow[]): void { + setRows(rows: T[]): void { this.rows = rows; this.loaded = true; this.state = { ...this.state, skip: 0 }; @@ -80,8 +106,8 @@ export class AuditTrailGrid { this.view = process(this.searched, this.state); } - private static searchValue(row: AuditTrailRow, field: keyof AuditTrailRow): string { - const value = row[field]; + private static searchValue(row: R, field: keyof R): string { + const value: unknown = row[field]; if (value === undefined || value === null) { return ''; } @@ -101,6 +127,31 @@ export class AuditTrailGrid { } } +/** One change-history tab: which Z_ table, its own columns, date range and grid state. */ +export class AuditHistoryTab { + fromDate: Date; + toDate: Date; + readonly grid: AuditTrailGrid; + /** Every column of the tab: when, what, the page's own columns, then the details and who. */ + readonly allColumns: AuditHistoryColumn[]; + + constructor(public readonly type: EnumSystemAuditHistory, + public readonly title: string, + public readonly filePrefix: string, + columns: AuditHistoryColumn[], + /** PrimeIcons class shown in the tab title. */ + public readonly icon: string) { + this.allColumns = [ + { field: 'auditDate', title: 'Date', width: 190, isDate: true }, + { field: 'auditType', title: 'Action', width: 200 }, + ...columns, + { field: 'activities', title: 'Activities', width: 220 }, + { field: 'actionBy', title: 'Action By', width: 220 } + ]; + this.grid = new AuditTrailGrid(this.allColumns.map(c => c.field), 'auditDate'); + } +} + @Component({ selector: 'app-system-audittrail', templateUrl: './system.audittrail.component.html', @@ -122,6 +173,33 @@ export class SystemAuditTrailComponent implements OnInit { badToDate: Date; badGrid = new AuditTrailGrid(['loginID', 'punchTime', 'pcNumber', 'ipAddress', 'deviceId']); + /** Change-history tabs (Z_ tables), one per Authentication page. */ + historyTabs: AuditHistoryTab[] = [ + new AuditHistoryTab(EnumSystemAuditHistory.Role, 'Role History', 'RoleHistory', [ + { field: 'code', title: 'Role Code', width: 140 }, + { field: 'name', title: 'Role Name', width: 220 }, + { field: 'roleType', title: 'Role Type', width: 130 } + ], 'pi pi-id-card'), + new AuditHistoryTab(EnumSystemAuditHistory.RolePermission, 'Role Permission History', 'RolePermissionHistory', [ + { field: 'roleName', title: 'Role', width: 200 }, + { field: 'menu', title: 'Menu', width: 260 } + ], 'pi pi-key'), + new AuditHistoryTab(EnumSystemAuditHistory.User, 'User History', 'UserHistory', [ + { field: 'loginID', title: 'Login ID', width: 150 }, + { field: 'name', title: 'Name', width: 220 }, + { field: 'userType', title: 'User Type', width: 130 } + ], 'pi pi-user'), + new AuditHistoryTab(EnumSystemAuditHistory.UserRole, 'User Role History', 'UserRoleHistory', [ + { field: 'code', title: 'Role Code', width: 140 }, + { field: 'roleName', title: 'Role Name', width: 220 } + ], 'pi pi-users'), + new AuditHistoryTab(EnumSystemAuditHistory.UserAccessType, 'User Access Type History', 'UserAccessTypeHistory', [ + { field: 'loginID', title: 'Login ID', width: 150 }, + { field: 'name', title: 'Name', width: 220 }, + { field: 'accessType', title: 'Access Type', width: 200 } + ], 'pi pi-sitemap') + ]; + constructor(public apiService: ApiService, public authService: AuthService, public notificationService: HRMNotificationService, @@ -139,6 +217,10 @@ export class SystemAuditTrailComponent implements OnInit { this.userToDate = new Date(today); this.badFromDate = new Date(weekAgo); this.badToDate = new Date(today); + this.historyTabs.forEach(tab => { + tab.fromDate = new Date(weekAgo); + tab.toDate = new Date(today); + }); this.loadingPanel.ShowLoadingPanel = false; } @@ -194,10 +276,44 @@ export class SystemAuditTrailComponent implements OnInit { }); } + // -- Change-history tabs (Z_ tables) --------------------------------------- + + loadHistory(tab: AuditHistoryTab): void { + if (!this.validDateRange(tab.fromDate, tab.toDate)) { + return; + } + this.loadingPanel.ShowLoadingPanel = true; + this.authService.getSystemAuditHistory(tab.type, tab.fromDate, tab.toDate).subscribe({ + next: (items: SystemAuditHistory[]) => { + tab.grid.setRows((items ?? []).map(x => ({ + auditDate: x.auditDate ? new Date(x.auditDate) : null, + auditType: x.auditType ?? '', + loginID: x.loginID ?? '', + name: x.name ?? '', + code: x.code ?? '', + userType: x.userType ?? '', + roleName: x.roleName ?? '', + roleType: x.roleType ?? '', + menu: x.menuName || x.menuKey || '', + accessType: x.accessType ?? '', + activities: (x.activities ?? '').trim(), + actionBy: x.actionByName + ? x.actionByName + (x.actionByLoginID ? ' (' + x.actionByLoginID + ')' : '') + : (x.actionByLoginID ?? '') + }))); + this.loadingPanel.ShowLoadingPanel = false; + }, + error: (err) => { + this.loadingPanel.ShowLoadingPanel = false; + this.notificationService.showError(err?.error ?? 'Could not load the ' + tab.title.toLowerCase() + '.'); + } + }); + } + // -- Shared ---------------------------------------------------------------- /** PDF renders every row into the page first, so refuse it for very large results. */ - exportPdf(grid: GridComponent, auditGrid: AuditTrailGrid): void { + exportPdf(grid: GridComponent, auditGrid: { filteredCount: number }): void { if (auditGrid.filteredCount === 0) { this.notificationService.showError('There is no data to export.'); return; @@ -210,7 +326,7 @@ export class SystemAuditTrailComponent implements OnInit { grid.saveAsPDF(); } - exportExcel(grid: GridComponent, auditGrid: AuditTrailGrid): void { + exportExcel(grid: GridComponent, auditGrid: { filteredCount: number }): void { if (auditGrid.filteredCount === 0) { this.notificationService.showError('There is no data to export.'); return; diff --git a/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs b/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs index 79104cb..7ca7791 100644 --- a/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs +++ b/HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs @@ -43,6 +43,7 @@ namespace HRM.UI.Configuration.DI services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/HRM.UI/Controllers/Auth/AuthController.cs b/HRM.UI/Controllers/Auth/AuthController.cs index 58e9d04..f4a7381 100644 --- a/HRM.UI/Controllers/Auth/AuthController.cs +++ b/HRM.UI/Controllers/Auth/AuthController.cs @@ -55,6 +55,7 @@ namespace HRM.UI.Controllers private readonly IMemoryCache _cache; private readonly IUserLogInInfoService _userLogInInfoService; private readonly IBadLoginAttemptInfoService _badLoginAttemptInfoService; + private readonly ISystemAuditHistoryService _systemAuditHistoryService; public AuthController(IConfiguration config, IUserService userService, @@ -73,7 +74,8 @@ namespace HRM.UI.Controllers ISmsService smsService, IMemoryCache cache, IUserLogInInfoService userLogInInfoService, - IBadLoginAttemptInfoService badLoginAttemptInfoService) + IBadLoginAttemptInfoService badLoginAttemptInfoService, + ISystemAuditHistoryService systemAuditHistoryService) { _config = config; _jwt = jwtOptions.Value; @@ -94,6 +96,7 @@ namespace HRM.UI.Controllers _cache = cache; _userLogInInfoService = userLogInInfoService; _badLoginAttemptInfoService = badLoginAttemptInfoService; + _systemAuditHistoryService = systemAuditHistoryService; } [HttpPost] @@ -1979,7 +1982,7 @@ namespace HRM.UI.Controllers return BadRequest("You cannot reject a change you made yourself. Another user must reject it."); } - this._userAccessTypeService.Reject(userID); + this._userAccessTypeService.Reject(userID, currentUser.UserID); } catch (Exception e) { @@ -2063,7 +2066,7 @@ namespace HRM.UI.Controllers if (approve) this._userAccessTypeService.Approve(userID, currentUser.UserID); else - this._userAccessTypeService.Reject(userID); + this._userAccessTypeService.Reject(userID, currentUser.UserID); done++; } catch (Exception e) @@ -2457,6 +2460,38 @@ namespace HRM.UI.Controllers return Ok(items); } + // Change history of the Role, Role Permission, User, User Role and User Access Type pages, + // read from their Z_ tables (SystemAuditHistory_DB_Changes.sql). type = EnumSystemAuditHistory. + [HttpGet] + [Route("getSystemAuditHistory/{type}/{fromDate}/{toDate}")] + public ActionResult GetSystemAuditHistory(int type, string fromDate, string toDate) + { + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to view the audit trail."); + if (!Enum.IsDefined(typeof(EnumSystemAuditHistory), type)) + return StatusCode(StatusCodes.Status400BadRequest, "Unknown audit history."); + + List items = new List(); + try + { + DateTime dFromDate = GlobalFunctions.GetApiDefaultDateData(fromDate); + DateTime dToDate = GlobalFunctions.GetApiDefaultDateData(toDate); + if (dFromDate == DateTime.MinValue || dToDate == DateTime.MinValue) + return StatusCode(StatusCodes.Status400BadRequest, "From date and To date are required."); + if (dFromDate.Date > dToDate.Date) + return StatusCode(StatusCodes.Status400BadRequest, "From date can not be after To date."); + + items = _systemAuditHistoryService.Get((EnumSystemAuditHistory)type, dFromDate, dToDate); + } + catch (Exception ex) + { + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + + return Ok(items); + } + #endregion [HttpGet] diff --git a/SystemAuditHistory_DB_Changes.sql b/SystemAuditHistory_DB_Changes.sql new file mode 100644 index 0000000..e1a0182 --- /dev/null +++ b/SystemAuditHistory_DB_Changes.sql @@ -0,0 +1,172 @@ +/* + System Audit History (Authentication > System Audit Log) + ======================================================== + + The System Audit Log page shows the change history of the Authentication pages, one tab each: + Role -> dbo.Z_ROLE (trigger trRole - NEW, below) + Role Permission -> dbo.Z_ROLEPERMISSION (trigger trRolePermission - already in the database) + User -> dbo.Z_USERS (trigger trUsers - already in the database) + User Role -> dbo.Z_USERROLE (trigger truserrole - already in the database) + User Access Type -> dbo.Z_USERACCESSTYPE (table + trigger trUserAccessType - NEW, below) + + This script: + Part 1 creates dbo.Z_UserAccessType (same shape as dbo.z_users, plus the payroll type). + Part 2 creates trigger dbo.trUserAccessType on dbo.UserAccessType (insert, update, delete). + Part 3 creates trigger dbo.trRole on dbo.Role (insert, update, delete) writing dbo.Z_ROLE. + dbo.Role had no trigger, so dbo.Z_ROLE stayed empty. + + Both new triggers are set-based: User Access Type approves / rejects many rows of a user in + one UPDATE / DELETE, and a trigger that reads one value from "inserted" fails on that (Msg 512). + + Who did it (actionby): + UserAccessType: the application puts the acting user into SESSION_CONTEXT(N'AuditUserID') + (UserAccessTypeService RequestChange / Approve / Reject). Without it the trigger falls back to + the row's own ApprovedBy / ModifiedBy / CreatedBy (a delete then has no known user). + Role: worked out when reading, from the copied row (ApproveBy / AUTHORIZEDBY / CreatedBy). + + Run order: after UserAccessTypeMakerChecker_DB_Changes.sql (needs UserAccessType.Status, + CreatedBy, ModifiedBy, ApprovedBy). Safe to run before or after the code deploys; re-runnable. +*/ + +-- --------------------------------------------------------------------------------------------- +-- Part 1: dbo.Z_UserAccessType +-- --------------------------------------------------------------------------------------------- +IF OBJECT_ID('dbo.Z_UserAccessType', 'U') IS NULL +BEGIN + CREATE TABLE dbo.Z_UserAccessType + ( + audittype VARCHAR(100) NULL, + auditdate DATETIME NULL, + loginid VARCHAR(100) NULL, + name VARCHAR(500) NULL, + payrolltype VARCHAR(500) NULL, + actionby INT NULL, + activities VARCHAR(MAX) NULL + ); + PRINT 'Created dbo.Z_UserAccessType'; +END +GO + +-- --------------------------------------------------------------------------------------------- +-- Part 2: dbo.trUserAccessType +-- --------------------------------------------------------------------------------------------- +IF OBJECT_ID('dbo.trUserAccessType', 'TR') IS NOT NULL + DROP TRIGGER dbo.trUserAccessType; +GO + +CREATE TRIGGER dbo.trUserAccessType +ON dbo.UserAccessType +FOR INSERT, UPDATE, DELETE +AS +BEGIN + SET NOCOUNT ON; + + DECLARE @auditTime DATETIME = GETDATE(); + DECLARE @auditUser INT = TRY_CAST(SESSION_CONTEXT(N'AuditUserID') AS INT); + + -- insert: access requested (maker) or given directly + INSERT INTO dbo.Z_UserAccessType (audittype, auditdate, loginid, name, payrolltype, actionby, activities) + SELECT CASE WHEN i.Status = 2 THEN 'Access type requested' ELSE 'Access type assigned' END, + @auditTime, u.LoginID, u.UserName, p.Description, + COALESCE(@auditUser, i.CreatedBy, i.ApprovedBy), + CASE i.Status + WHEN 1 THEN 'Active' + WHEN 2 THEN 'New Not Yet Approve' + WHEN 5 THEN 'Approved' + ELSE 'None' + END + FROM inserted i + LEFT JOIN deleted d ON d.UserAccessTypeID = i.UserAccessTypeID + LEFT JOIN dbo.Users u ON u.UserID = i.UserID + LEFT JOIN dbo.PayrollType p ON p.PayrollTypeID = i.PayrollTypeID + WHERE d.UserAccessTypeID IS NULL; + + -- update: removal requested (maker), request approved, removal rejected, other change + INSERT INTO dbo.Z_UserAccessType (audittype, auditdate, loginid, name, payrolltype, actionby, activities) + SELECT 'Access type modified', + @auditTime, u.LoginID, u.UserName, p.Description, + COALESCE(@auditUser, + CASE + WHEN i.Status = 3 THEN i.ModifiedBy + WHEN ISNULL(i.ApprovedBy, 0) <> ISNULL(d.ApprovedBy, 0) THEN i.ApprovedBy + ELSE COALESCE(i.ModifiedBy, i.CreatedBy) + END), + CASE + WHEN ISNULL(d.Status, 0) = 2 AND i.Status = 5 THEN 'Approved' + WHEN ISNULL(d.Status, 0) = 3 AND i.Status = 5 THEN 'Removal Rejected' + WHEN ISNULL(d.Status, 0) <> ISNULL(i.Status, 0) THEN + CASE i.Status + WHEN 1 THEN 'Active' + WHEN 2 THEN 'New Not Yet Approve' + WHEN 3 THEN 'Deleted Not Yet Approve' + WHEN 4 THEN 'Edited Not Yet Approve' + WHEN 5 THEN 'Approved' + ELSE 'None' + END + WHEN ISNULL(d.PayrollTypeID, 0) <> ISNULL(i.PayrollTypeID, 0) THEN 'Access type changed' + ELSE ' ' + END + FROM inserted i + JOIN deleted d ON d.UserAccessTypeID = i.UserAccessTypeID + LEFT JOIN dbo.Users u ON u.UserID = i.UserID + LEFT JOIN dbo.PayrollType p ON p.PayrollTypeID = i.PayrollTypeID; + + -- delete: removal approved, request rejected, or access deleted + INSERT INTO dbo.Z_UserAccessType (audittype, auditdate, loginid, name, payrolltype, actionby, activities) + SELECT 'Access type removed', + @auditTime, u.LoginID, u.UserName, p.Description, + @auditUser, + CASE d.Status + WHEN 3 THEN 'Removal Approved' + WHEN 2 THEN 'Request Rejected' + ELSE 'Deleted' + END + FROM deleted d + LEFT JOIN inserted i ON i.UserAccessTypeID = d.UserAccessTypeID + LEFT JOIN dbo.Users u ON u.UserID = d.UserID + LEFT JOIN dbo.PayrollType p ON p.PayrollTypeID = d.PayrollTypeID + WHERE i.UserAccessTypeID IS NULL; +END +GO + +PRINT 'Created trigger dbo.trUserAccessType'; +GO + +-- --------------------------------------------------------------------------------------------- +-- Part 3: dbo.trRole -> dbo.Z_ROLE (copy of the row: Inserted / Update (before) / Update (after) / Deleted) +-- --------------------------------------------------------------------------------------------- +IF OBJECT_ID('dbo.trRole', 'TR') IS NOT NULL + DROP TRIGGER dbo.trRole; +GO + +CREATE TRIGGER dbo.trRole +ON dbo.Role +FOR INSERT, UPDATE, DELETE +AS +BEGIN + SET NOCOUNT ON; + + DECLARE @auditTime DATETIME = GETDATE(); + + -- the row before the change (update) or the removed row (delete) + INSERT INTO dbo.Z_ROLE (AUDITTYPE, AUDITDATE, ROLEID, CODE, NAME, CREATEDBY, CREATEDDATE, SEQUENCE, STATUS, + ROLETYPE, AUTHORIZEDBY, AUTHORIZEDDATE, DESCRIPTION, APPROVEBY, APPROVEDATE) + SELECT CASE WHEN i.RoleID IS NULL THEN 'Deleted' ELSE 'Update (before)' END, + @auditTime, d.RoleID, LEFT(d.Code, 20), LEFT(d.Name, 50), d.CreatedBy, d.CreatedDate, d.Sequence, d.Status, + d.RoleType, d.AUTHORIZEDBY, d.AUTHORIZEDDATE, LEFT(d.Description, 255), d.ApproveBy, d.ApproveDate + FROM deleted d + LEFT JOIN inserted i ON i.RoleID = d.RoleID; + + -- the new row (insert) or the row after the change (update) + INSERT INTO dbo.Z_ROLE (AUDITTYPE, AUDITDATE, ROLEID, CODE, NAME, CREATEDBY, CREATEDDATE, SEQUENCE, STATUS, + ROLETYPE, AUTHORIZEDBY, AUTHORIZEDDATE, DESCRIPTION, APPROVEBY, APPROVEDATE) + SELECT CASE WHEN d.RoleID IS NULL THEN 'Inserted' ELSE 'Update (after)' END, + @auditTime, i.RoleID, LEFT(i.Code, 20), LEFT(i.Name, 50), i.CreatedBy, i.CreatedDate, i.Sequence, i.Status, + i.RoleType, i.AUTHORIZEDBY, i.AUTHORIZEDDATE, LEFT(i.Description, 255), i.ApproveBy, i.ApproveDate + FROM inserted i + LEFT JOIN deleted d ON d.RoleID = i.RoleID; +END +GO + +PRINT 'Created trigger dbo.trRole'; +GO