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

291 lines
9.1 KiB
TypeScript

import { CurrencyPipe, DecimalPipe } from '@angular/common';
import { Component, inject, computed, input, linkedSignal, signal, afterNextRender } from '@angular/core';
import { form as createForm, FormField, FormRoot, required } from '@angular/forms/signals';
import { MatButtonModule } from '@angular/material/button';
import { MatOptionModule } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialog } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { MatSelectChange, MatSelectModule } from '@angular/material/select';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatSortModule, Sort } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { Router } from '@angular/router';
import moment from 'moment';
import { AuthService } from '../auth/auth.service';
import { CostCentre } from '../core/cost-centre';
import { User } from '../core/user';
import { CostCentreService } from '../cost-centre/cost-centre.service';
import { ConfirmDialogComponent } from '../shared/confirm-dialog/confirm-dialog.component';
import { ErrorStateComponent } from '../shared/error-state/error-state.component';
import { SkeletonLoaderComponent } from '../shared/skeleton-loader/skeleton-loader.component';
import { ToCsvService } from '../shared/to-csv.service';
import { ClosingStock } from './closing-stock';
import { ClosingStockItem } from './closing-stock-item';
import { ClosingStockService } from './closing-stock.service';
export interface ClosingStockFormData {
date: Date;
costCentre: CostCentre | null;
stocks: { physical: number; costCentre: string | undefined }[];
}
@Component({
selector: 'app-closing-stock',
templateUrl: './closing-stock.component.html',
styleUrls: ['./closing-stock.component.css'],
host: {
'(window:keydown.f2)': 'focusDate($event)',
},
imports: [
MatIconModule,
FormField,
FormRoot,
MatFormFieldModule,
MatSelectModule,
MatOptionModule,
MatInputModule,
MatDatepickerModule,
MatButtonModule,
MatTableModule,
MatSortModule,
MatPaginatorModule,
DecimalPipe,
CurrencyPipe,
SkeletonLoaderComponent,
ErrorStateComponent,
],
})
export class ClosingStockComponent {
private router = inject(Router);
private toCsv = inject(ToCsvService);
private dialog = inject(MatDialog);
private snackBar = inject(MatSnackBar);
protected auth = inject(AuthService);
private ser = inject(ClosingStockService);
private costCentreSer = inject(CostCentreService);
pageSize = signal(50);
pageIndex = signal(0);
sortActive = signal('');
sortDirection = signal('');
date = input(null, { transform: (v: string | null | undefined) => v ?? null });
d = input(null, { transform: (v: string | null | undefined) => v ?? null });
startDate = input(null, { transform: (v: string | null | undefined) => v ?? null });
finishDate = input(null, { transform: (v: string | null | undefined) => v ?? null });
infoResource = this.ser.list(this.date, this.d);
info = computed(() => this.infoResource.value() ?? new ClosingStock());
costCentresResource = this.costCentreSer.list();
costCentres = computed(() => this.costCentresResource.value() ?? []);
model = linkedSignal({
source: computed(() => ({ info: this.info(), costCentres: this.costCentres() })),
computation: ({ info, costCentres }): ClosingStockFormData => ({
date: moment(info.date, 'DD-MMM-YYYY').toDate(),
costCentre: costCentres.find((c) => c.id === info.costCentre?.id) || null,
stocks: info.items.map((x) => ({
physical: x.physical,
costCentre: x.costCentre?.id,
})),
}),
});
form = createForm(this.model, (f) => {
required(f.costCentre);
required(f.date);
});
sortedList = computed(() => {
const data = this.info().items ?? [];
const active = this.sortActive();
const direction = this.sortDirection();
if (!active || direction === '') {
return data;
}
return [...data].sort((a, b) => {
const isAsc = direction === 'asc';
switch (active) {
case 'product':
return compare(a.product?.name ?? '', b.product?.name ?? '', isAsc);
case 'group':
return compare(a.group ?? '', b.group ?? '', isAsc);
case 'quantity':
return compare(a.quantity ?? 0, b.quantity ?? 0, isAsc);
case 'amount':
return compare(a.amount ?? 0, b.amount ?? 0, isAsc);
default:
return 0;
}
});
});
dataSource = computed(() => {
const data = this.sortedList();
const pageIndex = this.pageIndex();
const pageSize = this.pageSize();
return data.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize);
});
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['product', 'group', 'quantity', 'physical', 'variance', 'department', 'amount'];
focusDate(event: Event) {
event.preventDefault();
this.form().focusBoundControl();
}
constructor() {
afterNextRender(() => {
this.form().focusBoundControl();
});
}
show() {
if (this.form().invalid()) {
return;
}
const info = this.getInfo();
this.router.navigate(['closing-stock', info.date], {
queryParams: {
d: info.costCentre.id,
},
});
}
save() {
this.ser.save(this.getClosingStock()).subscribe({
next: () => {
this.snackBar.open('', 'Success');
},
error: (error) => {
this.snackBar.open(error, 'Danger');
},
});
}
getClosingStock(): ClosingStock {
const formModel = this.model();
const currentInfo = this.info();
currentInfo.date = moment(formModel.date).format('DD-MMM-YYYY');
const array = formModel.stocks;
currentInfo.items.forEach((item, index) => {
item.physical = array[index].physical ?? 0;
item.costCentre = array[index].costCentre == null ? undefined : new CostCentre({ id: array[index].costCentre });
});
return currentInfo;
}
getInfo(): ClosingStock {
const formModel = this.model();
return new ClosingStock({
date: moment(formModel.date).format('DD-MMM-YYYY'),
costCentre: formModel.costCentre ?? new CostCentre(),
});
}
exportCsv() {
const headers = {
Product: 'product',
Group: 'group',
Quantity: 'quantity',
Amount: 'amount',
};
const d = JSON.parse(JSON.stringify(this.dataSource())).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({
next: () => {
this.snackBar.open('Voucher Posted', 'Success');
},
error: (error) => {
this.snackBar.open(error, 'Danger');
},
});
}
delete() {
this.ser.delete(this.info().date, this.info().costCentre.id as string).subscribe({
next: () => {
this.snackBar.open('', 'Success');
this.router.navigate(['/closing-stock'], { replaceUrl: true });
},
error: (error) => {
this.snackBar.open(error, 'Danger');
},
});
}
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();
}
});
}
handlePageEvent(e: PageEvent) {
this.pageSize.set(e.pageSize);
this.pageIndex.set(e.pageIndex);
}
sortData(sort: Sort) {
this.sortActive.set(sort.active);
this.sortDirection.set(sort.direction);
}
}
const compare = (a: string | number | boolean, b: string | number | boolean, isAsc: boolean) =>
(a < b ? -1 : 1) * (isAsc ? 1 : -1);