Files
brewman/overlord/src/app/purchase/purchase.component.ts
tanshu 39e3cc51bb Moving to strict.
Create form has now moved to constructor and route data subscribe is type safe.
2020-11-23 09:18:02 +05:30

365 lines
10 KiB
TypeScript

import { AfterViewInit, Component, ElementRef, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { Hotkey, HotkeysService } from 'angular2-hotkeys';
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 { AuthService } from '../auth/auth.service';
import { Account } from '../core/account';
import { AccountService } from '../core/account.service';
import { DbFile } from '../core/db-file';
import { Inventory } from '../core/inventory';
import { Product } from '../core/product';
import { ToasterService } from '../core/toaster.service';
import { Voucher } from '../core/voucher';
import { VoucherService } from '../core/voucher.service';
import { ProductService } from '../product/product.service';
import { ConfirmDialogComponent } from '../shared/confirm-dialog/confirm-dialog.component';
import { ImageDialogComponent } from '../shared/image-dialog/image-dialog.component';
import { ImageService } from '../shared/image.service';
import { MathService } from '../shared/math.service';
import { PurchaseDataSource } from './purchase-datasource';
import { PurchaseDialogComponent } from './purchase-dialog.component';
@Component({
selector: 'app-purchase',
templateUrl: './purchase.component.html',
styleUrls: ['./purchase.component.css'],
})
export class PurchaseComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('accountElement', { static: true }) accountElement: ElementRef;
@ViewChild('productElement', { static: true }) productElement: ElementRef;
@ViewChild('dateElement', { static: true }) dateElement: ElementRef;
public inventoryObservable = new BehaviorSubject<Inventory[]>([]);
dataSource: PurchaseDataSource;
form: FormGroup;
voucher: Voucher;
product: Product;
accBal: any;
displayedColumns = ['product', 'quantity', 'rate', 'tax', 'discount', 'amount', 'action'];
accounts: Observable<Account[]>;
products: Observable<Product[]>;
constructor(
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder,
private dialog: MatDialog,
private hotkeys: HotkeysService,
private toaster: ToasterService,
public auth: AuthService,
private math: MathService,
public image: ImageService,
private ser: VoucherService,
private productSer: ProductService,
private accountSer: AccountService,
) {
this.form = this.fb.group({
date: '',
account: '',
amount: { value: '', disabled: true },
addRow: this.fb.group({
product: '',
quantity: '',
price: '',
tax: '',
discount: '',
}),
narration: '',
});
this.accBal = null;
this.listenToAccountAutocompleteChange();
this.listenToProductAutocompleteChange();
}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as { voucher: Voucher };
this.loadVoucher(data.voucher);
});
this.hotkeys.add(
new Hotkey(
'f2',
(): boolean => {
setTimeout(() => {
this.dateElement.nativeElement.focus();
}, 0);
return false; // Prevent bubbling
},
['INPUT', 'SELECT', 'TEXTAREA'],
),
);
this.hotkeys.add(
new Hotkey(
'ctrl+s',
(): boolean => {
if (this.canSave()) {
this.save();
}
return false; // Prevent bubbling
},
['INPUT', 'SELECT', 'TEXTAREA'],
),
);
this.hotkeys.add(
new Hotkey(
'ctrl+p',
(): boolean => {
if (
this.voucher.id &&
!this.voucher.posted &&
this.auth.user.perms.indexOf('post-vouchers') !== -1
) {
this.post();
}
return false; // Prevent bubbling
},
['INPUT', 'SELECT', 'TEXTAREA'],
),
);
}
ngAfterViewInit() {
this.focusAccount();
}
ngOnDestroy() {
this.hotkeys.reset();
}
loadVoucher(voucher) {
this.voucher = voucher;
this.form.setValue({
date: moment(this.voucher.date, 'DD-MMM-YYYY').toDate(),
account: this.voucher.vendor,
amount: Math.abs(this.voucher.inventories.map((x) => x.amount).reduce((p, c) => p + c, 0)),
addRow: {
product: '',
quantity: '',
price: '',
tax: '',
discount: '',
},
narration: this.voucher.narration,
});
this.dataSource = new PurchaseDataSource(this.inventoryObservable);
this.updateView();
}
focusAccount() {
setTimeout(() => {
this.accountElement.nativeElement.focus();
}, 0);
}
addRow() {
const formValue = this.form.get('addRow').value;
const quantity = this.math.parseAmount(formValue.quantity, 2);
const price = this.math.parseAmount(formValue.price, 2);
const tax = this.math.parseAmount(formValue.tax, 5);
const discount = this.math.parseAmount(formValue.discount, 5);
if (this.product === null || quantity <= 0 || price <= 0) {
return;
}
const oldFiltered = this.voucher.inventories.filter((x) => x.product.id === this.product.id);
if (oldFiltered.length) {
this.toaster.show('Danger', 'Product already added');
return;
}
this.voucher.inventories.push({
id: null,
quantity,
rate: price,
tax,
discount,
amount: round(quantity * price * (1 + tax) * (1 - discount), 2),
product: this.product,
batch: null,
});
this.resetAddRow();
this.updateView();
}
resetAddRow() {
this.form.get('addRow').reset({
product: null,
quantity: '',
price: '',
tax: '',
discount: '',
});
this.product = null;
setTimeout(() => {
this.productElement.nativeElement.focus();
}, 0);
}
updateView() {
this.inventoryObservable.next(this.voucher.inventories);
this.form
.get('amount')
.setValue(
round(Math.abs(this.voucher.inventories.map((x) => x.amount).reduce((p, c) => p + c, 0))),
2,
);
}
editRow(row: Inventory) {
const dialogRef = this.dialog.open(PurchaseDialogComponent, {
width: '750px',
data: { inventory: { ...row } },
});
dialogRef.afterClosed().subscribe((result: boolean | Inventory) => {
if (!result) {
return;
}
const j = result as Inventory;
if (
j.product.id !== row.product.id &&
this.voucher.inventories.filter((x) => x.product.id === j.product.id).length
) {
return;
}
Object.assign(row, j);
this.updateView();
});
}
deleteRow(row: Inventory) {
this.voucher.inventories.splice(this.voucher.inventories.indexOf(row), 1);
this.updateView();
}
canSave() {
if (!this.voucher.id) {
return true;
}
if (this.voucher.posted && this.auth.user.perms.indexOf('edit-posted-vouchers') !== -1) {
return true;
}
return (
this.voucher.user.id === this.auth.user.id ||
this.auth.user.perms.indexOf("edit-other-user's-vouchers") !== -1
);
}
post() {
this.ser.post(this.voucher.id).subscribe(
(result) => {
this.loadVoucher(result);
this.toaster.show('Success', 'Voucher Posted');
},
(error) => {
this.toaster.show('Danger', error);
},
);
}
save() {
const voucher: Voucher = this.getVoucher();
this.ser.saveOrUpdate(voucher).subscribe(
(result) => {
this.toaster.show('Success', '');
if (voucher.id === result.id) {
this.loadVoucher(result);
} else {
this.router.navigate(['/purchase', result.id]);
}
},
(error) => {
this.toaster.show('Danger', error);
},
);
}
getVoucher(): Voucher {
const formModel = this.form.value;
this.voucher.date = moment(formModel.date).format('DD-MMM-YYYY');
this.voucher.vendor = formModel.account;
this.voucher.narration = formModel.narration;
return this.voucher;
}
delete() {
this.ser.delete(this.voucher.id).subscribe(
() => {
this.toaster.show('Success', '');
this.router.navigate(['/purchase'], { replaceUrl: true });
},
(error) => {
this.toaster.show('Danger', error);
},
);
}
confirmDelete(): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px',
data: { title: 'Delete Voucher?', content: 'Are you sure? This cannot be undone.' },
});
dialogRef.afterClosed().subscribe((result: boolean) => {
if (result) {
this.delete();
}
});
}
listenToAccountAutocompleteChange(): void {
const control = this.form.get('account');
this.accounts = control.valueChanges.pipe(
startWith(null),
map((x) => (x !== null && x.length >= 1 ? x : null)),
debounceTime(150),
distinctUntilChanged(),
switchMap((x) => (x === null ? observableOf([]) : this.accountSer.autocomplete(x))),
);
}
listenToProductAutocompleteChange(): void {
const control = this.form.get('addRow').get('product');
this.products = control.valueChanges.pipe(
startWith(null),
map((x) => (x !== null && x.length >= 1 ? x : null)),
debounceTime(150),
distinctUntilChanged(),
switchMap((x) => (x === null ? observableOf([]) : this.productSer.autocomplete(x))),
);
}
displayFn(item?: Account | Product): string | undefined {
return item ? item.name : undefined;
}
accountSelected(event: MatAutocompleteSelectedEvent): void {
this.form.get('account').setValue(event.option.value);
}
productSelected(event: MatAutocompleteSelectedEvent): void {
this.product = event.option.value;
this.form.get('addRow').get('price').setValue(this.product.price);
}
zoomImage(file: DbFile) {
this.dialog.open(ImageDialogComponent, {
width: '750px',
data: file.resized,
});
}
deleteImage(file: DbFile) {
const index = this.voucher.files.indexOf(file);
this.voucher.files.splice(index, 1);
}
}