brewman/overlord/src/app/closing-stock/closing-stock.component.ts

219 lines
6.4 KiB
TypeScript

import { Component, OnInit, ViewChild } from '@angular/core';
import { UntypedFormArray, UntypedFormBuilder, FormControl, UntypedFormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSelectChange } from '@angular/material/select';
import { MatSort } from '@angular/material/sort';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { AuthService } from '../auth/auth.service';
import { CostCentre } from '../core/cost-centre';
import { ToasterService } from '../core/toaster.service';
import { User } from '../core/user';
import { ConfirmDialogComponent } from '../shared/confirm-dialog/confirm-dialog.component';
import { ToCsvService } from '../shared/to-csv.service';
import { ClosingStock } from './closing-stock';
import { ClosingStockDataSource } from './closing-stock-datasource';
import { ClosingStockItem } from './closing-stock-item';
import { ClosingStockService } from './closing-stock.service';
@Component({
selector: 'app-closing-stock',
templateUrl: './closing-stock.component.html',
styleUrls: ['./closing-stock.component.css'],
})
export class ClosingStockComponent implements OnInit {
@ViewChild(MatPaginator, { static: true }) paginator?: MatPaginator;
@ViewChild(MatSort, { static: true }) sort?: MatSort;
info: ClosingStock = new ClosingStock();
dataSource: ClosingStockDataSource = new ClosingStockDataSource(this.info.items);
form: UntypedFormGroup;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = [
'product',
'group',
'quantity',
'physical',
'variance',
'department',
'amount',
];
costCentres: CostCentre[];
constructor(
private route: ActivatedRoute,
private router: Router,
private fb: UntypedFormBuilder,
private toCsv: ToCsvService,
private dialog: MatDialog,
private toaster: ToasterService,
public auth: AuthService,
private ser: ClosingStockService,
) {
this.costCentres = [];
this.form = this.fb.group({
date: '',
costCentre: '',
stocks: this.fb.array([]),
});
}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as { info: ClosingStock; costCentres: CostCentre[] };
this.info = data.info;
this.costCentres = data.costCentres;
this.form.patchValue({
date: moment(this.info.date, 'DD-MMM-YYYY').toDate(),
costCentre: this.info.costCentre.id,
});
this.form.setControl(
'stocks',
this.fb.array(
this.info.items.map((x) =>
this.fb.group({
physical: '' + x.physical,
costCentre: x.costCentre?.id,
}),
),
),
);
this.dataSource = new ClosingStockDataSource(this.info.items, this.paginator, this.sort);
});
}
show() {
const info = this.getInfo();
this.router.navigate(['closing-stock', info.date], {
queryParams: {
d: info.costCentre.id,
},
});
}
save() {
this.ser.save(this.getClosingStock()).subscribe(
() => {
this.toaster.show('Success', '');
},
(error) => {
this.toaster.show('Danger', error);
},
);
}
getClosingStock(): ClosingStock {
const formModel = this.form.value;
this.info.date = moment(formModel.date).format('DD-MMM-YYYY');
const array = this.form.get('stocks') as UntypedFormArray;
this.info.items.forEach((item, index) => {
item.physical = +array.controls[index].value.physical;
item.costCentre =
array.controls[index].value.costCentre == null
? undefined
: new CostCentre({ id: array.controls[index].value.costCentre });
});
console.log('getClosingStock', this.info);
return this.info;
}
getInfo(): ClosingStock {
const formModel = this.form.value;
return new ClosingStock({
date: moment(formModel.date).format('DD-MMM-YYYY'),
costCentre: new CostCentre({ id: formModel.costCentre }),
});
}
exportCsv() {
const headers = {
Product: 'product',
Group: 'group',
Quantity: 'quantity',
Amount: 'amount',
};
const d = JSON.parse(JSON.stringify(this.dataSource.data)).map(
(x: ClosingStockItem)=> ({product: x.product.name, group: x.group, quantity: x.quantity, amount: x.amount})
);
const csvData = new Blob([this.toCsv.toCsv(headers, d)], {
type: 'text/csv;charset=utf-8;',
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(csvData);
link.setAttribute('download', 'closing-stock.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
updatePhysical($event: Event, row: ClosingStockItem) {
row.physical = +($event.target as HTMLInputElement).value;
}
updateDepartment($event: MatSelectChange, row: ClosingStockItem) {
row.costCentre = new CostCentre({ id: $event.value });
}
canDelete() {
return this.info.items.find((x) => !!x.id) !== undefined;
}
canSave() {
if (this.info.items.find((x) => !!x.id) !== undefined) {
return true;
}
if (this.info.posted && this.auth.allowed('edit-posted-vouchers')) {
return true;
}
return (
this.info.user.id === (this.auth.user as User).id ||
this.auth.allowed("edit-other-user's-vouchers")
);
}
post() {
this.ser.post(this.info.date, this.info.costCentre.id as string).subscribe(
(result) => {
// this.loadVoucher(result);
this.toaster.show('Success', 'Voucher Posted');
},
(error) => {
this.toaster.show('Danger', error);
},
);
}
delete() {
this.ser.delete(this.info.date, this.info.costCentre.id as string).subscribe(
() => {
this.toaster.show('Success', '');
this.router.navigate(['/closing-stock'], { replaceUrl: true });
},
(error) => {
this.toaster.show('Danger', error);
},
);
}
confirmDelete(): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px',
data: {
title: 'Delete Closing Stock information?',
content: 'Are you sure? This cannot be undone.',
},
});
dialogRef.afterClosed().subscribe((result: boolean) => {
if (result) {
this.delete();
}
});
}
}