Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | 2x 2x 2x 2x 1x 1x 1x 1x 1x | import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ShoppingFacade } from 'ish-core/facades/shopping.facade';
import { SkuQuantityType } from 'ish-core/models/product/product.model';
declare type CsvStatusType = 'Default' | 'ValidFormat' | 'InvalidFormat' | 'IncorrectInput';
@Component({
selector: 'ish-quickorder-csv-form',
templateUrl: './quickorder-csv-form.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class QuickorderCsvFormComponent implements OnInit {
csvForm: FormGroup;
private productsFromCsv: SkuQuantityType[] = [];
status: CsvStatusType;
constructor(private qf: FormBuilder, private cdRef: ChangeDetectorRef, private shoppingFacade: ShoppingFacade) {}
ngOnInit() {
this.csvForm = this.qf.group({
csvFile: ['', Validators.required],
});
this.status = 'Default';
}
uploadListener(target: EventTarget): void {
const files = (target as HTMLInputElement).files;
this.status = 'Default';
if (this.isValidCSVFile(files[0])) {
const reader = new FileReader();
reader.readAsText(files[0]);
reader.onload = () => {
const csvData = reader.result;
const csvRecordsArray = (csvData as string).split(/\r\n|\n/);
this.productsFromCsv = this.getDataRecordsArrayFromCSVFile(csvRecordsArray);
};
reader.onloadend = () => {
this.status =
this.productsFromCsv.filter(p => p.sku !== '' && p.quantity !== undefined).length !== 0
? 'ValidFormat'
: 'IncorrectInput';
this.cdRef.markForCheck();
};
} else {
this.status = 'InvalidFormat';
}
}
private isValidCSVFile(file: File) {
return file.name.endsWith('.csv');
}
private getDataRecordsArrayFromCSVFile(csvRecordsArray: string[]): SkuQuantityType[] {
try {
return csvRecordsArray
.filter(r => !!r)
.map(record => record.split(/[,;]/))
.map(record => ({
sku: record[0].trim(),
quantity: +record[1].trim(),
}))
.filter(record => !isNaN(record.quantity));
} catch (error) {
this.status = 'IncorrectInput';
return [];
}
}
addCsvToCart() {
Iif (this.status === 'ValidFormat') {
Iif (this.productsFromCsv.length > 0) {
this.productsFromCsv.forEach(product => {
this.shoppingFacade.addProductToBasket(product.sku, product.quantity);
});
}
this.resetCsvProductArray();
}
}
resetCsvProductArray() {
this.productsFromCsv = [];
this.status = 'Default';
}
get isCsvDisabled() {
return this.status !== 'ValidFormat';
}
}
|