Table Sort Order Done

This commit is contained in:
Amritanshu 2019-06-16 21:08:18 +05:30
parent bcb158b837
commit 32500665b5
8 changed files with 184 additions and 137 deletions

View File

@ -7,41 +7,76 @@ from pyramid.view import view_config
from barker.models import FoodTable, Overview
@view_config(request_method='POST', route_name='v1_tables_new', renderer='json', permission='Tables', trans=True)
@view_config(
request_method="POST",
route_name="v1_tables_new",
renderer="json",
permission="Tables",
trans=True,
)
def save(request):
json = request.json_body
item = FoodTable(json['name'], json['location'], json['isActive'], json['sortOrder'])
item = FoodTable(
json["name"], json["location"], json["isActive"], json["sortOrder"]
)
request.dbsession.add(item)
transaction.commit()
item = request.dbsession.query(FoodTable).filter(FoodTable.id == item.id).first()
return food_table_info(item)
@view_config(request_method='PUT', route_name='v1_tables_id', renderer='json', permission='Tables', trans=True)
@view_config(
request_method="PUT",
route_name="v1_tables_id",
renderer="json",
permission="Tables",
trans=True,
)
def update(request):
json = request.json_body
item = request.dbsession.query(FoodTable).filter(FoodTable.id == uuid.UUID(request.matchdict['id'])).first()
item.name = json['name']
item.location = json['location']
item.is_active = json['isActive']
item.sort_order = json['sortOrder']
item = (
request.dbsession.query(FoodTable)
.filter(FoodTable.id == uuid.UUID(request.matchdict["id"]))
.first()
)
item.name = json["name"]
item.location = json["location"]
item.is_active = json["isActive"]
item.sort_order = json["sortOrder"]
transaction.commit()
item = request.dbsession.query(FoodTable).filter(FoodTable.id == item.id).first()
return food_table_info(item)
@view_config(request_method='DELETE', route_name='v1_tables_id', renderer='json', permission='Tables', trans=True)
@view_config(
request_method="DELETE",
route_name="v1_tables_id",
renderer="json",
permission="Tables",
trans=True,
)
def delete(request):
item = request.dbsession.query(FoodTable).filter(FoodTable.id == uuid.UUID(request.matchdict['id'])).first()
item = (
request.dbsession.query(FoodTable)
.filter(FoodTable.id == uuid.UUID(request.matchdict["id"]))
.first()
)
request.dbsession.delete(item)
transaction.commit()
return {}
@view_config(request_method='GET', route_name='v1_tables_id', renderer='json', permission='Authenticated')
@view_config(
request_method="GET",
route_name="v1_tables_id",
renderer="json",
permission="Authenticated",
)
def show_id(request):
id_ = request.matchdict['id']
p = re.compile('^[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}$')
id_ = request.matchdict["id"]
p = re.compile(
"^[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}$"
)
if p.match(id_):
id_ = uuid.UUID(id_)
item = request.dbsession.query(FoodTable).filter(FoodTable.id == id_).first()
@ -50,28 +85,39 @@ def show_id(request):
return food_table_info(item)
@view_config(request_method='GET', route_name='v1_tables_new', renderer='json', request_param='v')
@view_config(
request_method="GET", route_name="v1_tables_new", renderer="json", request_param="v"
)
def show_voucher(request):
voucher_id = request.GET['v']
voucher = request.dbsession.query(Overview).filter(Overview.voucher_id == voucher_id).first()
voucher_id = request.GET["v"]
voucher = (
request.dbsession.query(Overview)
.filter(Overview.voucher_id == voucher_id)
.first()
)
if voucher is not None:
return food_table_info(voucher.food_table)
return {}
@view_config(request_method='GET', route_name='v1_tables_new', renderer='json', permission='Tables')
@view_config(
request_method="GET",
route_name="v1_tables_new",
renderer="json",
permission="Tables",
)
def show_blank(request):
return {
'name': "",
'isActive': True,
'location': "",
'sortOrder': 0
}
return {"name": "", "isActive": True, "location": "", "sortOrder": 0}
@view_config(request_method='GET', route_name='v1_tables_list', renderer='json', permission='Authenticated')
@view_config(
request_method="GET",
route_name="v1_tables_list",
renderer="json",
permission="Authenticated",
)
def show_list(request):
active = request.GET.get('a', None)
active = request.GET.get("a", None)
list_ = request.dbsession.query(FoodTable)
if active is not None:
list_ = list_.filter(FoodTable.is_active == active)
@ -79,39 +125,42 @@ def show_list(request):
food_tables = []
for item in list_:
food_tables.append({
'id': item.id,
'name': item.name,
'location': item.location,
'isActive': item.is_active,
'sortOrder': item.sort_order,
'status': '' if item.status is None else item.status.status,
'voucherId': None if item.status is None else item.status.voucher_id
})
food_tables.append(
{
"id": item.id,
"name": item.name,
"location": item.location,
"isActive": item.is_active,
"sortOrder": item.sort_order,
"status": "" if item.status is None else item.status.status,
"voucherId": None if item.status is None else item.status.voucher_id,
}
)
return food_tables
@view_config(request_method='PUT', route_name='v1_tables_list', renderer='json', permission='Tables')
@view_config(
request_method="POST",
route_name="v1_tables_list",
renderer="json",
permission="Tables",
)
def sort_order(request):
json = request.json_body
for index, item in enumerate(json):
request.dbsession.query(
FoodTable
).filter(
FoodTable.id == uuid.UUID(item['FoodTableID'])
).update(
{FoodTable.sort_order: index}
)
request.dbsession.query(FoodTable).filter(
FoodTable.id == uuid.UUID(item["id"])
).update({FoodTable.sort_order: index})
return True
def food_table_info(item):
return {
'id': item.id,
'name': item.name,
'location': item.location,
'isActive': item.is_active,
'status': '' if item.status is None else item.status.status,
'sortOrder': item.sort_order,
'voucherId': None if item.status is None else item.status.voucher_id
"id": item.id,
"name": item.name,
"location": item.location,
"isActive": item.is_active,
"status": "" if item.status is None else item.status.status,
"sortOrder": item.sort_order,
"voucherId": None if item.status is None else item.status.voucher_id,
}

