System Audit Log

This commit is contained in:
Mohaimen Hasan 2026-11-17 16:18:50 +06:00
parent 92d4225a82
commit 7ef18abce5
14 changed files with 1205 additions and 167 deletions

View File

@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using Ease.Core.Model;
namespace HRM.BO
{
#region SystemAuditHistory
/// <summary>Which change history the System Audit Log page asks for (one tab each).</summary>
public enum EnumSystemAuditHistory
{
Role = 1,
RolePermission = 2,
User = 3,
UserRole = 4,
UserAccessType = 5
}
/// <summary>
/// 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.
/// </summary>
public class SystemAuditHistory : ObjectTemplate
{
#region Constructor
public SystemAuditHistory()
{
}
#endregion
#region Properties
/// <summary>What happened, e.g. "User created", "Role modified", "Access type removed".</summary>
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
{
/// <summary>The change history of one page in a date range (both days inclusive), newest first.</summary>
List<SystemAuditHistory> Get(EnumSystemAuditHistory type, DateTime dtFrom, DateTime dtTo);
}
#endregion
}

View File

@ -63,7 +63,7 @@ namespace HRM.BO
/// <summary>Checker: makes every pending change of the user live.</summary>
void Approve(int userID, int approverID);
/// <summary>Checker: drops every pending change of the user; access stays as it was.</summary>
void Reject(int userID);
void Reject(int userID, int rejecterID);
/// <summary>Every row waiting for approval, of every user, with user, payroll type and maker for display.</summary>
List<UserAccessType> GetPending();
}

View File

@ -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
}
}

View File

@ -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)
{

View File

@ -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<T>(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<SystemAuditHistory> Get(EnumSystemAuditHistory type, DateTime dtFrom, DateTime dtTo)
{
List<SystemAuditHistory> items = new List<SystemAuditHistory>();
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<SystemAuditHistory>(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
}
}

View File

@ -240,6 +240,7 @@ namespace HRM.DA
DateTime now = DateTime.Now;
List<int> wanted = (payrollTypeIDs ?? new List<int>()).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();
}

View File

@ -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;
}

View File

@ -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<BadLoginAttemptInfo[]>('/Authentication/getBadLoginAuditTrail/' +
this.apiService.getApiDateString(fromDate) + '/' + this.apiService.getApiDateString(toDate));
}
getSystemAuditHistory(type: EnumSystemAuditHistory, fromDate: Date, toDate: Date) {
return this.apiService.httpGet<SystemAuditHistory[]>('/Authentication/getSystemAuditHistory/' + type + '/' +
this.apiService.getApiDateString(fromDate) + '/' + this.apiService.getApiDateString(toDate));
}
getBookmarks() {
return this.apiService.httpGet<Bookmark[]>('/Authentication/getBookmarks');
}

View File

