import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnDestroy, OnInit, Optional, Output, ViewChild } from '@angular/core'; import { formatDate } from '@angular/common'; import { of, Subject, Subscription } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, finalize, switchMap } from 'rxjs/operators'; import { ExcelExportData } from '@progress/kendo-angular-excel-export'; import { GridComponent, GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid'; import { SortDescriptor } from '@progress/kendo-data-query'; 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 { VirtualGridColumn, VirtualGridLoadedEvent, VirtualPageRequest, VirtualPageResult } from 'src/app/_models/common/virtual-grid'; /** * Common virtual-scrolling grid. The page gives it an endpoint and the columns: * * * this.grid.load({ fromDate: this.fromDate, toDate: this.toDate }); * * The grid asks for 100 rows at a time while the user scrolls; SQL Server reads just those rows and does * the search, sort and total count (VirtualPagingDA). Export to Excel downloads every matching row. */ @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 { /** The page endpoint, e.g. '/Employee/getDiscontinueEmployeePage'. Required. */ @Input() url: string; /** The columns. field = a column alias of the page's SQL query (camelCase). Required. */ @Input() columns: VirtualGridColumn[] = []; @Input() height = 600; @Input() pageSize = 100; /** Minimum row height; rows with wrapped text grow. */ @Input() rowHeight = 36; @Input() searchPlaceholder = 'Search in all columns...'; @Input() noRecordsText = 'No records found.'; @Input() exportFileName = 'Export.xlsx'; @Input() showSearch = true; @Input() showExport = true; /** After every loaded window. */ @Output() loaded = new EventEmitter(); @ViewChild(GridComponent) kendoGrid: GridComponent; started = false; gridView: GridDataResult = { data: [], total: 0 }; totalWithoutSearch = 0; gridLoading = false; skip = 0; sort: SortDescriptor[] = []; searchText = ''; appliedSearch = ''; exporting = false; exportRows: any[] = []; private filters: { [name: string]: string } = {}; private firstLoad = false; private totalsPending = false; private readonly load$ = new Subject(); private readonly search$ = new Subject(); private readonly subscriptions = new Subscription(); constructor(public apiService: ApiService, @Optional() private notificationService: HRMNotificationService, @Optional() private loadingPanel: loadingPanelService) { } ngOnInit(): void { // A newer request (scroll, sort, search) cancels an older one, so old rows never overwrite new ones. this.subscriptions.add( this.load$.pipe( switchMap(request => { this.gridLoading = true; return this.apiService.httpPost(this.url, request).pipe( catchError(err => { this.showError(this.errorText(err, 'Failed to load data.')); return of(null as VirtualPageResult); }), finalize(() => this.gridLoading = false) ); }) ).subscribe(result => this.onPageLoaded(result)) ); // Search 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(true); // a new search changes the total }) ); } ngOnDestroy(): void { this.subscriptions.unsubscribe(); } /** Preview: shows the grid for these filters (Date values are sent as 'yyyy-MM-dd'). */ load(filters: { [name: string]: any }): void { this.filters = {}; Object.keys(filters || {}).forEach(name => { const value = filters[name]; if (value !== null && value !== undefined && value !== '') { this.filters[name] = value instanceof Date ? formatDate(value, 'yyyy-MM-dd', 'en-US') : String(value); } }); this.searchText = ''; this.appliedSearch = ''; this.search$.next(''); this.skip = 0; this.sort = []; this.gridView = { data: [], total: 0 }; this.totalWithoutSearch = 0; this.started = true; this.firstLoad = true; this.requestPage(true); } onPageChange(event: PageChangeEvent): void { this.skip = event.skip; this.requestPage(false); } onSortChange(sort: SortDescriptor[]): void { this.sort = sort; this.skip = 0; this.requestPage(false); } onSearchChange(text: string): void { this.search$.next((text || '').trim()); } /** Loads every matching row (same search and sort), then lets Kendo build the Excel file. */ exportExcel(): void { if (!this.started || this.gridView.total === 0 || this.exporting) { return; } this.setExporting(true); this.apiService.httpPost(this.url, this.buildRequest(0, 0, false)).subscribe( (result) => { this.exportRows = (result.data || []).map(row => this.prepareRow(row)); setTimeout(() => this.kendoGrid.saveAsExcel()); }, (err) => { this.setExporting(false); this.showError(this.errorText(err, 'Failed to export to Excel.')); } ); } /** Kendo asks for the rows to put in the Excel file. */ excelData = (): ExcelExportData => ({ data: this.exportRows }); onExcelCreated(): void { this.exportRows = []; this.setExporting(false); } /** Grid display format by column type. */ displayFormat(column: VirtualGridColumn): string { switch (column.type) { case 'date': return '{0:dd MMM yyyy}'; case 'datetime': return '{0:dd MMM yyyy HH:mm}'; case 'money': return '{0:n2}'; default: return undefined; } } /** Excel cell format by column type. */ excelOptions(column: VirtualGridColumn): any { switch (column.type) { case 'date': return { format: 'dd MMM yyyy' }; case 'datetime': return { format: 'dd MMM yyyy HH:mm' }; case 'money': return { format: '#,##0.00', textAlign: 'right' }; case 'number': return { textAlign: 'right' }; default: return {}; } } isNumber(column: VirtualGridColumn): boolean { return column.type === 'money' || column.type === 'number'; } /** At least wide enough for the header title on one line (~8px per character + sort icon/padding). */ columnWidth(column: VirtualGridColumn): number { return Math.max(column.width || 130, (column.title || '').length * 8 + 48); } /** countTotal: true on Preview and a new search (the total can change); scroll and sort keep the totals. */ private requestPage(countTotal: boolean): void { if (this.started && this.url) { // Keep asking for the totals until a response brings them (a newer request cancels an older one). this.totalsPending = this.totalsPending || countTotal; this.load$.next(this.buildRequest(this.skip, this.pageSize, this.totalsPending)); } } private buildRequest(skip: number, take: number, countTotal: boolean): VirtualPageRequest { const sort = this.sort && this.sort.length > 0 && this.sort[0].dir ? this.sort[0] : null; return { filters: this.filters, columns: this.columns.map(c => ({ field: c.field, type: c.type || 'text' })), skip: skip, take: take, search: this.appliedSearch || undefined, sortField: sort ? sort.field : undefined, sortDir: sort ? (sort.dir as 'asc' | 'desc') : undefined, countTotal: countTotal, }; } private onPageLoaded(result: VirtualPageResult): void { if (!result) { return; } // Totals come only when they were counted; otherwise keep the ones we have. const counted = result.total !== null && result.total !== undefined; if (counted) { this.totalsPending = false; } const total = counted ? result.total : this.gridView.total; if (result.totalWithoutSearch !== null && result.totalWithoutSearch !== undefined) { this.totalWithoutSearch = result.totalWithoutSearch; } this.gridView = { data: (result.data || []).map(row => this.prepareRow(row)), total: total }; this.loaded.emit({ total: total, totalWithoutSearch: this.totalWithoutSearch, firstLoad: this.firstLoad }); this.firstLoad = false; } /** Dates arrive as text; turn them into Date so the grid and Excel format them. */ private prepareRow(row: { [field: string]: any }): { [field: string]: any } { for (const column of this.columns) { if ((column.type === 'date' || column.type === 'datetime') && row[column.field]) { row[column.field] = new Date(row[column.field]); } } return row; } private setExporting(value: boolean): void { this.exporting = value; if (this.loadingPanel) { this.loadingPanel.ShowLoadingPanel = value; } } 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); } } }