HRM-10/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts
2026-11-09 14:54:13 +06:00

266 lines
8.9 KiB
TypeScript

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:
*
* <app-virtual-grid #grid url="/Employee/getDiscontinueEmployeePage" [columns]="columns"></app-virtual-grid>
* this.grid.load({ fromDate: this.fromDate, toDate: this.toDate });
*
* The grid loads 100 rows at a time while the user scrolls; search, sort and the total count are done
* on the server (VirtualPaging.Page). 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 = property name of the server object (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<VirtualGridLoadedEvent>();
@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 readonly load$ = new Subject<VirtualPageRequest>();
private readonly search$ = new Subject<string>();
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<VirtualPageResult>(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(false);
})
);
}
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<VirtualPageResult>(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);
}
private requestPage(refresh: boolean): void {
if (this.started && this.url) {
this.load$.next(this.buildRequest(this.skip, this.pageSize, refresh));
}
}
private buildRequest(skip: number, take: number, refresh: boolean): VirtualPageRequest {
const sort = this.sort && this.sort.length > 0 && this.sort[0].dir ? this.sort[0] : null;
return {
filters: this.filters,
fields: this.columns.map(c => c.field),
skip: skip,
take: take,
search: this.appliedSearch || undefined,
sortField: sort ? sort.field : undefined,
sortDir: sort ? (sort.dir as 'asc' | 'desc') : undefined,
refresh: refresh,
};
}
private onPageLoaded(result: VirtualPageResult): void {
if (!result) {
return;
}
this.gridView = { data: (result.data || []).map(row => this.prepareRow(row)), total: result.total };
this.totalWithoutSearch = result.totalWithoutSearch;
this.loaded.emit({ total: result.total, totalWithoutSearch: result.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);
}
}
}