feat: add server-side pagination sort and search for centers component (#506)

- Add server-side pagination, sort and search for centers component
- Refactor code to meet current guidelines

See: #234
This commit is contained in:
punwai
2020-05-07 02:54:09 +05:30
committed by GitHub
parent f2a19708b7
commit 3136cd3b30
6 changed files with 289 additions and 122 deletions
+59 -52
View File
@@ -1,53 +1,60 @@
<div class="container m-t-40 m-b-40"> <mat-card class="container">
<div fxLayout="row" fxLayoutAlign="start center">
<mat-form-field class="filter"> <div class="search-box">
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter"> <mat-form-field>
</mat-form-field> <input matInput placeholder="Search by Name" [formControl]="name">
</mat-form-field>
<div class="mat-elevation-z8"> <mat-form-field>
<table mat-table [dataSource]="dataSource" matSort> <input matInput placeholder="Search by ExternalID" [formControl]="externalId">
</mat-form-field>
<!-- Name Column --> <mat-checkbox #showClosedCenters labelPosition="after" (change)="changeShowClosedCenters()">Show Closed Centers
<ng-container matColumnDef="name"> </mat-checkbox>
<th mat-header-cell *matHeaderCellDef mat-sort-header='name'> Name </th> </div>
<td mat-cell *matCellDef="let row"> {{row?.name}} </td> <div class="action-button" fxLayoutGap="25px">
</ng-container> <button mat-raised-button color="primary">
<fa-icon icon="download"></fa-icon>&nbsp;&nbsp;Import Center
<!-- Name Column --> </button>
<ng-container matColumnDef="accountno"> <button mat-raised-button color="primary">
<th mat-header-cell *matHeaderCellDef mat-sort-header='accountno'> Account # </th> <fa-icon icon="plus"></fa-icon>&nbsp;&nbsp;Create Center
<td mat-cell *matCellDef="let row"> {{row?.accountNo}} </td> </button>
</ng-container> </div>
<!-- Account no Column -->
<ng-container matColumnDef="externalid">
<th mat-header-cell *matHeaderCellDef mat-sort-header='externalid'> ExternalID </th>
<td mat-cell *matCellDef="let row"> {{row?.externalId}} </td>
</ng-container>
<!-- External ID Column -->
<ng-container matColumnDef="status">
<th mat-header-cell *matHeaderCellDef mat-sort-header='status'> Status </th>
<td mat-cell *matCellDef="let row"> <div [className]="row.active === true ? 'active' : 'inactive'">
<i class="fa fa-circle fa-2x"> </i>
</div> </td>
</ng-container>
<!-- Status Column -->
<ng-container matColumnDef="office">
<th mat-header-cell *matHeaderCellDef mat-sort-header='office'> Office </th>
<td mat-cell *matCellDef="let row"> {{row?.officeName}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;" [routerLink]="[ ]">
</tr>
</table>
<mat-paginator [pageSizeOptions]="[10, 25, 100]"></mat-paginator>
</div> </div>
<table mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
<td mat-cell *matCellDef="let center"> {{ center.name }} </td>
</ng-container>
<ng-container matColumnDef="accountNo">
<th mat-header-cell *matHeaderCellDef> Account # </th>
<td mat-cell *matCellDef="let center"> {{ center.accountNo }} </td>
</ng-container>
<ng-container matColumnDef="externalId">
<th mat-header-cell *matHeaderCellDef> ExternalID </th>
<td mat-cell *matCellDef="let center"> {{ center.externalId }} </td>
</ng-container>
<ng-container matColumnDef="status">
<th mat-header-cell *matHeaderCellDef> Status </th>
<td mat-cell *matCellDef="let row">
<div [ngClass]="row.active|statusLookup">
<fa-icon icon="stop"></fa-icon>
</div>
</td>
</ng-container>
<ng-container matColumnDef="officeName">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Office Name </th>
<td mat-cell *matCellDef="let center"> {{ center.officeName }} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;" [routerLink]="[ ]"></tr>
</table>
<mat-paginator [length]="dataSource?.records$ | async" [pageSize]="10" [pageSizeOptions]="[10, 25, 50, 100]" showFirstLastButtons></mat-paginator>
</mat-card>
+7 -24
View File
@@ -1,27 +1,10 @@
.container {
table { .action-button{
width: 100%; margin-left: auto;
} }
.search-button{
min-width: 30px;
margin: 4px;
.mat-form-field {
font-size: 14px;
width: 100%;
} }
}
td, th {
width: 15%;
}
.filter{
width: 50%;
}
.inactive {
color: red;
}
.active {
color: green;
}
+114 -27
View File
@@ -1,45 +1,132 @@
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; /** Angular Imports */
import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material'; import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { CentersService } from 'app/centers/centers.service'; import { MatPaginator, MatSort, MatCheckbox } from '@angular/material';
import {DataSource} from '@angular/cdk/collections'; import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs'; import { Router, ActivatedRoute } from '@angular/router';
/** rxjs Imports */
import { merge } from 'rxjs';
import { tap, startWith, map, distinctUntilChanged, debounceTime} from 'rxjs/operators';
/** Custom Services */
import { CentersService } from './centers.service';
/** Custom Data Source */
import { CentersDataSource } from './centers.datasource';
/**
* Centers component.
*/
@Component({ @Component({
selector: 'mifosx-app-centers', selector: 'mifosx-app-centers',
templateUrl: './centers.component.html', templateUrl: './centers.component.html',
styleUrls: ['./centers.component.scss'], styleUrls: ['./centers.component.scss'],
}) })
export class CentersComponent implements OnInit { export class CentersComponent implements OnInit, AfterViewInit {
private ELEMENT_DATA: any = undefined; @ViewChild('showClosedCenters') showClosedCenters: MatCheckbox;
displayedColumns = ['name', 'accountno', 'externalid', 'status', 'office'];
dataSource = new MatTableDataSource();
/** Name form control. */
name = new FormControl();
/** ExternalId form control. */
externalId = new FormControl();
/** Columns to be displayed in centers table. */
displayedColumns = ['name', 'accountNo', 'externalId', 'status', 'officeName'];
/** Data source for centers table. */
dataSource: CentersDataSource;
/** Centers filter. */
filterCentersBy = [
{
type: 'name',
value: ''
},
{
type: 'externalId',
value: ''
}
];
/** Paginator for centers table. */
@ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatPaginator) paginator: MatPaginator;
/** Sorter for centers table. */
@ViewChild(MatSort) sort: MatSort; @ViewChild(MatSort) sort: MatSort;
constructor(private centerService: CentersService) { }
constructor(private centersService: CentersService) { }
ngOnInit() { ngOnInit() {
this.centerService.getCenters() this.getCenters();
.subscribe( }
(res => {
console.log(res); /**
// console.log(res.active); * Subscribes to all search filters:
res.active = !!res.active; * Name, ExternalId
this.dataSource = new MatTableDataSource(res); * sort change and page change.
this.dataSource.paginator = this.paginator; */
this.dataSource.sort = this.sort; ngAfterViewInit() {
this.name.valueChanges
.pipe(
debounceTime(500),
distinctUntilChanged(),
tap((filterValue) => {
this.applyFilter(filterValue, 'name');
}) })
); )
.subscribe();
this.externalId.valueChanges
.pipe(
debounceTime(500),
distinctUntilChanged(),
tap((filterValue) => {
this.applyFilter(filterValue, 'externalId');
})
)
.subscribe();
this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);
merge(this.sort.sortChange, this.paginator.page)
.pipe(
tap(() => this.loadCentersPage())
)
.subscribe();
} }
/**
* Reloads page on changing show closed centers checkbox
*/
changeShowClosedCenters() {
this.loadCentersPage();
}
applyFilter(filterValue: string) { /**
filterValue = filterValue.trim(); // Remove whitespace * Loads a page of centers.
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches */
this.dataSource.filter = filterValue; loadCentersPage() {
if (this.dataSource.paginator) { if (!this.sort.direction) {
this.dataSource.paginator.firstPage(); delete this.sort.active;
} }
this.dataSource.getCenters(this.filterCentersBy, this.sort.active, this.sort.direction, this.paginator.pageIndex, this.paginator.pageSize, !this.showClosedCenters.checked);
} }
/**
* Filters data in centers table based on passed value and poperty.
* @param {string} filterValue Value to filter data.
* @param {string} property Property to filter data by.
*/
applyFilter(filterValue: string, property: string) {
this.paginator.pageIndex = 0;
const findIndex = this.filterCentersBy.findIndex(filter => filter.type === property);
this.filterCentersBy[findIndex].value = filterValue;
this.loadCentersPage();
}
/**
* Initializes the data source for centers table and loads the first page.
*/
getCenters() {
this.dataSource = new CentersDataSource(this.centersService);
this.dataSource.getCenters(this.filterCentersBy, this.sort.active, this.sort.direction, this.paginator.pageIndex, this.paginator.pageSize);
}
} }
+61
View File
@@ -0,0 +1,61 @@
/** Angular Imports */
import { CollectionViewer, DataSource } from '@angular/cdk/collections';
/** rxjs Imports */
import { Observable, BehaviorSubject } from 'rxjs';
/** Custom Services */
import { CentersService } from './centers.service';
/**
* Centers custom data source to implement server side filtering, pagination and sorting.
*/
export class CentersDataSource implements DataSource<any> {
/** centers behavior subject to represent loaded centers page. */
private centersSubject = new BehaviorSubject<any[]>([]);
/** Records subject to represent total number of filtered centers records. */
private recordsSubject = new BehaviorSubject<number>(0);
/** Records observable which can be subscribed to get the value of total number of filtered centers records. */
public records$ = this.recordsSubject.asObservable();
/**
* @param {CentersService} centersService Centers Service
*/
constructor(private centersService: CentersService) { }
/**
* Gets centers on the basis of provided parameters and emits the value.
* @param {any} filterBy Properties by which entries should be filtered.
* @param {string} orderBy Property by which entries should be sorted.
* @param {string} sortOrder Sort order: ascending or descending.
* @param {number} pageIndex Page number.
* @param {number} limit Number of entries within the page.
* @param {boolean} centerActive Specify whether to only filter active centers.
*/
getCenters(filterBy: any, orderBy: string = '', sortOrder: string = '', pageIndex: number = 0, limit: number = 10, centerActive: boolean = true) {
this.centersSubject.next([]);
this.centersService.getCenters(filterBy, orderBy, sortOrder, pageIndex * limit, limit)
.subscribe((centers: any) => {
centers.pageItems = (centerActive) ? (centers.pageItems.filter((center: any) => center.active)) : centers.pageItems;
this.recordsSubject.next(centers.totalFilteredRecords);
this.centersSubject.next(centers.pageItems);
});
}
/**
* @param {CollectionViewer} collectionViewer
*/
connect(collectionViewer: CollectionViewer): Observable<any[]> {
return this.centersSubject.asObservable();
}
/**
* @param {CollectionViewer} collectionViewer
*/
disconnect(collectionViewer: CollectionViewer): void {
this.centersSubject.complete();
this.recordsSubject.complete();
}
}
+20 -19
View File
@@ -1,28 +1,29 @@
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; /** Angular Imports */
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http'; import { DatePipe } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CoreModule } from '../core/core.module';
import { MatTableModule } from '@angular/material/table';
import { FlexLayoutModule } from '@angular/flex-layout';
/** Custom Modules */
import { CentersRoutingModule } from './centers-routing.module';
import { SharedModule } from 'app/shared/shared.module';
import { PipesModule } from '../pipes/pipes.module';
/** Custom Components */
import { CentersComponent } from './centers.component'; import { CentersComponent } from './centers.component';
import { CentersRoutingModule } from 'app/centers/centers-routing.module';
import { CentersService } from './centers.service';
/**
* Centers Module
*
* All components related to Centers should be declared here.
*/
@NgModule({ @NgModule({
imports: [ imports: [
CoreModule, SharedModule,
CommonModule,
CentersRoutingModule, CentersRoutingModule,
FormsModule, PipesModule
MatTableModule,
FlexLayoutModule
], ],
declarations: [CentersComponent], declarations: [
schemas: [ CentersComponent
CUSTOM_ELEMENTS_SCHEMA ],
] providers: [DatePipe]
}) })
export class CentersModule { } export class CentersModule { }
+35 -7
View File
@@ -1,17 +1,45 @@
/** Angular Imports */
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http'; import { HttpClient, HttpParams } from '@angular/common/http';
/** rxjs Imports */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
/**
* Clients service.
*/
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class CentersService { export class CentersService {
constructor(private http: HttpClient) { } /**
* @param {HttpClient} http Http Client to send requests.
*/
constructor(private http: HttpClient) { }
getCenters(): Observable<any> { /**
return this.http.get('/centers'); * @param {any} filterBy Properties by which entries should be filtered.
} * @param {string} orderBy Property by which entries should be sorted.
* @param {string} sortOrder Sort order: ascending or descending.
* @param {number} offset Page offset.
* @param {number} limit Number of entries within the page.
* @returns {Observable<any>} Centers.
*/
getCenters(filterBy: any, orderBy: string, sortOrder: string, offset: number, limit: number): Observable<any> {
let httpParams = new HttpParams()
.set('offset', offset.toString())
.set('limit', limit.toString())
.set('sortOrder', sortOrder)
.set('orderBy', orderBy)
.set('paged', 'true');
// filterBy: name, externalId
filterBy.forEach(function (filter: any) {
if (filter.value) {
console.log(filter.value);
httpParams = httpParams.set(filter.type, filter.value);
}
});
return this.http.get('/centers', { params: httpParams });
}
} }