@malga-checkout-full/core
Version:
Core components for Malga Checkout Full
63 lines (62 loc) • 2.53 kB
JavaScript
import { cleanTextOnlyNumbers } from '@malga-checkout/utils';
import { t } from '@malga-checkout/i18n';
import { isCNPJ, isCPF } from 'brazilian-values';
export const normalizeValidationErrors = (errors) => {
const normalizedErrors = errors.reduce((accumulatorErrors, currentError) => (Object.assign(Object.assign({}, accumulatorErrors), { [currentError.path]: currentError.message })), {});
return normalizedErrors;
};
export const getIdentificationMask = (isBrazilianDocument, documentType, identification) => {
const normalizedIdentification = cleanTextOnlyNumbers(identification);
if (!normalizedIdentification || !isBrazilianDocument || !documentType) {
return '';
}
const cnpjMask = '99.999.999/9999-99';
const cpfMask = '999.999.999-99';
const mask = documentType === 'cpf' ? cpfMask : cnpjMask;
return mask;
};
export const validAddressAutocomplete = (address) => {
const parsedAddress = Object.entries(address);
const filteredAddress = parsedAddress.filter(([, value]) => value);
const reducedAddress = filteredAddress.reduce((accumulator, [field]) => (Object.assign(Object.assign({}, accumulator), { [field]: undefined })), {});
return reducedAddress;
};
export const handleCpfOrCnpjInvalidMessage = (number, locale, documentType) => {
const cleaned = cleanTextOnlyNumbers(number);
if (cleaned.length < 11) {
return t('page.customer.fields.identification.errorInvalidNationalDocument', locale);
}
if (documentType) {
if (documentType === 'cpf') {
if (cleaned.length !== 11) {
return t('page.customer.fields.identification.errorMessageInvalidCpf', locale);
}
if (!isCPF(cleaned)) {
return t('page.customer.fields.identification.errorMessageInvalidCpf', locale);
}
return '';
}
if (documentType === 'cnpj') {
if (cleaned.length !== 14) {
return t('page.customer.fields.identification.errorMessageInvalidCnpj', locale);
}
if (!isCNPJ(cleaned)) {
return t('page.customer.fields.identification.errorMessageInvalidCnpj', locale);
}
return '';
}
}
if (cleaned.length === 11) {
if (!isCPF(cleaned)) {
return t('page.customer.fields.identification.errorMessageInvalidCpf', locale);
}
return '';
}
if (cleaned.length === 14) {
if (!isCNPJ(cleaned)) {
return t('page.customer.fields.identification.errorMessageInvalidCnpj', locale);
}
return '';
}
return t('page.customer.fields.identification.errorInvalidNationalDocument', locale);
};