import { ChangeDetectionStrategy, Component, EventEmitter, Inject, Input, LOCALE_ID, OnDestroy, OnInit, Optional, Output } from '@angular/core'; import { formatDate } from '@angular/common'; import { of, Subject, Subscription } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, finalize, switchMap } from 'rxjs/operators'; import { GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid'; import { SortDescriptor } from '@progress/kendo-data-query'; import { saveAs } from 'file-saver'; import { ApiService } from 'src/app/app.api.service'; import { HRMNotificationService } from 'src/app/app.notification.service'; import { loadingPanelService } from 'src/app/hrm-loding panel/loding.panel.service'; import { VirtualGridService } from 'src/app/_services/common/virtual-grid.service'; import { EnumVirtualGridColumnType, VirtualGridFilters, VirtualGridLayout, VirtualGridLoadedEvent, VirtualGridPage, VirtualGridRequest } from 'src/app/_models/common/virtual-grid'; @Component({ selector: 'app-virtual-grid', templateUrl: './virtual-grid.component.html', styleUrls: ['./virtual-grid.component.scss'], changeDetection: ChangeDetectionStrategy.Eager, standalone: false, }) export class VirtualGridComponent implements OnInit, OnDestroy { /** Server grid key (VirtualGridRegistry). Required. */ @Input() gridKey: string; /** Grid height in px. */ @Input() height = 600; /** Rows fetched per window. */ @Input() pageSize = 100; /** Minimum (estimated) row height in px. Rows with wrapped text grow; Kendo measures the real heights while scrolling. */ @Input() rowHeight = 36; @Input() searchPlaceholder = 'Search in all columns...'; @Input() noRecordsText = 'No records found.'; /** Excel file name; defaults to the grid title. */ @Input() exportFileName: string; @Input() showSearch = true; @Input() showExport = true; /** After every loaded window. */ @Output() loaded = new EventEmitter(); layout: VirtualGridLayout; layoutError = ''; started = false; gridView: GridDataResult = { data: [], total: 0 }; totalWithoutSearch = 0; gridLoading = false; skip = 0; sort: SortDescriptor[] = []; searchText = ''; appliedSearch = ''; exporting = false; readonly columnType = EnumVirtualGridColumnType; private filters: VirtualGridFilters = {}; private pendingFilters: VirtualGridFilters = null; private firstLoad = false; private readonly load$ = new Subject(); private readonly search$ = new Subject(); private readonly subscriptions = new Subscription(); private readonly money = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); constructor(public apiService: ApiService, private virtualGridService: VirtualGridService, @Inject(LOCALE_ID) private locale: string, @Optional() private notificationService: HRMNotificationService, @Optional() private loadingPanel: loadingPanelService) { } ngOnInit(): void { this.subscriptions.add( this.virtualGridService.getLayout(this.gridKey).subscribe( (layout) => { layout.columns = (layout.columns || []).map(c => ({ ...c, width: this.fitWidth(c) })); this.layout = layout; this.resetSort(); if (this.pendingFilters) { const filters = this.pendingFilters; this.pendingFilters = null; this.load(filters); } }, (err) => { this.layoutError = this.errorText(err, 'Failed to load the grid.'); this.showError(this.layoutError); } ) ); // A newer request (scroll, sort, search) cancels an older one still in flight, // so a slow response can never overwrite newer rows. this.subscriptions.add( this.load$.pipe( switchMap(request => { this.gridLoading = true; return this.virtualGridService.getPage(request).pipe( catchError(err => { this.showError(this.errorText(err, 'Failed to load data.')); return of(null as VirtualGridPage); }), finalize(() => this.gridLoading = false) ); }) ).subscribe(page => this.onPageLoaded(page)) ); // Ask the server only once the user stops typing. this.subscriptions.add( this.search$.pipe(debounceTime(400), distinctUntilChanged()).subscribe(text => { this.appliedSearch = text; this.skip = 0; this.requestPage(); }) ); } ngOnDestroy(): void { this.subscriptions.unsubscribe(); } /** Shows the grid for these filters, from the first row, with the search cleared and the default sort. */ load(filters: VirtualGridFilters): void { if (!this.layout) { this.pendingFilters = filters || {}; // runs as soon as the layout arrives return; } this.filters = { ...(filters || {}) }; this.searchText = ''; this.appliedSearch = ''; this.search$.next(''); // keeps distinctUntilChanged in step with the cleared box this.skip = 0; this.resetSort(); this.gridView = { data: [], total: 0 }; this.totalWithoutSearch = 0; this.started = true; this.firstLoad = true; this.requestPage(true); // Preview: the server reloads the data instead of using its kept copy } /** Reloads the current window, keeping filters, search and sort. */ reload(): void { this.requestPage(); } onPageChange(event: PageChangeEvent): void { this.skip = event.skip; this.requestPage(); } onSortChange(sort: SortDescriptor[]): void { this.sort = sort; this.skip = 0; this.requestPage(); } onSearchChange(text: string): void { this.search$.next((text || '').trim()); } exportExcel(): void { if (!this.started || this.gridView.total === 0 || this.exporting) { return; } this.exporting = true; if (this.loadingPanel) { this.loadingPanel.ShowLoadingPanel = true; } const request = { ...this.buildRequest(0, 0), fields: this.layout.columns.map(c => c.field) }; const fileName = this.exportFileName || (this.layout.title || this.gridKey).replace(/[^A-Za-z0-9]+/g, '') + '.xlsx'; this.virtualGridService.exportExcel(request).pipe( finalize(() => { this.exporting = false; if (this.loadingPanel) { this.loadingPanel.ShowLoadingPanel = false; } }) ).subscribe( (blob: Blob) => saveAs(blob, fileName), (err) => this.showBlobError(err, 'Failed to export to Excel.') ); } /** * At least wide enough for the header title on one line plus the sort icon and cell padding, * so no grid ever needs a wrapped or cut-off header (~8px per character + 48px). */ private fitWidth(column: { title: string; width: number }): number { const titleWidth = (column.title || '').length * 8 + 48; return Math.max(column.width || 0, titleWidth); } private resetSort(): void { this.sort = this.layout && this.layout.defaultSortField ? [{ field: this.layout.defaultSortField, dir: this.layout.defaultSortDir || 'asc' }] : []; } private requestPage(refresh = false): void { if (!this.started || !this.layout) { return; } this.load$.next({ ...this.buildRequest(this.skip, this.pageSize), refresh: refresh }); } private buildRequest(skip: number, take: number): VirtualGridRequest { const sort = this.sort && this.sort.length > 0 && this.sort[0].dir ? this.sort[0] : null; return { gridKey: this.gridKey, filters: this.filters, skip: skip, take: take, search: this.appliedSearch || undefined, sortField: sort ? sort.field : undefined, sortDir: sort ? (sort.dir as 'asc' | 'desc') : undefined, }; } private onPageLoaded(page: VirtualGridPage): void { if (!page) { return; } this.gridView = { data: (page.data || []).map(row => this.formatRow(row)), total: page.total }; this.totalWithoutSearch = page.totalWithoutSearch; this.loaded.emit({ total: page.total, totalWithoutSearch: page.totalWithoutSearch, firstLoad: this.firstLoad }); this.firstLoad = false; } /** Display formatting by column type: dates 'dd MMM yyyy', money with 2 decimals — the same text the server searches. */ private formatRow(row: { [field: string]: any }): { [field: string]: any } { const result: { [field: string]: any } = { ...row }; for (const column of this.layout.columns) { const value = row[column.field]; if (value === null || value === undefined || value === '') { result[column.field] = ''; continue; } switch (column.type) { case EnumVirtualGridColumnType.Date: result[column.field] = formatDate(value, 'dd MMM yyyy', this.locale); break; case EnumVirtualGridColumnType.DateTime: result[column.field] = formatDate(value, 'dd MMM yyyy HH:mm', this.locale); break; case EnumVirtualGridColumnType.Money: result[column.field] = this.money.format(Number(value)); break; default: result[column.field] = String(value); } } return result; } private errorText(err: any, fallback: string): string { if (typeof err === 'string' && err) { return err; } if (err && typeof err.error === 'string' && err.error) { return err.error; } return fallback; } private showError(message: string): void { if (this.notificationService) { this.notificationService.showError(message); } else { console.error(message); } } /** A failed file download returns its error message as a Blob; read it before showing it. */ private showBlobError(err: any, fallback: string): void { const blob: Blob = err instanceof Blob ? err : (err && err.error instanceof Blob ? err.error : null); if (blob) { blob.text().then(text => this.showError(text || fallback), () => this.showError(fallback)); } else { this.showError(this.errorText(err, fallback)); } } }