This commit is contained in:
Amritanshu
2019-06-15 23:09:43 +05:30
parent 3dcf1c4c42
commit 459ab244ff
70 changed files with 2140 additions and 103 deletions

View File

@ -0,0 +1,77 @@
<div fxLayout="row" fxFlex="50%" fxLayoutAlign="space-around center" class="example-card">
<mat-card fxFlex>
<mat-card-title-group>
<mat-card-title>Product</mat-card-title>
</mat-card-title-group>
<mat-card-content>
<form [formGroup]="form" fxLayout="column">
<div fxLayout="row" fxLayoutAlign="space-around start" fxLayout.lt-md="column" fxLayoutGap="20px"
fxLayoutGap.lt-md="0px">
<mat-form-field fxFlex>
<mat-label>Code</mat-label>
<input matInput placeholder="Code" formControlName="code">
</mat-form-field>
</div>
<div fxLayout="row" fxLayoutAlign="space-around start" fxLayout.lt-md="column" fxLayoutGap="20px"
fxLayoutGap.lt-md="0px">
<mat-form-field fxFlex="75">
<mat-label>Name</mat-label>
<input matInput #nameElement placeholder="Name" formControlName="name">
</mat-form-field>
<mat-form-field fxFlex="25">
<mat-label>Units</mat-label>
<input matInput placeholder="Units" formControlName="units">
</mat-form-field>
</div>
<div fxLayout="row" fxLayoutAlign="space-around start" fxLayout.lt-md="column" fxLayoutGap="20px"
fxLayoutGap.lt-md="0px">
<mat-form-field fxFlex>
<mat-label>Fraction</mat-label>
<input matInput type="number" placeholder="Fraction" formControlName="fraction">
</mat-form-field>
<mat-form-field cdk-overlay-origin="">
<mat-label>Fraction Units</mat-label>
<input matInput placeholder="Fraction Units" formControlName="fractionUnits">
</mat-form-field>
<mat-form-field cdk-overlay-origin="">
<mat-label>Yield</mat-label>
<input matInput type="number" placeholder="Tield" formControlName="productYield">
</mat-form-field>
</div>
<div fxLayout="row" fxLayoutAlign="space-around start" fxLayout.lt-md="column" fxLayoutGap="20px"
fxLayoutGap.lt-md="0px">
<mat-form-field fxFlex>
<mat-label>{{item.isPurchased ? 'Purchase Price' : 'Cost Price' }}</mat-label>
<input matInput type="number" placeholder="{{item.isPurchased ? 'Purchase Price' : 'Cost Price' }}"
formControlName="price">
</mat-form-field>
<mat-form-field fxFlex [hidden]="!item.isSold">
<mat-label>Sale Price</mat-label>
<input matInput type="number" placeholder="Sale Price" formControlName="salePrice">
</mat-form-field>
</div>
<div fxLayout="row" fxLayoutAlign="space-around start" fxLayout.lt-md="column" fxLayoutGap="20px"
fxLayoutGap.lt-md="0px">
<mat-checkbox formControlName="isPurchased">Is Purchased?</mat-checkbox>
<mat-checkbox formControlName="isSold">Is Sold?</mat-checkbox>
<mat-checkbox formControlName="isActive">Is Active?</mat-checkbox>
</div>
<div fxLayout="row" fxLayoutAlign="space-around start" fxLayout.lt-md="column" fxLayoutGap="20px"
fxLayoutGap.lt-md="0px">
<mat-form-field fxFlex>
<mat-label>Product Type</mat-label>
<mat-select placeholder="Product Group" formControlName="productGroup">
<mat-option *ngFor="let pg of productGroups" [value]="pg.id">
{{ pg.name }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</form>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" (click)="save()">Save</button>
<button mat-raised-button color="warn" (click)="confirmDelete()" *ngIf="!!item.id">Delete</button>
</mat-card-actions>
</mat-card>
</div>

View File

@ -0,0 +1,25 @@
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {ProductDetailComponent} from './product-detail.component';
describe('ProductDetailComponent', () => {
let component: ProductDetailComponent;
let fixture: ComponentFixture<ProductDetailComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ProductDetailComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProductDetailComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,132 @@
import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ToasterService} from '../../core/toaster.service';
import {ActivatedRoute, Router} from '@angular/router';
import {ProductService} from '../product.service';
import {Product} from '../../core/product';
import {ProductGroup} from '../../core/product-group';
import {ConfirmDialogComponent} from '../../shared/confirm-dialog/confirm-dialog.component';
import { MatDialog } from '@angular/material/dialog';
import {FormBuilder, FormGroup} from '@angular/forms';
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html',
styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit, AfterViewInit {
@ViewChild('nameElement', { static: true }) nameElement: ElementRef;
form: FormGroup;
productGroups: ProductGroup[];
item: Product;
constructor(
private route: ActivatedRoute,
private router: Router,
private dialog: MatDialog,
private fb: FormBuilder,
private toaster: ToasterService,
private ser: ProductService
) {
this.createForm();
}
createForm() {
this.form = this.fb.group({
code: {value: '', disabled: true},
name: '',
units: '',
fraction: '',
fractionUnits: '',
productYield: '',
price: '',
salePrice: '',
isPurchased: '',
isSold: '',
isActive: '',
productGroup: ''
});
}
ngOnInit() {
this.route.data
.subscribe((data: { item: Product, productGroups: ProductGroup[] }) => {
this.productGroups = data.productGroups;
this.showItem(data.item);
});
}
showItem(item: Product) {
this.item = item;
this.form.setValue({
code: this.item.code || '(Auto)',
name: this.item.name || '',
units: this.item.units || '',
productGroup: this.item.tax.id ? this.item.tax.id : '',
tax: this.item.productGroup.id ? this.item.productGroup.id : '',
price: this.item.price || '',
hadHappyHour: this.item.hasHappyHour,
isNotAvailable: this.item.isNotAvailable,
quantity: this.item.quantity || '',
isActive: this.item.isActive,
});
}
ngAfterViewInit() {
setTimeout(() => {
this.nameElement.nativeElement.focus();
}, 0);
}
save() {
this.ser.saveOrUpdate(this.getItem())
.subscribe(
(result) => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/products');
},
(error) => {
this.toaster.show('Danger', error.error);
}
);
}
delete() {
this.ser.delete(this.item.id)
.subscribe(
(result) => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/products');
},
(error) => {
this.toaster.show('Danger', error.error);
}
);
}
confirmDelete(): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px',
data: {title: 'Delete Product?', content: 'Are you sure? This cannot be undone.'}
});
dialogRef.afterClosed().subscribe((result: boolean) => {
if (result) {
this.delete();
}
});
}
getItem(): Product {
const formModel = this.form.value;
this.item.name = formModel.name;
this.item.units = formModel.units;
this.item.productGroup.id = formModel.productGroup;
this.item.tax.id = formModel.tax;
this.item.price = +formModel.price;
this.item.hasHappyHour = formModel.hasHappyHour;
this.item.isNotAvailable = formModel.isNotAvailable;
this.item.quantity = +formModel.quantity;
this.item.isActive = formModel.isActive;
return this.item;
}
}

