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 | 2x 2x 198x 2x 7x 44x 44x 22x 22x 22x 22x 44x 44x 22x 22x 22x 18x 2x 22x 22x 18x 22x 2x 44x 44x 4x | import Papa from "papaparse";
import * as Yup from "yup";
import { TImportedRow } from "../types";
import { COLUMN_NAMES } from "../constants";
import { MERCHANT_NAME_SANITIZE_REGEX } from "@validation/regex";
const emailValidator = Yup.string().email();
const getCorrectString = (word?: string | number) =>
typeof word === "string" ? word.toLocaleLowerCase().trim() : word;
export const parseCsv = (
file: File,
onError: VoidFunction,
onStep: (el: TImportedRow) => void,
onComplete: VoidFunction,
) =>
Papa.parse(file, {
skipEmptyLines: true,
header: true,
dynamicTyping: true,
transform: (value, field) => {
const filedName = getCorrectString(field);
if (filedName === getCorrectString(COLUMN_NAMES[0])) {
return validateWithExceptions(value, validators[COLUMN_NAMES[0]]);
} else if (filedName === getCorrectString(COLUMN_NAMES[1])) {
return validateWithExceptions(value, validators[COLUMN_NAMES[1]]);
} else E{
return value;
}
},
error: (error) => {
if (error) onError();
},
step: ({ data, errors }) => {
// Cast data to an object to remove the "unknown" type error
const normalizedData = Object.keys(data as Record<string, any>).reduce(
(acc, key) => {
acc[getCorrectString(key) as string] = (data as Record<string, any>)[
key
];
return acc;
},
{} as Record<string, any>,
);
const merchantName =
normalizedData?.[getCorrectString(COLUMN_NAMES[1]) as string] || "";
const pahEmail =
normalizedData?.[getCorrectString(COLUMN_NAMES[0]) as string] || "";
if (errors.length === 0 && (merchantName || pahEmail)) {
onStep({ merchantName, pahEmail });
}
},
complete: onComplete,
});
type Validator = (value: string) => void;
type FieldValidators = Record<(typeof COLUMN_NAMES)[number], Validator>;
const validators: FieldValidators = {
[COLUMN_NAMES[0]]: (value) => {
const val = value.trim().toLowerCase();
emailValidator.validateSync(val);
return val;
},
[COLUMN_NAMES[1]]: (value) => {
return value
.trim()
.replace(MERCHANT_NAME_SANITIZE_REGEX, "")
.replace(/\s+/g, " ");
},
};
const validateWithExceptions = (value: string, validator: Validator) => {
try {
return validator(value);
} catch (err) {
return "";
}
};
|