import { COMMA, ENTER } from '@angular/cdk/keycodes'; import { AsyncPipe, CurrencyPipe } from '@angular/common'; import { AfterViewInit, Component, ElementRef, OnInit, ViewChild, HostListener } from '@angular/core'; import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { MatAutocompleteSelectedEvent, MatAutocompleteTrigger, MatAutocomplete } from '@angular/material/autocomplete'; import { MatButton, MatIconButton } from '@angular/material/button'; import { MatCard, MatCardHeader, MatCardTitleGroup, MatCardTitle, MatCardContent, MatCardActions, } from '@angular/material/card'; import { MatChipInputEvent, MatChipGrid, MatChipRow, MatChipRemove, MatChipInput } from '@angular/material/chips'; import { MatOption } from '@angular/material/core'; import { MatDatepickerInput, MatDatepickerToggle, MatDatepicker } from '@angular/material/datepicker'; import { MatDialog } from '@angular/material/dialog'; import { MatSuffix, MatFormField, MatLabel, MatPrefix, MatHint } from '@angular/material/form-field'; import { MatIcon } from '@angular/material/icon'; import { MatInput } from '@angular/material/input'; import { MatSelect } from '@angular/material/select'; import { MatSort } from '@angular/material/sort'; import { MatTable, MatColumnDef, MatHeaderCellDef, MatHeaderCell, MatCellDef, MatCell, MatHeaderRowDef, MatHeaderRow, MatRowDef, MatRow, } from '@angular/material/table'; import { ActivatedRoute, Router } from '@angular/router'; import { round } from 'mathjs'; import moment from 'moment'; import { BehaviorSubject, Observable, of as observableOf } from 'rxjs'; import { debounceTime, distinctUntilChanged, map, switchMap } from 'rxjs/operators'; import { AuthService } from '../auth/auth.service'; import { Account } from '../core/account'; import { AccountBalance } from '../core/account-balance'; import { AccountService } from '../core/account.service'; import { DbFile } from '../core/db-file'; import { Journal } from '../core/journal'; import { Tag } from '../tag/tag'; import { TagService } from '../tag/tag.service'; import { MatSnackBar } from '@angular/material/snack-bar'; import { User } from '../core/user'; import { Voucher } from '../core/voucher'; import { VoucherService } from '../core/voucher.service'; import { AccountingPipe } from '../shared/accounting.pipe'; 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 { LocalTimePipe } from '../shared/local-time.pipe'; import { MathService } from '../shared/math.service'; import { PaymentDataSource } from './payment-datasource'; import { PaymentDialogComponent } from './payment-dialog.component'; @Component({ selector: 'app-payment', templateUrl: './payment.component.html', styleUrls: ['./payment.component.css'], standalone: true, imports: [ MatCard, MatCardHeader, MatCardTitleGroup, MatCardTitle, MatIcon, MatSuffix, MatCardContent, ReactiveFormsModule, MatFormField, MatLabel, MatInput, MatDatepickerInput, MatDatepickerToggle, MatDatepicker, MatSelect, MatOption, MatPrefix, MatAutocompleteTrigger, MatHint, MatAutocomplete, MatButton, MatTable, MatSort, MatColumnDef, MatHeaderCellDef, MatHeaderCell, MatCellDef, MatCell, MatIconButton, MatHeaderRowDef, MatHeaderRow, MatRowDef, MatRow, MatChipGrid, MatChipRow, MatChipRemove, MatChipInput, MatCardActions, AsyncPipe, CurrencyPipe, AccountingPipe, LocalTimePipe, ], }) export class PaymentComponent implements OnInit, AfterViewInit { @ViewChild('accountElement', { static: true }) accountElement!: ElementRef; @ViewChild('dateElement', { static: true }) dateElement!: ElementRef; @ViewChild('tagInput') tagInput?: ElementRef; @HostListener('window:keydown.f2', ['$event']) focusDate(event: KeyboardEvent) { event.preventDefault(); this.dateElement.nativeElement.focus(); this.dateElement.nativeElement.select(); } @HostListener('window:keydown.control.s', ['$event']) saveListner(event: KeyboardEvent) { event.preventDefault(); if (this.canSave()) { this.save(); } } @HostListener('window:keydown.control.p', ['$event']) postListner(event: KeyboardEvent) { event.preventDefault(); if (this.voucher.id && !this.voucher.posted && this.auth.allowed('post-vouchers')) { this.post(); } } separatorKeysCodes: number[] = [ENTER, COMMA]; public journalObservable = new BehaviorSubject([]); dataSource: PaymentDataSource = new PaymentDataSource(this.journalObservable); form: FormGroup<{ date: FormControl; paymentAccount: FormControl; paymentAmount: FormControl; addRow: FormGroup<{ account: FormControl; amount: FormControl; }>; narration: FormControl; tags: FormControl; }>; paymentAccounts: Account[] = []; paymentJournal: Journal = new Journal(); voucher: Voucher = new Voucher(); account: Account | null; accBal: AccountBalance | null = null; displayedColumns = ['account', 'amount', 'action']; accounts: Observable; tags: Observable; constructor( private route: ActivatedRoute, private router: Router, private dialog: MatDialog, private snackBar: MatSnackBar, public auth: AuthService, private math: MathService, public image: ImageService, private ser: VoucherService, private accountSer: AccountService, private tagSer: TagService, ) { this.account = null; this.form = new FormGroup({ date: new FormControl(new Date(), { nonNullable: true }), paymentAccount: new FormControl('', { nonNullable: true }), paymentAmount: new FormControl({ value: 0, disabled: true }, { nonNullable: true }), addRow: new FormGroup({ account: new FormControl(''), amount: new FormControl('', { nonNullable: true }), }), narration: new FormControl('', { nonNullable: true }), tags: new FormControl(''), }); this.accBal = null; // Listen to Account Autocomplete Change this.accounts = this.form.controls.addRow.controls.account.valueChanges.pipe( debounceTime(150), distinctUntilChanged(), switchMap((x) => (x === null ? observableOf([]) : this.accountSer.autocomplete(x))), ); this.tags = this.form.controls.tags.valueChanges.pipe( debounceTime(150), distinctUntilChanged(), map((tag: string | Tag | null) => (tag === null ? '' : typeof tag !== 'string' ? tag.name.toLowerCase() : tag)), switchMap((tag: string) => this.tagSer.autocomplete(tag)), ); // Listen to Payment Account Change this.form.controls.paymentAccount.valueChanges.subscribe((x) => this.router.navigate([], { relativeTo: this.route, queryParams: { a: x }, replaceUrl: true, }), ); } ngOnInit() { this.route.data.subscribe((value) => { const data = value as { voucher: Voucher; paymentAccounts: Account[] }; this.paymentAccounts = data.paymentAccounts; this.loadVoucher(data.voucher); }); } ngAfterViewInit() { this.focusAccount(); } loadVoucher(voucher: Voucher) { this.voucher = voucher; [this.paymentJournal] = this.voucher.journals.filter((x) => x.debit === -1); this.form.setValue({ date: moment(this.voucher.date, 'DD-MMM-YYYY').toDate(), paymentAccount: this.paymentJournal.account.id ?? '', paymentAmount: this.paymentJournal.amount, addRow: { account: '', amount: '', }, narration: this.voucher.narration, tags: '', }); this.dataSource = new PaymentDataSource(this.journalObservable); this.updateView(); } focusAccount() { setTimeout(() => { this.accountElement.nativeElement.focus(); }, 0); } addRow() { const amount = this.math.parseAmount(this.form.value.addRow?.amount ?? '0', 2); const debit = 1; if (this.account === null || amount <= 0) { return; } const oldFiltered = this.voucher.journals.filter((x) => x.account.id === (this.account as Account).id); const old = oldFiltered.length ? oldFiltered[0] : null; if (old && (old.debit === -1 || old.id === this.paymentJournal.id)) { return; } if (old) { old.amount += amount; } else { this.voucher.journals.push( new Journal({ debit, amount, account: this.account, costCentre: null, }), ); } this.resetAddRow(); this.updateView(); } resetAddRow() { this.form.controls.addRow.reset({ account: null, amount: '' }); this.account = null; this.accBal = null; setTimeout(() => { this.accountElement.nativeElement.focus(); }, 0); } updateView() { const journals = this.voucher.journals.filter((x) => x.debit === 1); this.journalObservable.next(journals); this.paymentJournal.amount = round(Math.abs(journals.map((x) => x.amount).reduce((p, c) => p + c, 0)), 2); this.form.controls.paymentAmount.setValue(this.paymentJournal.amount); } editRow(row: Journal) { const dialogRef = this.dialog.open(PaymentDialogComponent, { width: '750px', data: { journal: { ...row }, date: moment(this.form.value.date).format('DD-MMM-YYYY'), }, }); dialogRef.afterClosed().subscribe((result: boolean | Journal) => { if (!result) { return; } const j = result as Journal; if ( j.account.id !== row.account.id && this.voucher.journals.filter((x) => x.account.id === j.account.id).length ) { return; } Object.assign(row, j); this.updateView(); }); } deleteRow(row: Journal) { this.voucher.journals.splice(this.voucher.journals.indexOf(row), 1); this.updateView(); } canSave() { if (!this.voucher.id) { return true; } if (this.voucher.posted && this.auth.allowed('edit-posted-vouchers')) { return true; } return this.voucher.user.id === (this.auth.user as User).id || this.auth.allowed("edit-other-user's-vouchers"); } post() { this.ser.post(this.voucher.id as string).subscribe({ next: (result) => { this.loadVoucher(result); this.snackBar.open('Voucher Posted', 'Success'); }, error: (error) => { this.snackBar.open(error, 'Danger'); }, }); } save() { const voucher: Voucher = this.getVoucher(); this.ser.saveOrUpdate(voucher).subscribe({ next: (result) => { this.snackBar.open('', 'Success'); if (voucher.id === result.id) { this.loadVoucher(result); } else { this.router.navigate(['/payment', result.id]); } }, error: (error) => { this.snackBar.open(error, 'Danger'); }, }); } getVoucher(): Voucher { const formModel = this.form.value; this.voucher.date = moment(formModel.date).format('DD-MMM-YYYY'); this.paymentJournal.account.id = formModel.paymentAccount; this.voucher.narration = formModel.narration ?? ''; return this.voucher; } delete() { this.ser.delete(this.voucher.id as string).subscribe({ next: () => { this.snackBar.open('', 'Success'); this.router.navigate(['/payment'], { replaceUrl: true }); }, error: (error) => { this.snackBar.open(error, 'Danger'); }, }); } 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(); } }); } displayFn(account?: Account | string): string { return !account ? '' : typeof account === 'string' ? account : account.name; } accountSelected(event: MatAutocompleteSelectedEvent): void { const account = event.option.value; this.account = account; const date = moment(this.form.value.date).format('DD-MMM-YYYY'); this.accountSer.balance(account.id as string, date).subscribe((v) => { this.accBal = v; }); } 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); } removeTag(tag: Tag): void { const index = this.voucher.tags.indexOf(tag); if (index >= 0) { this.voucher.tags.splice(index, 1); } } addTag(event: MatChipInputEvent): void { const value = (event.value || '').trim(); // Add our tag if (value) { this.voucher.tags.push(new Tag({ name: value })); } // Clear the input value event.chipInput!.clear(); this.form.controls.tags.setValue(null); } selectedTag(event: MatAutocompleteSelectedEvent): void { const tag = event.option.value as Tag; const index = this.voucher.tags.findIndex((t) => (tag.id === null ? t.name === tag.name : t.id === tag.id)); if (index === -1) { this.voucher.tags.push(tag); } if (this.tagInput) { this.tagInput.nativeElement.value = ''; } this.form.controls.tags.setValue(null); } }