View File

@ -5,6 +5,7 @@ import { tap } from "rxjs/operators";
export class ProductGroupListDataSource extends DataSource<ProductGroup> {
private data: ProductGroup[];
constructor(private readonly dataObs: Observable<ProductGroup[]>) {
super();
this.dataObs = dataObs.pipe(

View File

@ -46,7 +46,6 @@ export class ProductGroupListComponent implements OnInit {
.subscribe(
(result) => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/product-groups');
},
(error) => {
this.toaster.show('Danger', error.error);

View File

@ -1,59 +1,22 @@
import {DataSource} from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import {map} from 'rxjs/operators';
import {merge, Observable, of as observableOf} from 'rxjs';
import {Table} from '../../core/table';
import { DataSource } from '@angular/cdk/collections';
import { tap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { Table } from '../../core/table';
export class TableListDataSource extends DataSource<Table> {
private data: Table[];
constructor(private paginator: MatPaginator, private sort: MatSort, public data: Table[]) {
constructor(private readonly dataObs: Observable<Table[]>) {
super();
this.dataObs = dataObs.pipe(
tap(x => this.data = x)
);
}
connect(): Observable<Table[]> {
const dataMutations = [
observableOf(this.data),
this.paginator.page,
this.sort.sortChange
];
// Set the paginators length
this.paginator.length = this.data.length;
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data]));
}));
return this.dataObs;
}
disconnect() {
}
private getPagedData(data: Table[]) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
private getSortedData(data: Table[]) {
if (!this.sort.active || this.sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = this.sort.direction === 'asc';
switch (this.sort.active) {
case 'name':
return compare(a.name, b.name, isAsc);
case 'id':
return compare(+a.id, +b.id, isAsc);
default:
return 0;
}
});
}
}
/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a, b, isAsc) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

View File

