64 lines
2.0 KiB
TypeScript
64 lines
2.0 KiB
TypeScript
import { Component, Inject } from '@angular/core';
|
|
import { FormArray, FormBuilder, 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';
|
|
|
|
@Component({
|
|
selector: 'app-modifiers',
|
|
templateUrl: './discount.component.html',
|
|
styleUrls: ['./discount.component.css'],
|
|
})
|
|
export class DiscountComponent {
|
|
list: { name: string; discount: number; discountLimit: number }[] = [];
|
|
form: FormGroup;
|
|
dataSource: DiscountDataSource = new DiscountDataSource([]);
|
|
|
|
displayedColumns = ['name', 'discount'];
|
|
|
|
constructor(
|
|
public dialogRef: MatDialogRef<DiscountComponent>,
|
|
private fb: FormBuilder,
|
|
@Inject(MAT_DIALOG_DATA)
|
|
public data: Observable<{ name: string; discount: number; discountLimit: number }[]>,
|
|
) {
|
|
this.form = this.fb.group({
|
|
discounts: '',
|
|
});
|
|
this.data.subscribe((list: { name: string; discount: number; discountLimit: number }[]) => {
|
|
this.list = list;
|
|
this.form.setControl(
|
|
'discounts',
|
|
this.fb.array(
|
|
this.list.map((x) =>
|
|
this.fb.group({
|
|
name: [x.name],
|
|
discount: ['', [Validators.min(0), Validators.max(x.discountLimit * 100)]],
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
this.dataSource = new DiscountDataSource(list);
|
|
});
|
|
}
|
|
|
|
accept(): void {
|
|
const array = this.form.get('discounts') as FormArray;
|
|
for (let i = this.list.length - 1; i >= 0; i--) {
|
|
const item = this.list[i];
|
|
const control = (array.controls[i] as FormGroup).controls.discount as FormControl;
|
|
if (control.pristine || control.value === null) {
|
|
this.list.splice(i, 1);
|
|
} else {
|
|
item.discount = Math.max(
|
|
Math.min(round(array.controls[i].value.discount / 100, 5), item.discountLimit),
|
|
0,
|
|
);
|
|
}
|
|
}
|
|
this.dialogRef.close(this.list);
|
|
}
|
|
}
|