HRM-10/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.ts
2026-11-17 16:18:50 +06:00

353 lines
14 KiB
TypeScript

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { DataStateChangeEvent, GridComponent, GridDataResult } from '@progress/kendo-angular-grid';
import { type ExcelExportData } from '@progress/kendo-angular-excel-export';
import { process, State } from '@progress/kendo-data-query';
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, EnumSystemAuditHistory, SystemAuditHistory } from '../../_models/Authentication/auditTrail';
/** Rows per virtual "page" - enough to fill the grid viewport a few times over. */
const PAGE_SIZE = 60;
/** Above this many rows a PDF (every row is rendered to the DOM first) would hang the browser. */
const PDF_ROW_LIMIT = 5000;
/** One grid row, the same shape for both tabs. */
export interface AuditTrailRow {
loginID: string;
userName: string;
punchTime: Date;
pcNumber: string;
ipAddress: string;
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<T = AuditTrailRow> {
rows: T[] = [];
private searched: T[] = [];
searchText = '';
loaded = false;
state: State;
view: GridDataResult = { data: [], total: 0 };
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: T[]): void {
this.rows = rows;
this.loaded = true;
this.state = { ...this.state, skip: 0 };
this.applySearch();
}
onSearch(text: string): void {
this.searchText = text ?? '';
this.state = { ...this.state, skip: 0 };
this.applySearch();
}
/** Fired for virtual scrolling, sorting, column filters and the PDF export's "all pages" pass. */
onStateChange(state: DataStateChangeEvent): void {
this.state = state;
this.refresh();
}
/** Rows left after the search and the column filters (what Excel / PDF export). */
get filteredCount(): number {
return this.view.total;
}
/** Excel exports every searched + filtered + sorted row, not just the rendered page. */
allData = (): ExcelExportData => ({
data: process(this.searched, { sort: this.state.sort, filter: this.state.filter }).data
});
private applySearch(): void {
const text = this.searchText.trim().toLowerCase();
this.searched = text === ''
? this.rows
: this.rows.filter(r => this.searchFields.some(f => AuditTrailGrid.searchValue(r, f).includes(text)));
this.refresh();
}
private refresh(): void {
this.view = process(this.searched, this.state);
}
private static searchValue<R>(row: R, field: keyof R): string {
const value: unknown = row[field];
if (value === undefined || value === null) {
return '';
}
if (value instanceof Date) {
return AuditTrailGrid.formatDate(value).toLowerCase();
}
return value.toString().toLowerCase();
}
/** dd-MMM-yyyy hh:mm:ss AM - the same text the grid shows, so the search matches what is on screen. */
static formatDate(d: Date): string {
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const pad = (n: number) => (n < 10 ? '0' : '') + n;
const h = d.getHours() % 12 === 0 ? 12 : d.getHours() % 12;
return pad(d.getDate()) + '-' + months[d.getMonth()] + '-' + d.getFullYear() + ' ' +
pad(h) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) + ' ' + (d.getHours() < 12 ? 'AM' : 'PM');
}
}
/** 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',
styleUrls: ['./system.audittrail.component.scss'],
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false,
})
export class SystemAuditTrailComponent implements OnInit {
readonly pageSize = PAGE_SIZE;
readonly gridDateFormat = '{0:dd-MMM-yyyy hh:mm:ss a}';
readonly excelDateFormat = 'dd-mmm-yyyy hh:mm:ss AM/PM';
userFromDate: Date;
userToDate: Date;
userGrid = new AuditTrailGrid(['loginID', 'userName', 'punchTime', 'pcNumber', 'ipAddress', 'deviceId']);
badFromDate: Date;
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,
public loadingPanel: loadingPanelService) {
this.apiService.selectedMenuName = 'System audit log';
}
ngOnInit(): void {
const today = new Date();
today.setHours(0, 0, 0, 0);
const weekAgo = new Date(today);
weekAgo.setDate(weekAgo.getDate() - 7);
this.userFromDate = new Date(weekAgo);
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;
}
// -- Tab 1: User Audit Trail ---------------------------------------------
loadUserAuditTrail(): void {
if (!this.validDateRange(this.userFromDate, this.userToDate)) {
return;
}
this.loadingPanel.ShowLoadingPanel = true;
this.authService.getUserAuditTrail(this.userFromDate, this.userToDate).subscribe({
next: (items: UserLogInInfo[]) => {
this.userGrid.setRows((items ?? []).map(x => ({
loginID: x.loginID ?? '',
userName: x.userName ?? '',
punchTime: x.loginTime ? new Date(x.loginTime) : null,
pcNumber: x.pcNumber ?? '',
ipAddress: x.ipAddress ?? '',
deviceId: x.deviceId ?? ''
})));
this.loadingPanel.ShowLoadingPanel = false;
},
error: (err) => {
this.loadingPanel.ShowLoadingPanel = false;
this.notificationService.showError(err?.error ?? 'Could not load the user audit trail.');
}
});
}
// -- Tab 2: Bad Login Attempt --------------------------------------------
loadBadLoginAttempts(): void {
if (!this.validDateRange(this.badFromDate, this.badToDate)) {
return;
}
this.loadingPanel.ShowLoadingPanel = true;
this.authService.getBadLoginAuditTrail(this.badFromDate, this.badToDate).subscribe({
next: (items: BadLoginAttemptInfo[]) => {
this.badGrid.setRows((items ?? []).map(x => ({
loginID: x.loginID ?? '',
userName: x.userName ?? '',
punchTime: x.attemptTime ? new Date(x.attemptTime) : null,
pcNumber: x.pcNumber ?? '',
ipAddress: x.ipAddress ?? '',
deviceId: x.deviceId ?? ''
})));
this.loadingPanel.ShowLoadingPanel = false;
},
error: (err) => {
this.loadingPanel.ShowLoadingPanel = false;
this.notificationService.showError(err?.error ?? 'Could not load the bad login attempts.');
}
});
}
// -- 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: { filteredCount: number }): void {
if (auditGrid.filteredCount === 0) {
this.notificationService.showError('There is no data to export.');
return;
}
if (auditGrid.filteredCount > PDF_ROW_LIMIT) {
this.notificationService.showError('PDF export is limited to ' + PDF_ROW_LIMIT.toLocaleString() +
' rows (' + auditGrid.filteredCount.toLocaleString() + ' now). Narrow the date range, search or filter, or use Export to Excel.');
return;
}
grid.saveAsPDF();
}
exportExcel(grid: GridComponent, auditGrid: { filteredCount: number }): void {
if (auditGrid.filteredCount === 0) {
this.notificationService.showError('There is no data to export.');
return;
}
grid.saveAsExcel();
}
fileName(prefix: string, from: Date, to: Date, ext: string): string {
return prefix + '_' + this.apiService.getApiDateString(from) + '_to_' + this.apiService.getApiDateString(to) + '.' + ext;
}
private validDateRange(from: Date, to: Date): boolean {
if (!from || !to) {
this.notificationService.showError('Please select From date and To date.');
return false;
}
if (from.getTime() > to.getTime()) {
this.notificationService.showError('From date can not be after To date.');
return false;
}
return true;
}
}