Feature: Recipe module mostly working. What needs to be done is duplicating recipes and export for checking.

Feature: Non Contract Purchases Report
This commit is contained in:
2021-11-10 10:57:18 +05:30
parent 3b8c972c48
commit ffd46bf717
59 changed files with 2139 additions and 251 deletions
@@ -0,0 +1,16 @@
import { DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs';
import { RecipeItem } from '../recipe-item';
export class RecipeDetailDatasource extends DataSource<RecipeItem> {
constructor(private data: Observable<RecipeItem[]>) {
super();
}
connect(): Observable<RecipeItem[]> {
return this.data;
}
disconnect() {}
}
@@ -0,0 +1,3 @@
.example-card {
max-width: 400px;
}
@@ -0,0 +1,206 @@
<mat-card>
<mat-card-title-group>
<mat-card-title>Recipe Detail</mat-card-title>
</mat-card-title-group>
<mat-card-content>
<form [formGroup]="form" fxLayout="column">
<div
fxLayout="row"
fxLayout.lt-md="column"
fxLayoutGap="20px"
fxLayoutGap.lt-md="0px"
fxLayoutAlign="space-around start"
>
<mat-form-field fxFlex="50">
<input
matInput
[matDatepicker]="validFrom"
placeholder="Valid From"
formControlName="validFrom"
autocomplete="off"
/>
<mat-datepicker-toggle matSuffix [for]="validFrom"></mat-datepicker-toggle>
<mat-datepicker #validFrom></mat-datepicker>
</mat-form-field>
<mat-form-field fxFlex="50">
<input
matInput
[matDatepicker]="validTill"
placeholder="Valid Till"
formControlName="validTill"
autocomplete="off"
/>
<mat-datepicker-toggle matSuffix [for]="validTill"></mat-datepicker-toggle>
<mat-datepicker #validTill></mat-datepicker>
</mat-form-field>
</div>
<div fxLayout="row" fxLayout.lt-md="column" fxLayoutGap="20px" fxLayoutGap.lt-md="0px">
<mat-form-field fxFlex="60">
<input
type="text"
matInput
placeholder="Product"
#productElement
[matAutocomplete]="autoP"
formControlName="product"
autocomplete="off"
/>
<mat-autocomplete
#autoP="matAutocomplete"
autoActiveFirstOption
[displayWith]="displayProduct"
(optionSelected)="productSelected($event)"
>
<mat-option *ngFor="let product of products | async" [value]="product">{{
product.name
}}</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field fxFlex="10">
<mat-label>Yield</mat-label>
<input
type="text"
matInput
placeholder="Yield"
formControlName="recipeYield"
autocomplete="off"
/>
</mat-form-field>
<mat-form-field fxFlex="10">
<mat-label>Sale Price</mat-label>
<span matPrefix></span>
<input
type="text"
matInput
placeholder="Sale Price"
formControlName="salePrice"
autocomplete="off"
/>
</mat-form-field>
<mat-form-field fxFlex="10">
<mat-label>Cost Price</mat-label>
<span matPrefix></span>
<input
type="text"
matInput
placeholder="Cost Price"
formControlName="costPrice"
autocomplete="off"
/>
</mat-form-field>
<mat-form-field fxFlex="10">
<mat-label>Cost Percentage</mat-label>
<input
type="text"
matInput
placeholder="Cost Percentage"
formControlName="costPercentage"
autocomplete="off"
/>
<span matSuffix>%</span>
</mat-form-field>
</div>
<div
formGroupName="addRow"
fxLayout="row"
fxLayoutAlign="space-around start"
fxLayout.lt-md="column"
fxLayoutGap="20px"
fxLayoutGap.lt-md="0px"
>
<mat-form-field fxFlex="50">
<input
type="text"
matInput
placeholder="Ingredient"
#ingredientElement
[matAutocomplete]="autoI"
formControlName="ingredient"
autocomplete="off"
/>
<mat-autocomplete
#autoI="matAutocomplete"
autoActiveFirstOption
[displayWith]="displayIngredient"
(optionSelected)="ingredientSelected($event)"
>
<mat-option *ngFor="let product of ingredients | async" [value]="product"
>{{ product.name }} ({{ product.fractionUnits }})</mat-option
>
</mat-autocomplete>
</mat-form-field>
<mat-form-field fxFlex="20">
<mat-label>Quantity</mat-label>
<input
type="text"
matInput
placeholder="Quantity"
formControlName="quantity"
autocomplete="off"
/>
</mat-form-field>
<mat-form-field fxFlex="20">
<mat-label>Rate</mat-label>
<span matPrefix></span>
<input
type="text"
matInput
placeholder="Rate"
formControlName="rate"
autocomplete="off"
/>
</mat-form-field>
<button mat-raised-button color="primary" (click)="addRow()" fxFlex="15">Add</button>
</div>
<mat-table #table [dataSource]="dataSource" matSort aria-label="Elements">
<!-- Ingredient Column -->
<ng-container matColumnDef="product">
<mat-header-cell *matHeaderCellDef>Product</mat-header-cell>
<mat-cell *matCellDef="let row">{{ row.product.name }}</mat-cell>
</ng-container>
<!-- Quantity Column -->
<ng-container matColumnDef="quantity">
<mat-header-cell *matHeaderCellDef class="right">Quantity</mat-header-cell>
<mat-cell *matCellDef="let row" class="right"
>{{ row.quantity | number: '1.2-2' }} {{ row.product.fractionUnits }}</mat-cell
>
</ng-container>
<!-- Rate Column -->
<ng-container matColumnDef="rate">
<mat-header-cell *matHeaderCellDef class="right">Rate</mat-header-cell>
<mat-cell *matCellDef="let row" class="right">{{ row.price | currency: 'INR' }}</mat-cell>
</ng-container>
<!-- Amount Column -->
<ng-container matColumnDef="amount">
<mat-header-cell *matHeaderCellDef class="right">Amount</mat-header-cell>
<mat-cell *matCellDef="let row" class="right">{{
row.quantity * row.price | currency: 'INR'
}}</mat-cell>
</ng-container>
<!-- Action Column -->
<ng-container matColumnDef="action">
<mat-header-cell *matHeaderCellDef class="center">Action</mat-header-cell>
<mat-cell *matCellDef="let row" class="center">
<button mat-icon-button tabindex="-1" color="warn" (click)="deleteRow(row)">
<mat-icon>delete</mat-icon>
</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
</form>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button (click)="save()" color="primary">
{{ item.id ? 'Update' : 'Save' }}
</button>
<button mat-raised-button color="warn" (click)="confirmDelete()" *ngIf="item.id">Delete</button>
</mat-card-actions>
</mat-card>
@@ -0,0 +1,29 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { RecipeDetailComponent } from './recipe-detail.component';
describe('ProductGroupDetailComponent', () => {
let component: RecipeDetailComponent;
let fixture: ComponentFixture<RecipeDetailComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, RouterTestingModule],
declarations: [RecipeDetailComponent],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(RecipeDetailComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,258 @@
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { round } from 'mathjs';
import * as moment from 'moment';
import { BehaviorSubject, Observable, of as observableOf } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, startWith, switchMap } from 'rxjs/operators';
import { Product } from '../../core/product';
import { ProductSku } from '../../core/product-sku';
import { ToasterService } from '../../core/toaster.service';
import { ProductService } from '../../product/product.service';
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
import { MathService } from '../../shared/math.service';
import { Recipe } from '../recipe';
import { RecipeItem } from '../recipe-item';
import { RecipeService } from '../recipe.service';
import { RecipeDetailDatasource } from './recipe-detail-datasource';
@Component({
selector: 'app-product-group-detail',
templateUrl: './recipe-detail.component.html',
styleUrls: ['./recipe-detail.component.css'],
})
export class RecipeDetailComponent implements OnInit, AfterViewInit {
@ViewChild('productElement', { static: true }) productElement?: ElementRef;
@ViewChild('ingredientElement', { static: true }) ingredientElement?: ElementRef;
public itemsObservable = new BehaviorSubject<RecipeItem[]>([]);
dataSource: RecipeDetailDatasource = new RecipeDetailDatasource(this.itemsObservable);
form: FormGroup;
product: ProductSku | null;
products: Observable<ProductSku[]>;
ingredient: ProductSku | null;
ingredients: Observable<ProductSku[]>;
item: Recipe = new Recipe();
displayedColumns = ['product', 'quantity', 'rate', 'amount', 'action'];
constructor(
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder,
private dialog: MatDialog,
private toaster: ToasterService,
private math: MathService,
private ser: RecipeService,
private productSer: ProductService,
) {
this.product = null;
this.ingredient = null;
this.form = this.fb.group({
validFrom: '',
validTill: '',
recipeYield: '',
salePrice: '',
costPrice: '',
costPercentage: '',
product: new Product(),
addRow: this.fb.group({
ingredient: '',
quantity: '',
rate: '',
}),
});
// Setup Product Autocomplete
this.products = (this.form.get('product') as FormControl).valueChanges.pipe(
startWith(null),
map((x) => (x !== null && x.length >= 1 ? x : null)),
debounceTime(150),
distinctUntilChanged(),
switchMap((x) => (x === null ? observableOf([]) : this.productSer.autocompleteSku(x, false))),
);
// Setup Product Autocomplete
this.ingredients = (
(this.form.get('addRow') as FormControl).get('ingredient') as FormControl
).valueChanges.pipe(
startWith(null),
map((x) => (x !== null && x.length >= 1 ? x : null)),
debounceTime(150),
distinctUntilChanged(),
switchMap((x) =>
x === null ? observableOf([]) : this.productSer.autocompleteProduct(x, null),
),
);
}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as { item: Recipe };
this.showItem(data.item);
this.updateView();
});
}
showItem(item: Recipe) {
this.item = item;
this.form.setValue({
validFrom: moment(item.validFrom, 'DD-MMM-YYYY').toDate(),
validTill: moment(item.validTill, 'DD-MMM-YYYY').toDate(),
recipeYield: '' + item.recipeYield,
salePrice: '' + item.salePrice,
costPrice: '' + item.costPrice,
costPercentage: '',
product: item.sku,
addRow: {
ingredient: null,
quantity: '',
rate: '',
},
});
this.dataSource = new RecipeDetailDatasource(this.itemsObservable);
}
ngAfterViewInit() {
setTimeout(() => {
if (this.productElement) {
this.productElement.nativeElement.focus();
}
}, 0);
}
displayIngredient(product?: Product): string {
return product ? `${product.name} (${product.fractionUnits})` : '';
}
displayProduct(product?: Product): string {
return product?.name || '';
}
productSelected(event: MatAutocompleteSelectedEvent): void {
const product: ProductSku = event.option.value;
this.item.sku = product;
(this.form.get('product') as FormControl).setValue(product);
(this.form.get('salePrice') as FormControl).setValue('' + (product.salePrice ?? 0));
}
ingredientSelected(event: MatAutocompleteSelectedEvent): void {
const ingredient: ProductSku = event.option.value;
this.ingredient = ingredient;
const item = this.getItem();
this.ser
.getIngredientDetails(ingredient.id, item.validFrom, item.validTill)
.subscribe((x) =>
((this.form.get('addRow') as FormControl).get('rate') as FormControl).setValue(
'' + x.costPrice,
),
);
}
addRow() {
const formValue = (this.form.get('addRow') as FormControl).value;
const quantity = this.math.parseAmount(formValue.quantity, 2);
const rate = this.math.parseAmount(formValue.rate, 2);
if (this.ingredient === null || quantity <= 0 || rate <= 0) {
return;
}
const oldFiltered = this.item.items.filter(
(x) => x.product.id === (this.ingredient as ProductSku).id,
);
if (oldFiltered.length) {
this.toaster.show('Danger', 'Product already added');
return;
}
this.item.items.push(
new RecipeItem({
product: this.ingredient,
quantity,
price: rate,
}),
);
this.resetAddRow();
this.updateView();
}
resetAddRow() {
(this.form.get('addRow') as FormControl).reset({
ingredient: null,
quantity: '',
rate: '',
});
this.ingredient = null;
setTimeout(() => {
if (this.ingredientElement) {
this.ingredientElement.nativeElement.focus();
}
}, 0);
}
updateView() {
this.itemsObservable.next(this.item.items);
const costPrice = round(
this.item.items.map((x) => x.quantity * x.price).reduce((p, c) => p + c, 0),
2,
);
(this.form.get('costPrice') as FormControl).setValue(costPrice);
const salePrice = this.math.parseAmount(this.form.value.salePrice, 2);
if (salePrice < 0) {
return;
}
const costPercentage = round((100 * costPrice) / salePrice, 2);
(this.form.get('costPercentage') as FormControl).setValue(costPercentage);
}
deleteRow(row: RecipeItem) {
this.item.items.splice(this.item.items.indexOf(row), 1);
this.updateView();
}
save() {
this.ser.saveOrUpdate(this.getItem()).subscribe(
() => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/recipes');
},
(error) => {
this.toaster.show('Danger', error);
},
);
}
delete() {
this.ser.delete(this.item.id as string).subscribe(
() => {
this.toaster.show('Success', '');
this.router.navigate(['/recipes']);
},
(error) => {
this.toaster.show('Danger', error);
},
);
}
confirmDelete(): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px',
data: { title: 'Delete Recipe?', content: 'Are you sure? This cannot be undone.' },
});
dialogRef.afterClosed().subscribe((result: boolean) => {
if (result) {
this.delete();
}
});
}
getItem(): Recipe {
const formModel = this.form.value;
this.item.validFrom = moment(formModel.validFrom).format('DD-MMM-YYYY');
this.item.validTill = moment(formModel.validTill).format('DD-MMM-YYYY');
this.item.recipeYield = this.math.parseAmount(formModel.recipeYield, 2);
this.item.salePrice = this.math.parseAmount(formModel.salePrice, 2);
this.item.costPrice = this.math.parseAmount(formModel.costPrice, 2);
return this.item;
}
}