@ -1,41 +1,37 @@
<mat-card>
<mat-card-title-group>
<mat-card-title>Tables</mat-card-title>
<button mat-button (click)="updateSortOrder()">
Update Order
</button>
<a mat-button [routerLink]="['/tables', 'new']">
<mat-icon>add_box</mat-icon>
Add
</a>
</mat-card-title-group>
<mat-card-content>
<mat-table #table [dataSource]="dataSource" matSort aria-label="Elements">
<mat-table #table cdkDropList [dataSource]="dataSource" [cdkDropListData]="dataSource" aria-label="Elements" (cdkDropListDropped)="dropTable($event)">
<!-- Name Column -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef mat-sort-header>Name</mat-header-cell>
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let row"><a [routerLink]="['/tables', row.id]">{{row.name}}</a></mat-cell>
</ng-container>
<!-- Location Column -->
<ng-container matColumnDef="location">
<mat-header-cell *matHeaderCellDef mat-sort-header>Location</mat-header-cell>
<mat-header-cell *matHeaderCellDef>Location</mat-header-cell>
<mat-cell *matCellDef="let row">{{row.location}}</mat-cell>
</ng-container>
<!-- Name Column -->
<!-- Is Active Column -->
<ng-container matColumnDef="isActive">
<mat-header-cell *matHeaderCellDef mat-sort-header>Is Active?</mat-header-cell>
<mat-header-cell *matHeaderCellDef>Is Active?</mat-header-cell>
<mat-cell *matCellDef="let row">{{row.isActive}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
<mat-row *matRowDef="let row; columns: displayedColumns;" cdkDrag [cdkDragData]="row"></mat-row>
</mat-table>
<mat-paginator #paginator
[length]="dataSource.data.length"
[pageIndex]="0"
[pageSize]="50"
[pageSizeOptions]="[25, 50, 100, 250]">
</mat-paginator>
</mat-card-content>
</mat-card>

View File

@ -1,9 +1,13 @@
import {Component, OnInit, ViewChild} from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import {TableListDataSource} from './table-list-datasource';
import {Table} from '../../core/table';
import {ActivatedRoute} from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { TableListDataSource } from './table-list-datasource';
import { Table } from '../../core/table';
import { ActivatedRoute, Router } from '@angular/router';
import { MatTable } from "@angular/material";
import { ProductGroup } from "../../core/product-group";
import { BehaviorSubject } from "rxjs";
import { CdkDragDrop, moveItemInArray } from "@angular/cdk/drag-drop";
import { ToasterService } from "../../core/toaster.service";
import { TableService } from "../table.service";
@Component({
selector: 'app-table-list',
@ -11,21 +15,48 @@ import {ActivatedRoute} from '@angular/router';
styleUrls: ['./table-list.component.css']
})
export class TableListComponent implements OnInit {
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
@ViewChild(MatSort, { static: true }) sort: MatSort;
@ViewChild('table', { static: true }) table: MatTable<ProductGroup>;
dataSource: TableListDataSource;
list: Table[];
data: BehaviorSubject<Table[]>;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['name', 'isActive'];
displayedColumns = ['name', 'location', 'isActive'];
constructor(private route: ActivatedRoute) {
constructor(
private route: ActivatedRoute,
private router: Router,
private toaster: ToasterService,
private ser: TableService
) {
this.data = new BehaviorSubject([]);
this.data.subscribe((data: Table[]) => {
this.list = data;
})
}
ngOnInit() {
this.route.data
.subscribe((data: { list: Table[] }) => {
this.list = data.list;
this.data.next(data.list);
});
this.dataSource = new TableListDataSource(this.paginator, this.sort, this.list);
this.dataSource = new TableListDataSource(this.data);
}
updateSortOrder() {
this.ser.updateSortOrder(this.list)
.subscribe(
(result) => {
this.toaster.show('Success', '');
},
(error) => {
this.toaster.show('Danger', error.error);
}
);
}
dropTable(event: CdkDragDrop<ProductGroup[]>) {
const prevIndex = this.list.indexOf(event.item.data);
moveItemInArray(this.list, prevIndex, event.currentIndex);
this.data.next(this.list);
}
}

View File

@ -1,9 +1,9 @@
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {ErrorLoggerService} from '../core/error-logger.service';
import {catchError} from 'rxjs/operators';
import {Observable} from 'rxjs/internal/Observable';
import {Table} from '../core/table';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { ErrorLoggerService } from '../core/error-logger.service';
import { catchError } from 'rxjs/operators';
import { Observable } from 'rxjs/internal/Observable';
import { Table } from '../core/table';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
@ -48,6 +48,13 @@ export class TableService {
);
}
updateSortOrder(list: Table[]): Observable<boolean> {
return <Observable<boolean>>this.http.post<Table[]>(url, list, httpOptions)
.pipe(
catchError(this.log.handleError(serviceName, 'updateSortOrder'))
);
}
saveOrUpdate(tables: Table): Observable<Table> {
if (!tables.id) {
return this.save(tables);

View File

@ -1,9 +1,6 @@
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {TableListComponent} from './table-list/table-list.component';
import {TableDetailComponent} from './table-detail/table-detail.component';
import {TableRoutingModule} from './tables-routing.module';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
@ -13,14 +10,18 @@ import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import {CdkTableModule} from '@angular/cdk/table';
import {ReactiveFormsModule} from '@angular/forms';
import {FlexLayoutModule} from '@angular/flex-layout';
import { CdkTableModule } from '@angular/cdk/table';
import { DragDropModule } from "@angular/cdk/drag-drop";
import { FlexLayoutModule } from '@angular/flex-layout';
import { TableListComponent } from './table-list/table-list.component';
import { TableDetailComponent } from './table-detail/table-detail.component';
import { TableRoutingModule } from './tables-routing.module';
@NgModule({
imports: [
CommonModule,
CdkTableModule,
DragDropModule,
FlexLayoutModule,
MatButtonModule,
MatCardModule,