View File

@ -0,0 +1,15 @@
import {inject, TestBed} from '@angular/core/testing';
import {ProductListResolverService} from './product-list-resolver.service';
describe('ProductListResolverService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ProductListResolverService]
});
});
it('should be created', inject([ProductListResolverService], (service: ProductListResolverService) => {
expect(service).toBeTruthy();
}));
});

View File

@ -0,0 +1,18 @@
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router';
import {Product} from '../core/product';
import {Observable} from 'rxjs/internal/Observable';
import {ProductService} from './product.service';
@Injectable({
providedIn: 'root'
})
export class ProductListResolver implements Resolve<Product[]> {
constructor(private ser: ProductService) {
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Product[]> {
return this.ser.list();
}
}

View File

@ -0,0 +1,55 @@
import {DataSource} from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import {map, tap} from 'rxjs/operators';
import {merge, Observable, of as observableOf} from 'rxjs';
import {Product} from '../../core/product';
export class ProductListDataSource extends DataSource<Product> {
private dataObservable: Observable<Product[]>;
private filterValue: string;
constructor(private paginator: MatPaginator, private filter: Observable<string>, public data: Product[]) {
super();
this.filter = filter.pipe(
tap(x => this.filterValue = x)
);
}
connect(): Observable<Product[]> {
this.dataObservable = observableOf(this.data);
const dataMutations = [
this.dataObservable,
this.filter,
this.paginator.page
];
return merge(...dataMutations).pipe(
map((x: any) => {
return this.getPagedData(this.getFilteredData([...this.data]));
}),
tap((x: Product[]) => this.paginator.length = x.length)
);
}
disconnect() {
}
private getFilteredData(data: Product[]): Product[] {
const filter = (this.filterValue === undefined) ? '' : this.filterValue;
return filter.split(' ').reduce((p: Product[], c: string) => {
return p.filter(x => {
const productString = (
x.code + ' ' + x.name + ' ' + x.units + ' ' + x.productGroup + (x.isActive ? 'active' : 'deactive')
).toLowerCase();
return productString.indexOf(c) !== -1;
}
);
}, Object.assign([], data));
}
private getPagedData(data: Product[]) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
}

View File

@ -0,0 +1,97 @@
<mat-card>
<mat-card-title-group>
<mat-card-title>Products</mat-card-title>
<button mat-button mat-icon-button *ngIf="dataSource.data.length" (click)="exportCsv()">
<mat-icon>save_alt</mat-icon>
</button>
<a mat-button [routerLink]="['/products', 'new']">
<mat-icon>add_box</mat-icon>
Add
</a>
</mat-card-title-group>
<mat-card-content>
<form [formGroup]="form" fxLayout="column">
<div fxLayout="row" fxLayoutAlign="space-around start" fxLayout.lt-md="column" fxLayoutGap="20px"
fxLayoutGap.lt-md="0px">
<mat-form-field fxFlex>
<mat-label>Product Type</mat-label>
<mat-select placeholder="Product Group" formControlName="productGroup" (selectionChange)="filterOn(pg.id)">
<mat-option>--</mat-option>
<mat-option *ngFor="let pg of productGroups" [value]="pg.id">
{{ pg.name }}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</form>
<mat-table #table [dataSource]="dataSource" matSort aria-label="Elements">
<!-- Name Column -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let row"><a [routerLink]="['/products', row.id]">{{row.name}} ({{row.units}})</a></mat-cell>
</ng-container>
<!-- Price Column -->
<ng-container matColumnDef="price">
<mat-header-cell *matHeaderCellDef>Price</mat-header-cell>
<mat-cell *matCellDef="let row">{{row.price | currency:'INR'}}</mat-cell>
</ng-container>
<!-- Product Group Column -->
<ng-container matColumnDef="productGroup">
<mat-header-cell *matHeaderCellDef>Product Group</mat-header-cell>
<mat-cell *matCellDef="let row">{{row.productGroup}}</mat-cell>
</ng-container>
<!-- Tax Column -->
<ng-container matColumnDef="tax">
<mat-header-cell *matHeaderCellDef>Tax</mat-header-cell>
<mat-cell *matCellDef="let row">{{row.tax}}</mat-cell>
</ng-container>
<!-- Info Column -->
<ng-container matColumnDef="info">
<mat-header-cell *matHeaderCellDef>Details</mat-header-cell>
<mat-cell *matCellDef="let row">
<div layout="row">
<div flex>
<mat-icon>
{{ row.hasHappyHour ? "sentiment_satisfied_alt" : "sentiment_dissatisfied" }}
</mat-icon>
<b> {{ row.hasHappyHour ? "Happy Hour" : "Regular" }}</b>
</div>
<div flex>
<mat-icon>
{{ row.isNotAvailable ? "pause" : "play_arrow" }}
</mat-icon>
<b> {{ row.isNotAvailable ? "Not Available" : "Available" }}</b>
</div>
<div flex>
<mat-icon>
{{ row.isActive ? "visibility" : "visibility_off" }}
</mat-icon>
<b> {{ row.isActive ? "Active" : "Deactivated" }}</b>
</div>
</div>
</mat-cell>
</ng-container>
<!-- Yield Column -->
<ng-container matColumnDef="quantity">
<mat-header-cell *matHeaderCellDef>Quantity</mat-header-cell>
<mat-cell *matCellDef="let row">{{row.quantity | currency:'INR'}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator #paginator
[length]="dataSource.data.length"
[pageIndex]="0"
[pageSize]="5000"
[pageSizeOptions]="[25, 50, 100, 250, 5000]">
</mat-paginator>
</mat-card-content>
</mat-card>

View File

@ -0,0 +1,23 @@
import {ComponentFixture, fakeAsync, TestBed} from '@angular/core/testing';
import {ProductListComponent} from './product-list.component';
describe('ProductListComponent', () => {
let component: ProductListComponent;
let fixture: ComponentFixture<ProductListComponent>;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
declarations: [ProductListComponent]
})
.compileComponents();
fixture = TestBed.createComponent(ProductListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should compile', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,59 @@
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { ProductListDataSource } from './product-list-datasource';
import { Product } from '../../core/product';
import { ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Observable } from 'rxjs';
import { ToCsvService } from "../../shared/to-csv.service";
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
dataSource: ProductListDataSource;
filter: Observable<string> = new Observable<string>();
form: FormGroup;
list: Product[];
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns: string[] = ['name', 'price', 'productGroup', 'tax', 'info', 'quantity'];
constructor(private route: ActivatedRoute, private fb: FormBuilder, private toCsv: ToCsvService) {
this.form = this.fb.group({
productGroup: ''
});
}
filterOn(val: string) {
console.log(val);
}
ngOnInit() {
this.route.data
.subscribe((data: { list: Product[] }) => {
this.list = data.list;
});
this.dataSource = new ProductListDataSource(this.paginator, this.filter, this.list);
}
exportCsv() {
const headers = {
Code: 'code',
Name: 'name',
Units: 'units',
Price: 'price',
ProductGroup: 'productGroup',
Tax: 'tax'
};
const csvData = new Blob([this.toCsv.toCsv(headers, this.dataSource.data)], {type: 'text/csv;charset=utf-8;'});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(csvData);
link.setAttribute('download', 'products.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}

View File

@ -0,0 +1,15 @@
import {inject, TestBed} from '@angular/core/testing';
import {ProductResolverService} from './product-resolver.service';
describe('ProductResolverService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ProductDetailResolverService]
});
});
it('should be created', inject([ProductDetailResolverService], (service: ProductDetailResolverService) => {
expect(service).toBeTruthy();
}));
});

