77 lines
2.2 KiB
TypeScript
77 lines
2.2 KiB
TypeScript
import { Component, Inject } from '@angular/core';
|
|
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
|
|
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
|
|
import { round } from 'mathjs';
|
|
import { Observable } from 'rxjs';
|
|
|
|
import { DiscountDataSource } from './discount-datasource';
|
|
import { DiscountItem } from './discount-item';
|
|
|
|
@Component({
|
|
selector: 'app-modifiers',
|
|
templateUrl: './discount.component.html',
|
|
styleUrls: ['./discount.component.css'],
|
|
})
|
|
export class DiscountComponent {
|
|
list: DiscountItem[] = [];
|
|
form: FormGroup<{
|
|
discounts: FormArray<
|
|
FormGroup<{
|
|
name: FormControl<string>;
|
|
discount: FormControl<number>;
|
|
}>
|
|
>;
|
|
}>;
|
|
|
|
dataSource: DiscountDataSource = new DiscountDataSource([]);
|
|
|
|
displayedColumns = ['name', 'discount'];
|
|
|
|
constructor(
|
|
public dialogRef: MatDialogRef<DiscountComponent>,
|
|
@Inject(MAT_DIALOG_DATA)
|
|
public data: Observable<DiscountItem[]>,
|
|
) {
|
|
this.form = new FormGroup({
|
|
discounts: new FormArray<
|
|
FormGroup<{
|
|
name: FormControl<string>;
|
|
discount: FormControl<number>;
|
|
}>
|
|
>([]),
|
|
});
|
|
|
|
this.data.subscribe((list: DiscountItem[]) => {
|
|
this.list = list;
|
|
this.form.controls.discounts.clear();
|
|
|
|
this.list.forEach((x) =>
|
|
this.form.controls.discounts.push(
|
|
new FormGroup({
|
|
name: new FormControl(x.name, { nonNullable: true }),
|
|
discount: new FormControl(x.discount * 100, {
|
|
validators: [Validators.min(0), Validators.max(x.limit * 100)],
|
|
nonNullable: true,
|
|
}),
|
|
}),
|
|
),
|
|
),
|
|
(this.dataSource = new DiscountDataSource(this.list));
|
|
});
|
|
}
|
|
|
|
accept(): void {
|
|
const array = this.form.controls.discounts;
|
|
for (let i = this.list.length - 1; i >= 0; i--) {
|
|
const item = this.list[i];
|
|
const control = array.controls[i].controls.discount;
|
|
if (control.pristine && control.value === 0) {
|
|
this.list.splice(i, 1);
|
|
} else {
|
|
item.discount = Math.max(Math.min(round(control.value / 100, 5), item.limit), 0);
|
|
}
|
|
}
|
|
this.dialogRef.close(this.list);
|
|
}
|
|
}
|