@ -1,169 +1,269 @@
<app-loading-panel></app-loading-panel>
<div class="sal-page">
<app-loading-panel></app-loading-panel>
<div class="card card-w-title audit-trail">
<kendo-tabstrip [keepTabContent]="true">
<!-- ── Page header ── -->
<section class="sal-card sal-header">
<span class="sal-header-ico"><i class="pi pi-shield"></i></span>
<div class="sal-header-text">
<h2>System Audit Log</h2>
<p>Who signed in, failed logins, and every change made on the Role, Role Permission, User, User Role and User Access Type pages.</p>
</div>
</section>
<kendo-tabstrip class="sal-tabs" [keepTabContent]="true" [scrollable]="true">
<!-- ── Tab 1: User Audit Trail (dbo.UserLoginInfo) ── -->
<kendo-tabstrip-tab title="User Audit Trail" [selected]="true">
<kendo-tabstrip-tab [selected]="true">
<ng-template kendoTabTitle><i class="pi pi-sign-in"></i><span>User Audit Trail</span></ng-template>
<ng-template kendoTabContent>
<div class="grid audit-trail-filter">
<div class="col-12 md:col-1 audit-trail-label">
<label for="dtUserFrom">From Date</label>
<section class="sal-card sal-body">
<div class="sal-filter">
<div class="sal-field">
<label for="dtUserFrom">From Date</label>
<kendo-datepicker id="dtUserFrom" [(ngModel)]="userFromDate" [format]="'dd-MMM-yyyy'" [max]="userToDate"></kendo-datepicker>
</div>
<div class="sal-field">
<label for="dtUserTo">To Date</label>
<kendo-datepicker id="dtUserTo" [(ngModel)]="userToDate" [format]="'dd-MMM-yyyy'" [min]="userFromDate"></kendo-datepicker>
</div>
<button kendoButton themeColor="primary" class="sal-load" [svgIcon]="apiService.KendoSVGIcon['search']"
(click)="loadUserAuditTrail()">Load</button>
</div>
<div class="col-12 md:col-3">
<kendo-datepicker id="dtUserFrom" [(ngModel)]="userFromDate" [format]="'dd-MMM-yyyy'" [max]="userToDate"
style="width: 100%"></kendo-datepicker>
</div>
<div class="col-12 md:col-1 audit-trail-label">
<label for="dtUserTo">To Date</label>
</div>
<div class="col-12 md:col-3">
<kendo-datepicker id="dtUserTo" [(ngModel)]="userToDate" [format]="'dd-MMM-yyyy'" [min]="userFromDate"
style="width: 100%"></kendo-datepicker>
</div>
<div class="col-12 md:col-2">
<button kendoButton themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['search']"
(click)="loadUserAuditTrail()" style="width: 100%;">Load</button>
</div>
</div>
<kendo-grid #userGridRef
[data]="userGrid.view"
[skip]="userGrid.state.skip"
[pageSize]="pageSize"
[sort]="userGrid.state.sort"
[filter]="userGrid.state.filter"
[sortable]="true"
filterable="menu"
scrollable="virtual"
[rowHeight]="36"
[height]="520"
[navigable]="true"
(dataStateChange)="userGrid.onStateChange($event)">
<kendo-grid #userGridRef class="sal-grid"
[data]="userGrid.view"
[skip]="userGrid.state.skip"
[pageSize]="pageSize"
[sort]="userGrid.state.sort"
[filter]="userGrid.state.filter"
[sortable]="true"
filterable="menu"
scrollable="virtual"
[rowHeight]="36"
[height]="520"
[navigable]="true"
(dataStateChange)="userGrid.onStateChange($event)">
<ng-template kendoGridToolbarTemplate>
<input kendoTextBox class="audit-trail-search" placeholder="Search in all columns..."
[value]="userGrid.searchText" (input)="userGrid.onSearch($any($event.target).value)" />
<span class="audit-trail-count">
{{ userGrid.filteredCount | number }} of {{ userGrid.rows.length | number }} records
</span>
<kendo-grid-spacer></kendo-grid-spacer>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']"
(click)="exportExcel(userGridRef, userGrid)">Export to Excel</button>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['filePdf']"
(click)="exportPdf(userGridRef, userGrid)">Export to PDF</button>
</ng-template>
<ng-template kendoGridToolbarTemplate>
<span class="sal-search">
<i class="pi pi-search"></i>
<input kendoTextBox placeholder="Search in all columns..."
[value]="userGrid.searchText" (input)="userGrid.onSearch($any($event.target).value)" />
</span>
<span class="sal-count">
<strong>{{ userGrid.filteredCount | number }}</strong>&nbsp;of {{ userGrid.rows.length | number }} records
</span>
<kendo-grid-spacer></kendo-grid-spacer>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']"
(click)="exportExcel(userGridRef, userGrid)">Export to Excel</button>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['filePdf']"
(click)="exportPdf(userGridRef, userGrid)">Export to PDF</button>
</ng-template>
<kendo-grid-column field="loginID" title="Login ID" [width]="160"></kendo-grid-column>
<kendo-grid-column field="userName" title="Name" [width]="240"></kendo-grid-column>
<kendo-grid-column field="punchTime" title="Punch Time" [width]="210" filter="date"
[format]="gridDateFormat"></kendo-grid-column>
<kendo-grid-column field="pcNumber" title="Computer" [width]="260"></kendo-grid-column>
<kendo-grid-column field="ipAddress" title="IP Address" [width]="150"></kendo-grid-column>
<kendo-grid-column field="deviceId" title="Device ID" [width]="220"></kendo-grid-column>
<kendo-grid-column field="loginID" title="Login ID" [width]="160"></kendo-grid-column>
<kendo-grid-column field="userName" title="Name" [width]="240"></kendo-grid-column>
<kendo-grid-column field="punchTime" title="Punch Time" [width]="210" filter="date"
[format]="gridDateFormat"></kendo-grid-column>
<kendo-grid-column field="pcNumber" title="Computer" [width]="260"></kendo-grid-column>
<kendo-grid-column field="ipAddress" title="IP Address" [width]="150"></kendo-grid-column>
<kendo-grid-column field="deviceId" title="Device ID" [width]="220"></kendo-grid-column>
<ng-template kendoGridNoRecordsTemplate>
{{ userGrid.loaded ? 'No login found for this date range.' : 'Select a date range and press Load.' }}
</ng-template>
<ng-template kendoGridNoRecordsTemplate>
<div class="sal-empty">
<i class="pi" [class.pi-inbox]="userGrid.loaded" [class.pi-calendar]="!userGrid.loaded"></i>
{{ userGrid.loaded ? 'No login found for this date range.' : 'Select a date range and press Load.' }}
</div>
</ng-template>
<kendo-grid-excel [fileName]="fileName('UserAuditTrail', userFromDate, userToDate, 'xlsx')"
[fetchData]="userGrid.allData">
<kendo-excelexport-column field="loginID" title="Login ID" [width]="140"></kendo-excelexport-column>
<kendo-excelexport-column field="userName" title="Name" [width]="220"></kendo-excelexport-column>
<kendo-excelexport-column field="punchTime" title="Punch Time" [width]="180"
[cellOptions]="{ format: excelDateFormat }"></kendo-excelexport-column>
<kendo-excelexport-column field="pcNumber" title="Computer" [width]="300"></kendo-excelexport-column>
<kendo-excelexport-column field="ipAddress" title="IP Address" [width]="130"></kendo-excelexport-column>
<kendo-excelexport-column field="deviceId" title="Device ID" [width]="220"></kendo-excelexport-column>
</kendo-grid-excel>
<kendo-grid-excel [fileName]="fileName('UserAuditTrail', userFromDate, userToDate, 'xlsx')"
[fetchData]="userGrid.allData">
<kendo-excelexport-column field="loginID" title="Login ID" [width]="140"></kendo-excelexport-column>
<kendo-excelexport-column field="userName" title="Name" [width]="220"></kendo-excelexport-column>
<kendo-excelexport-column field="punchTime" title="Punch Time" [width]="180"
[cellOptions]="{ format: excelDateFormat }"></kendo-excelexport-column>
<kendo-excelexport-column field="pcNumber" title="Computer" [width]="300"></kendo-excelexport-column>
<kendo-excelexport-column field="ipAddress" title="IP Address" [width]="130"></kendo-excelexport-column>
<kendo-excelexport-column field="deviceId" title="Device ID" [width]="220"></kendo-excelexport-column>
</kendo-grid-excel>
<kendo-grid-pdf [fileName]="fileName('UserAuditTrail', userFromDate, userToDate, 'pdf')"
[allPages]="true" [repeatHeaders]="true" paperSize="A4" [landscape]="true" [scale]="0.7">
<kendo-grid-pdf-margin top="1cm" left="1cm" right="1cm" bottom="1cm"></kendo-grid-pdf-margin>
</kendo-grid-pdf>
</kendo-grid>
<kendo-grid-pdf [fileName]="fileName('UserAuditTrail', userFromDate, userToDate, 'pdf')"
[allPages]="true" [repeatHeaders]="true" paperSize="A4" [landscape]="true" [scale]="0.7">
<kendo-grid-pdf-margin top="1cm" left="1cm" right="1cm" bottom="1cm"></kendo-grid-pdf-margin>
</kendo-grid-pdf>
</kendo-grid>
</section>
</ng-template>
</kendo-tabstrip-tab>
<!-- ── Tab 2: Bad Login Attempt (dbo.BadLoginAttemptInfo) ── -->
<kendo-tabstrip-tab title="Bad Login Attempt">
<kendo-tabstrip-tab>
<ng-template kendoTabTitle><i class="pi pi-ban"></i><span>Bad Login Attempt</span></ng-template>
<ng-template kendoTabContent>
<div class="grid audit-trail-filter">
<div class="col-12 md:col-1 audit-trail-label">
<label for="dtBadFrom">From Date</label>
<section class="sal-card sal-body">
<div class="sal-filter">
<div class="sal-field">
<label for="dtBadFrom">From Date</label>
<kendo-datepicker id="dtBadFrom" [(ngModel)]="badFromDate" [format]="'dd-MMM-yyyy'" [max]="badToDate"></kendo-datepicker>
</div>
<div class="sal-field">
<label for="dtBadTo">To Date</label>
<kendo-datepicker id="dtBadTo" [(ngModel)]="badToDate" [format]="'dd-MMM-yyyy'" [min]="badFromDate"></kendo-datepicker>
</div>
<button kendoButton themeColor="primary" class="sal-load" [svgIcon]="apiService.KendoSVGIcon['search']"
(click)="loadBadLoginAttempts()">Load</button>
</div>
<div class="col-12 md:col-3">
<kendo-datepicker id="dtBadFrom" [(ngModel)]="badFromDate" [format]="'dd-MMM-yyyy'" [max]="badToDate"
style="width: 100%"></kendo-datepicker>
</div>
<div class="col-12 md:col-1 audit-trail-label">
<label for="dtBadTo">To Date</label>
</div>
<div class="col-12 md:col-3">
<kendo-datepicker id="dtBadTo" [(ngModel)]="badToDate" [format]="'dd-MMM-yyyy'" [min]="badFromDate"
style="width: 100%"></kendo-datepicker>
</div>
<div class="col-12 md:col-2">
<button kendoButton themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['search']"
(click)="loadBadLoginAttempts()" style="width: 100%;">Load</button>
</div>
</div>
<kendo-grid #badGridRef
[data]="badGrid.view"
[skip]="badGrid.state.skip"
[pageSize]="pageSize"
[sort]="badGrid.state.sort"
[filter]="badGrid.state.filter"
[sortable]="true"
filterable="menu"
scrollable="virtual"
[rowHeight]="36"
[height]="520"
[navigable]="true"
(dataStateChange)="badGrid.onStateChange($event)">
<kendo-grid #badGridRef class="sal-grid"
[data]="badGrid.view"
[skip]="badGrid.state.skip"
[pageSize]="pageSize"
[sort]="badGrid.state.sort"
[filter]="badGrid.state.filter"
[sortable]="true"
filterable="menu"
scrollable="virtual"
[rowHeight]="36"
[height]="520"
[navigable]="true"
(dataStateChange)="badGrid.onStateChange($event)">
<ng-template kendoGridToolbarTemplate>
<input kendoTextBox class="audit-trail-search" placeholder="Search in all columns..."
[value]="badGrid.searchText" (input)="badGrid.onSearch($any($event.target).value)" />
<span class="audit-trail-count">
{{ badGrid.filteredCount | number }} of {{ badGrid.rows.length | number }} records
</span>
<kendo-grid-spacer></kendo-grid-spacer>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']"
(click)="exportExcel(badGridRef, badGrid)">Export to Excel</button>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['filePdf']"
(click)="exportPdf(badGridRef, badGrid)">Export to PDF</button>
</ng-template>
<ng-template kendoGridToolbarTemplate>
<span class="sal-search">
<i class="pi pi-search"></i>
<input kendoTextBox placeholder="Search in all columns..."
[value]="badGrid.searchText" (input)="badGrid.onSearch($any($event.target).value)" />
</span>
<span class="sal-count">
<strong>{{ badGrid.filteredCount | number }}</strong>&nbsp;of {{ badGrid.rows.length | number }} records
</span>
<kendo-grid-spacer></kendo-grid-spacer>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']"
(click)="exportExcel(badGridRef, badGrid)">Export to Excel</button>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['filePdf']"
(click)="exportPdf(badGridRef, badGrid)">Export to PDF</button>
</ng-template>
<kendo-grid-column field="loginID" title="Login ID" [width]="200"></kendo-grid-column>
<kendo-grid-column field="punchTime" title="Punch Time" [width]="220" filter="date"
[format]="gridDateFormat"></kendo-grid-column>
<kendo-grid-column field="pcNumber" title="Computer" [width]="280"></kendo-grid-column>
<kendo-grid-column field="ipAddress" title="IP Address" [width]="150"></kendo-grid-column>
<kendo-grid-column field="deviceId" title="Device ID" [width]="220"></kendo-grid-column>
<kendo-grid-column field="loginID" title="Login ID" [width]="200"></kendo-grid-column>
<kendo-grid-column field="punchTime" title="Punch Time" [width]="220" filter="date"
[format]="gridDateFormat"></kendo-grid-column>
<kendo-grid-column field="pcNumber" title="Computer" [width]="280"></kendo-grid-column>
<kendo-grid-column field="ipAddress" title="IP Address" [width]="150"></kendo-grid-column>
<kendo-grid-column field="deviceId" title="Device ID" [width]="220"></kendo-grid-column>
<ng-template kendoGridNoRecordsTemplate>
{{ badGrid.loaded ? 'No bad login attempt found for this date range.' : 'Select a date range and press Load.' }}
</ng-template>
<ng-template kendoGridNoRecordsTemplate>
<div class="sal-empty">
<i class="pi" [class.pi-inbox]="badGrid.loaded" [class.pi-calendar]="!badGrid.loaded"></i>
{{ badGrid.loaded ? 'No bad login attempt found for this date range.' : 'Select a date range and press Load.' }}
</div>
</ng-template>
<kendo-grid-excel [fileName]="fileName('BadLoginAttempt', badFromDate, badToDate, 'xlsx')"
[fetchData]="badGrid.allData">
<kendo-excelexport-column field="loginID" title="Login ID" [width]="160"></kendo-excelexport-column>
<kendo-excelexport-column field="punchTime" title="Punch Time" [width]="180"
[cellOptions]="{ format: excelDateFormat }"></kendo-excelexport-column>
<kendo-excelexport-column field="pcNumber" title="Computer" [width]="300"></kendo-excelexport-column>
<kendo-excelexport-column field="ipAddress" title="IP Address" [width]="130"></kendo-excelexport-column>
<kendo-excelexport-column field="deviceId" title="Device ID" [width]="220"></kendo-excelexport-column>
</kendo-grid-excel>
<kendo-grid-excel [fileName]="fileName('BadLoginAttempt', badFromDate, badToDate, 'xlsx')"
[fetchData]="badGrid.allData">
<kendo-excelexport-column field="loginID" title="Login ID" [width]="160"></kendo-excelexport-column>
<kendo-excelexport-column field="punchTime" title="Punch Time" [width]="180"
[cellOptions]="{ format: excelDateFormat }"></kendo-excelexport-column>
<kendo-excelexport-column field="pcNumber" title="Computer" [width]="300"></kendo-excelexport-column>
<kendo-excelexport-column field="ipAddress" title="IP Address" [width]="130"></kendo-excelexport-column>
<kendo-excelexport-column field="deviceId" title="Device ID" [width]="220"></kendo-excelexport-column>
</kendo-grid-excel>
<kendo-grid-pdf [fileName]="fileName('BadLoginAttempt', badFromDate, badToDate, 'pdf')"
[allPages]="true" [repeatHeaders]="true" paperSize="A4" [landscape]="true" [scale]="0.7">
<kendo-grid-pdf-margin top="1cm" left="1cm" right="1cm" bottom="1cm"></kendo-grid-pdf-margin>
</kendo-grid-pdf>
</kendo-grid>
<kendo-grid-pdf [fileName]="fileName('BadLoginAttempt', badFromDate, badToDate, 'pdf')"
[allPages]="true" [repeatHeaders]="true" paperSize="A4" [landscape]="true" [scale]="0.7">
<kendo-grid-pdf-margin top="1cm" left="1cm" right="1cm" bottom="1cm"></kendo-grid-pdf-margin>
</kendo-grid-pdf>
</kendo-grid>
</section>
</ng-template>
</kendo-tabstrip-tab>
<!-- ── Tabs 3-7: change history of the Authentication pages (Z_ tables) ── -->
@for (tab of historyTabs; track tab.type) {
<kendo-tabstrip-tab>
<ng-template kendoTabTitle><i [class]="tab.icon"></i><span>{{ tab.title }}</span></ng-template>
<ng-template kendoTabContent>
<section class="sal-card sal-body">
<div class="sal-filter">
<div class="sal-field">
<label [for]="'dtHistFrom' + tab.type">From Date</label>
<kendo-datepicker [id]="'dtHistFrom' + tab.type" [(ngModel)]="tab.fromDate" [format]="'dd-MMM-yyyy'"
[max]="tab.toDate"></kendo-datepicker>
</div>
<div class="sal-field">
<label [for]="'dtHistTo' + tab.type">To Date</label>
<kendo-datepicker [id]="'dtHistTo' + tab.type" [(ngModel)]="tab.toDate" [format]="'dd-MMM-yyyy'"
[min]="tab.fromDate"></kendo-datepicker>
</div>
<button kendoButton themeColor="primary" class="sal-load" [svgIcon]="apiService.KendoSVGIcon['search']"
(click)="loadHistory(tab)">Load</button>
</div>
<kendo-grid #historyGridRef class="sal-grid"
[data]="tab.grid.view"
[skip]="tab.grid.state.skip"
[pageSize]="pageSize"
[sort]="tab.grid.state.sort"
[filter]="tab.grid.state.filter"
[sortable]="true"
filterable="menu"
scrollable="virtual"
[rowHeight]="36"
[height]="520"
[navigable]="true"
(dataStateChange)="tab.grid.onStateChange($event)">
<ng-template kendoGridToolbarTemplate>
<span class="sal-search">
<i class="pi pi-search"></i>
<input kendoTextBox placeholder="Search in all columns..."
[value]="tab.grid.searchText" (input)="tab.grid.onSearch($any($event.target).value)" />
</span>
<span class="sal-count">
<strong>{{ tab.grid.filteredCount | number }}</strong>&nbsp;of {{ tab.grid.rows.length | number }} records
</span>
<kendo-grid-spacer></kendo-grid-spacer>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']"
(click)="exportExcel(historyGridRef, tab.grid)">Export to Excel</button>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['filePdf']"
(click)="exportPdf(historyGridRef, tab.grid)">Export to PDF</button>
</ng-template>
@for (col of tab.allColumns; track col.field) {
@if (col.isDate) {
<kendo-grid-column [field]="col.field" [title]="col.title" [width]="col.width" filter="date"
[format]="gridDateFormat"></kendo-grid-column>
} @else {
<kendo-grid-column [field]="col.field" [title]="col.title" [width]="col.width"></kendo-grid-column>
}
}
<ng-template kendoGridNoRecordsTemplate>
<div class="sal-empty">
<i class="pi" [class.pi-inbox]="tab.grid.loaded" [class.pi-calendar]="!tab.grid.loaded"></i>
{{ tab.grid.loaded ? 'No change found for this date range.' : 'Select a date range and press Load.' }}
</div>
</ng-template>
<kendo-grid-excel [fileName]="fileName(tab.filePrefix, tab.fromDate, tab.toDate, 'xlsx')"
[fetchData]="tab.grid.allData">
@for (col of tab.allColumns; track col.field) {
@if (col.isDate) {
<kendo-excelexport-column [field]="col.field" [title]="col.title" [width]="col.width"
[cellOptions]="{ format: excelDateFormat }"></kendo-excelexport-column>
} @else {
<kendo-excelexport-column [field]="col.field" [title]="col.title" [width]="col.width"></kendo-excelexport-column>
}
}
</kendo-grid-excel>
<kendo-grid-pdf [fileName]="fileName(tab.filePrefix, tab.fromDate, tab.toDate, 'pdf')"
[allPages]="true" [repeatHeaders]="true" paperSize="A4" [landscape]="true" [scale]="0.7">
<kendo-grid-pdf-margin top="1cm" left="1cm" right="1cm" bottom="1cm"></kendo-grid-pdf-margin>
</kendo-grid-pdf>
</kendo-grid>
</section>
</ng-template>
</kendo-tabstrip-tab>
}
</kendo-tabstrip>
</div>

View File

@ -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;
}
}

View File

@ -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<T = AuditTrailRow> {
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<R>(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<AuditHistoryRow>;
/** 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<AuditHistoryRow>(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;

View File

@ -43,6 +43,7 @@ namespace HRM.UI.Configuration.DI
services.AddTransient<IUserService, UserService>();
services.AddTransient<IUserLogInInfoService, UserLogInInfoService>();
services.AddTransient<IBadLoginAttemptInfoService, BadLoginAttemptInfoService>();
services.AddTransient<ISystemAuditHistoryService, SystemAuditHistoryService>();
services.AddTransient<IPasswordHistoryService, PasswordHistoryService>();
services.AddTransient<ISearchEmployeeService, SearchEmployeeService>();
services.AddTransient<IHREmployeeService, HREmployeeService>();

View File

@ -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<SystemAuditHistory> items = new List<SystemAuditHistory>();
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]

View File

@ -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