View File

@ -0,0 +1,19 @@
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot} from '@angular/router';
import {ProductService} from './product.service';
import {Product} from '../core/product';
import {Observable} from 'rxjs/internal/Observable';
@Injectable({
providedIn: 'root'
})
export class ProductResolver implements Resolve<Product> {
constructor(private ser: ProductService, private router: Router) {
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Product> {
const id = route.paramMap.get('id');
return this.ser.get(id);
}
}

View File

@ -0,0 +1,13 @@
import {ProductRoutingModule} from './product-routing.module';
describe('ProductRoutingModule', () => {
let productRoutingModule: ProductRoutingModule;
beforeEach(() => {
productRoutingModule = new ProductRoutingModule();
});
it('should create an instance', () => {
expect(productRoutingModule).toBeTruthy();
});
});

View File

@ -0,0 +1,66 @@
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule, Routes} from '@angular/router';
import {ProductListResolver} from './product-list-resolver.service';
import {ProductResolver} from './product-resolver.service';
import {ProductDetailComponent} from './product-detail/product-detail.component';
import {ProductListComponent} from './product-list/product-list.component';
import {AuthGuard} from '../auth/auth-guard.service';
import {ProductGroupListResolver} from '../product-group/product-group-list-resolver.service';
const productRoutes: Routes = [
{
path: '',
component: ProductListComponent,
canActivate: [AuthGuard],
data: {
permission: 'Products'
},
resolve: {
list: ProductListResolver
}
},
{
path: 'new',
component: ProductDetailComponent,
canActivate: [AuthGuard],
data: {
permission: 'Products'
},
resolve: {
item: ProductResolver,
productGroups: ProductGroupListResolver
}
},
{
path: ':id',
component: ProductDetailComponent,
canActivate: [AuthGuard],
data: {
permission: 'Products'
},
resolve: {
item: ProductResolver,
productGroups: ProductGroupListResolver
}
}
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(productRoutes)
],
exports: [
RouterModule
],
providers: [
ProductListResolver,
ProductResolver
]
})
export class ProductRoutingModule {
}

