HRM-10/HRM.UI/ClientApp/src/app/custom-components/virtual-grid/virtual-grid.component.ts
2026-11-09 16:39:51 +06:00

266 lines
9.5 KiB
TypeScript

import {
ChangeDetectionStrategy, Component, EventEmitter, Input, 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 {
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 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<VirtualGridLoadedEvent>();
started = false;
gridView: GridDataResult = { data: [], total: 0 };
totalWithoutSearch = 0;
gridLoading = false;
skip = 0;
sort: SortDescriptor[] = [];
searchText = '';
appliedSearch = '';
exporting = false;
private filters: { [name: string]: string } = {};
private firstLoad = false;
private totalsPending = 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(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());
}
/**
* The server builds the .xlsx (every row matching the search, in the grid's sort) and the browser
* only downloads it, so a long list never has to be loaded or processed in the page.
*/
exportExcel(): void {
if (!this.started || this.gridView.total === 0 || this.exporting) {
return;
}
this.setExporting(true);
const request: VirtualPageRequest = { ...this.buildRequest(0, 0, false), exportExcel: true };
this.apiService.httpDownloadFile(this.url, request).pipe(
finalize(() => this.setExporting(false))
).subscribe(
(file: Blob) => saveAs(file, this.exportFileName),
(err) => this.showDownloadError(err, 'Failed to export to Excel.')
);
}
/** 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;
}
}
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', title: c.title, width: this.columnWidth(c) })),
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;
}
/** A failed download returns its error message as a Blob; read it before showing it. */
private showDownloadError(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));
}
}
private showError(message: string): void {
if (this.notificationService) {
this.notificationService.showError(message);
} else {
console.error(message);
}
}
}