brewman/overlord/src/app/purchase-return/purchase-return.component.ts

370 lines
11 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 {BehaviorSubject, fromEvent, Observable, of, of as observableOf, zip} from 'rxjs';
import {PurchaseReturnDataSource} from './purchase-return-datasource';
import {Account} from '../core/account';
import {VoucherService} from '../core/voucher.service';
import {AccountService} from '../core/account.service';
import {Batch, DbFile, Inventory, Voucher} from '../core/voucher';
import * as moment from 'moment';
import {AuthService} from '../auth/auth.service';
import {ConfirmDialogComponent} from '../shared/confirm-dialog/confirm-dialog.component';
import {ToasterService} from '../core/toaster.service';
import {debounceTime, distinctUntilChanged, map, startWith, switchMap} from 'rxjs/operators';
import {PurchaseReturnDialogComponent} from './purchase-return-dialog.component';
import {ImageDialogComponent} from '../shared/image-dialog/image-dialog.component';
import {BatchService} from '../core/batch.service';
import {Hotkey, HotkeysService} from 'angular2-hotkeys';
@Component({
selector: 'app-purchase-return',
templateUrl: './purchase-return.component.html',
styleUrls: ['./purchase-return.component.css']
})
export class PurchaseReturnComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('accountElement', { static: true }) accountElement: ElementRef;
@ViewChild('batchElement', { static: true }) batchElement: ElementRef;
@ViewChild('dateElement', { static: true }) dateElement: ElementRef;
public inventoryObservable = new BehaviorSubject<Inventory[]>([]);
dataSource: PurchaseReturnDataSource;
form: FormGroup;
voucher: Voucher;
batch: Batch;
accBal: any;
displayedColumns = ['product', 'quantity', 'rate', 'tax', 'discount', 'amount', 'action'];
accounts: Observable<Account[]>;
batches: Observable<Batch[]>;
constructor(
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder,
private dialog: MatDialog,
private hotkeys: HotkeysService,
private toaster: ToasterService,
private auth: AuthService,
private ser: VoucherService,
private batchSer: BatchService,
private accountSer: AccountService
) {
this.createForm();
this.listenToAccountAutocompleteChange();
this.listenToBatchAutocompleteChange();
}
ngOnInit() {
this.route.data
.subscribe((data: { voucher: Voucher }) => {
this.loadVoucher(data.voucher);
});
this.hotkeys.add(new Hotkey('f2', (event: KeyboardEvent): boolean => {
setTimeout(() => {
this.dateElement.nativeElement.focus();
}, 0);
return false; // Prevent bubbling
}, ['INPUT', 'SELECT', 'TEXTAREA']));
this.hotkeys.add(new Hotkey('ctrl+s', (event: KeyboardEvent): boolean => {
if (this.canSave()) {
this.save();
}
return false; // Prevent bubbling
}, ['INPUT', 'SELECT', 'TEXTAREA']));
this.hotkeys.add(new Hotkey('ctrl+p', (event: KeyboardEvent): 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: 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: {
batch: '',
quantity: ''
},
narration: this.voucher.narration
});
this.dataSource = new PurchaseReturnDataSource(this.inventoryObservable);
this.updateView();
}
focusAccount() {
setTimeout(() => {
this.accountElement.nativeElement.focus();
}, 0);
}
addRow() {
const formValue = this.form.get('addRow').value;
const quantity = +(formValue.quantity);
if (this.batch === null || quantity <= 0 || this.batch.quantityRemaining < quantity) {
return;
}
const oldFiltered = this.voucher.inventories.filter((x) => x.product.id === this.batch.product.id);
if (oldFiltered.length) {
this.toaster.show('Danger', 'Product already added');
return;
}
this.voucher.inventories.push({
id: null,
quantity: quantity,
rate: this.batch.rate,
tax: this.batch.tax,
discount: this.batch.discount,
amount: quantity * this.batch.rate * (1 + this.batch.tax) * (1 - this.batch.discount),
product: this.batch.product,
batch: this.batch
});
this.resetAddRow();
this.updateView();
}
resetAddRow() {
this.form.get('addRow').reset({
batch: null,
quantity: ''
});
this.batch = null;
setTimeout(() => {
this.batchElement.nativeElement.focus();
}, 0);
}
updateView() {
this.inventoryObservable.next(this.voucher.inventories);
this.form.get('amount').setValue(Math.abs(this.voucher.inventories.map((x) => x.amount).reduce((p, c) => p + c, 0)));
}
editRow(row: Inventory) {
const dialogRef = this.dialog.open(PurchaseReturnDialogComponent, {
width: '750px',
data: {inventory: Object.assign({}, row), date: moment(this.form.value.date).format('DD-MMM-YYYY')}
});
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();
}
createForm() {
this.form = this.fb.group({
date: '',
account: '',
amount: {value: '', disabled: true},
addRow: this.fb.group({
batch: '',
quantity: ''
}),
narration: ''
});
}
canSave() {
if (!this.voucher.id) {
return true;
} else if (this.voucher.posted && this.auth.user.perms.indexOf('edit-posted-vouchers') !== -1) {
return true;
} else {
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-return', 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(
(result) => {
this.toaster.show('Success', '');
this.router.navigate(['/purchase-return'], {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))
);
}
listenToBatchAutocompleteChange(): void {
const control = this.form.get('addRow').get('batch');
this.batches = control.valueChanges
.pipe(
startWith(null),
map(x => (x !== null && x.length >= 1) ? x : null),
debounceTime(150),
distinctUntilChanged(),
switchMap(
x => (x === null) ? observableOf([]) : this.batchSer.autocomplete(
moment(this.form.value.date).format('DD-MMM-YYYY'), x
)
)
);
}
displayAccount(account?: Account): string | undefined {
return account ? account.name : undefined;
}
accountSelected(event: MatAutocompleteSelectedEvent): void {
this.form.get('account').setValue(event.option.value);
}
displayBatchName(batch?: Batch): string | undefined {
return batch ? batch.name : undefined;
}
batchSelected(event: MatAutocompleteSelectedEvent): void {
this.batch = event.option.value;
}
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);
}
detectFiles(event) {
const files = event.target.files;
if (files) {
for (const file of files) {
const reader = new FileReader();
reader.onload = (e: any) => {
zip(of(e.target.result),
this.resizeImage(e.target.result, 100, 150),
this.resizeImage(e.target.result, 825, 1170)
).subscribe(
val => this.voucher.files.push({id: null, thumbnail: val[1], resized: val[2]})
);
};
reader.readAsDataURL(file);
}
}
}
resizeImage(image, MAX_WIDTH, MAX_HEIGHT) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
const ex = fromEvent(img, 'load').pipe(
map((e) => {
let width = img.naturalWidth,
height = img.naturalHeight;
const ratio = Math.min(1, MAX_WIDTH / width, MAX_HEIGHT / height);
if (ratio === 1) {
return image;
}
width *= ratio;
height *= ratio;
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
return canvas.toDataURL('image/jpeg', 0.95);
})
);
img.src = image;
return ex;
}
}