View File

@ -0,0 +1,13 @@
import {ProductModule} from './product.module';
describe('ProductModule', () => {
let productModule: ProductModule;
beforeEach(() => {
productModule = new ProductModule();
});
it('should create an instance', () => {
expect(productModule).toBeTruthy();
});
});

View File

@ -0,0 +1,47 @@
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {ProductListComponent} from './product-list/product-list.component';
import {ProductDetailComponent} from './product-detail/product-detail.component';
import {ProductRoutingModule} from './product-routing.module';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatOptionModule } from '@angular/material/core';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
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';
@NgModule({
imports: [
CommonModule,
CdkTableModule,
FlexLayoutModule,
MatTableModule,
MatPaginatorModule,
MatSortModule,
MatCardModule,
MatProgressSpinnerModule,
MatInputModule,
MatButtonModule,
MatIconModule,
MatOptionModule,
MatSelectModule,
MatCheckboxModule,
ReactiveFormsModule,
ProductRoutingModule
],
declarations: [
ProductListComponent,
ProductDetailComponent
]
})
export class ProductModule {
}

View File

@ -0,0 +1,15 @@
import {inject, TestBed} from '@angular/core/testing';
import {ProductService} from './product.service';
describe('ProductService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ProductService]
});
});
it('should be created', inject([ProductService], (service: ProductService) => {
expect(service).toBeTruthy();
}));
});

