Files
brewman/overlord/src/app/payment/payment-dialog.component.ts
T

77 lines
2.5 KiB
TypeScript

import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Observable, of as observableOf } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, switchMap } from 'rxjs/operators';
import { Account } from '../core/account';
import { AccountBalance } from '../core/account-balance';
import { AccountService } from '../core/account.service';
import { Journal } from '../core/journal';
import { MathService } from '../shared/math.service';
@Component({
selector: 'app-payment-dialog',
templateUrl: './payment-dialog.component.html',
styleUrls: ['./payment-dialog.component.css'],
})
export class PaymentDialogComponent implements OnInit {
accounts: Observable<Account[]>;
form: FormGroup<{
account: FormControl<string | null>;
amount: FormControl<string>;
}>;
account: Account = new Account();
accBal: AccountBalance | null = null;
constructor(
public dialogRef: MatDialogRef<PaymentDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: { journal: Journal; date: string },
private math: MathService,
private accountSer: AccountService,
) {
this.form = new FormGroup({
account: new FormControl(''),
amount: new FormControl('', { nonNullable: true }),
});
this.accBal = null;
// Setup Account Autocomplete
this.accounts = this.form.controls.account.valueChanges.pipe(
map((x) => (x !== null && x.length >= 1 ? x : null)),
debounceTime(150),
distinctUntilChanged(),
switchMap((x) => (x === null ? observableOf([]) : this.accountSer.autocomplete(x))),
);
}
ngOnInit() {
this.form.setValue({
account: this.data.journal.account.name,
amount: `${this.data.journal.amount}`,
});
this.account = this.data.journal.account;
}
displayFn(account?: Account): string {
return account ? account.name : '';
}
accountSelected(event: MatAutocompleteSelectedEvent): void {
const account = event.option.value;
this.account = account;
this.accountSer.balance(account.id as string, this.data.date).subscribe((v) => {
this.accBal = v;
});
}
accept(): void {
const formValue = this.form.value;
const amount = this.math.parseAmount(formValue.amount, 2);
this.data.journal.account = this.account;
this.data.journal.amount = amount;
this.dialogRef.close(this.data.journal);
}
}