78 lines
2.5 KiB
TypeScript
78 lines
2.5 KiB
TypeScript
import { DataSource } from '@angular/cdk/collections';
|
|
import { EventEmitter } from '@angular/core';
|
|
import { MatPaginator, PageEvent } from '@angular/material/paginator';
|
|
import { MatSort, Sort } from '@angular/material/sort';
|
|
import { merge, Observable, of as observableOf } from 'rxjs';
|
|
import { map } from 'rxjs/operators';
|
|
|
|
import { ProductLedgerItem } from './product-ledger-item';
|
|
|
|
/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
|
|
const compare = (a: string | number, b: string | number, isAsc: boolean) => (a < b ? -1 : 1) * (isAsc ? 1 : -1);
|
|
export class ProductLedgerDataSource extends DataSource<ProductLedgerItem> {
|
|
constructor(
|
|
public data: ProductLedgerItem[],
|
|
private paginator?: MatPaginator,
|
|
private sort?: MatSort,
|
|
) {
|
|
super();
|
|
}
|
|
|
|
connect(): Observable<ProductLedgerItem[]> {
|
|
const dataMutations: (EventEmitter<PageEvent> | EventEmitter<Sort>)[] = [];
|
|
if (this.paginator) {
|
|
dataMutations.push((this.paginator as MatPaginator).page);
|
|
}
|
|
if (this.sort) {
|
|
dataMutations.push((this.sort as MatSort).sortChange);
|
|
}
|
|
|
|
// Set the paginators length
|
|
if (this.paginator) {
|
|
this.paginator.length = this.data.length;
|
|
}
|
|
const a = merge(observableOf(this.data), ...dataMutations).pipe(
|
|
map(() => this.getPagedData(this.getSortedData([...this.data]))),
|
|
);
|
|
return a;
|
|
}
|
|
|
|
disconnect() {}
|
|
|
|
private getPagedData(data: ProductLedgerItem[]) {
|
|
if (this.paginator === undefined) {
|
|
return data;
|
|
}
|
|
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
|
|
return data.splice(startIndex, this.paginator.pageSize);
|
|
}
|
|
|
|
private getSortedData(data: ProductLedgerItem[]) {
|
|
if (this.sort === undefined) {
|
|
return data;
|
|
}
|
|
if (!this.sort.active || this.sort.direction === '') {
|
|
return data;
|
|
}
|
|
|
|
const sort = this.sort as MatSort;
|
|
return data.sort((a, b) => {
|
|
const isAsc = sort.direction === 'asc';
|
|
switch (sort.active) {
|
|
case 'date':
|
|
return compare(a.date, b.date, isAsc);
|
|
case 'debitQuantity':
|
|
return compare(Number(a.debitQuantity), Number(b.debitQuantity), isAsc);
|
|
case 'debitAmount':
|
|
return compare(Number(a.debitAmount), Number(b.debitAmount), isAsc);
|
|
case 'creditQuantity':
|
|
return compare(Number(a.creditQuantity), Number(b.creditQuantity), isAsc);
|
|
case 'creditAmount':
|
|
return compare(Number(a.creditAmount), Number(b.creditAmount), isAsc);
|
|
default:
|
|
return 0;
|
|
}
|
|
});
|
|
}
|
|
}
|