View File

@ -0,0 +1,81 @@
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/internal/Observable';
import {catchError} from 'rxjs/operators';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {Product} from '../core/product';
import {ErrorLoggerService} from '../core/error-logger.service';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
const url = '/v1/products';
const serviceName = 'ProductService';
@Injectable({providedIn: 'root'})
export class ProductService {
constructor(private http: HttpClient, private log: ErrorLoggerService) {
}
get(id: string): Observable<Product> {
const getUrl: string = (id === null) ? `${url}/new` : `${url}/${id}`;
return <Observable<Product>>this.http.get<Product>(getUrl)
.pipe(
catchError(this.log.handleError(serviceName, `get id=${id}`))
);
}
list(): Observable<Product[]> {
const options = {params: new HttpParams().set('l', '')};
return <Observable<Product[]>>this.http.get<Product[]>(url, options)
.pipe(
catchError(this.log.handleError(serviceName, 'getList'))
);
}
save(product: Product): Observable<Product> {
return <Observable<Product>>this.http.post<Product>(`${url}/new`, product, httpOptions)
.pipe(
catchError(this.log.handleError(serviceName, 'save'))
);
}
update(product: Product): Observable<Product> {
return <Observable<Product>>this.http.put<Product>(`${url}/${product.id}`, product, httpOptions)
.pipe(
catchError(this.log.handleError(serviceName, 'update'))
);
}
saveOrUpdate(product: Product): Observable<Product> {
if (!product.id) {
return this.save(product);
} else {
return this.update(product);
}
}
delete(id: string): Observable<Product> {
return <Observable<Product>>this.http.delete<Product>(`${url}/${id}`, httpOptions)
.pipe(
catchError(this.log.handleError(serviceName, 'delete'))
);
}
autocomplete(term: string): Observable<Product[]> {
const options = {params: new HttpParams().set('t', term)};
return <Observable<Product[]>>this.http.get<Product[]>(url, options)
.pipe(
catchError(this.log.handleError(serviceName, 'autocomplete'))
);
}
balance(id: string, date: string): Observable<number> {
const options = {params: new HttpParams().set('b', 'true').set('d', date)};
return <Observable<number>>this.http.get<number>(`${url}/${id}`, options)
.pipe(
catchError(this.log.handleError(serviceName, 'balance'))
);
}
}