Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(account-settings): refactor formValidation, updateAccountSettings & dataProcessing #242

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 38 additions & 52 deletions apps/storefront/src/pages/AccountSetting/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,47 +18,15 @@ export interface GetFilterMoreListProps {
size: string;
}

interface GetAccountSettingFilesReturnProps {
accountB2BFormFields: GetFilterMoreListProps[];
passwordModified: GetFilterMoreListProps[];
}

interface PasswordKeysProps {
name: string;
label: string;
idLang: string;
}

export const getPasswordKeys = (): PasswordKeysProps[] => [
{
name: 'currentPassword',
label: 'Current Password',
idLang: 'accountSettings.form.currentPassword',
},
{
name: 'password',
label: 'Password',
idLang: 'accountSettings.form.password',
},
{
name: 'confirmPassword',
label: 'Confirm Password',
idLang: 'accountSettings.form.confirmPassword',
},
];

export const getAccountSettingFiles = (
xs: number,
b3Lang: LangFormatFunction,
): GetAccountSettingFilesReturnProps => {
const accountB2BFormFields = [
export const getAccountSettingsFields = (b3Lang: LangFormatFunction): GetFilterMoreListProps[] => {
return [
{
name: 'company',
label: b3Lang('accountSettings.form.company'),
required: false,
default: '',
fieldType: 'text',
xs,
xs: 12,
variant: 'filled',
size: 'small',
},
Expand Down Expand Up @@ -86,26 +54,44 @@ export const getAccountSettingFiles = (
value: 3,
},
],
xs,
xs: 12,
variant: 'filled',
size: 'small',
},
];
};

const passwordModified = getPasswordKeys().map((item: PasswordKeysProps) => ({
name: item.name,
label: item.label,
required: false,
default: '',
fieldType: 'password',
xs,
variant: 'filled',
size: 'small',
idLang: item.idLang,
}));

return {
accountB2BFormFields,
passwordModified,
};
export const getPasswordModifiedFields = (b3Lang: LangFormatFunction): GetFilterMoreListProps[] => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any benefit in turning these into a hooks and getting b3Lang internally rather than by argument?

return [
{
name: 'currentPassword',
label: b3Lang('accountSettings.form.currentPassword'),
required: false,
default: '',
fieldType: 'password',
xs: 12,
variant: 'filled',
size: 'small',
},
{
name: 'password',
label: b3Lang('accountSettings.form.password'),
required: false,
default: '',
fieldType: 'password',
xs: 12,
variant: 'filled',
size: 'small',
},
{
name: 'confirmPassword',
label: b3Lang('accountSettings.form.confirmPassword'),
required: false,
default: '',
fieldType: 'password',
xs: 12,
variant: 'filled',
size: 'small',
},
];
};
199 changes: 91 additions & 108 deletions apps/storefront/src/pages/AccountSetting/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { B3SStorage, channelId, snackbar } from '@/utils';

import { deCodeField, getAccountFormFields } from '../Registered/config';

import { getAccountSettingFiles } from './config';
import { getAccountSettingsFields, getPasswordModifiedFields } from './config';
import { b2bSubmitDataProcessing, bcSubmitDataProcessing, initB2BInfo, initBcInfo } from './utils';

function useData() {
Expand All @@ -40,11 +40,42 @@ function useData() {
const companyId = role === 3 && isAgenting ? Number(salesRepCompanyId) : Number(companyInfoId);
const isBCUser = !isB2BUser || (role === 3 && !isAgenting);

return { isBCUser, companyId, customer };
const validateEmailValue = async (emailValue: string) => {
if (customer.emailAddress === trim(emailValue)) return true;
const payload = {
email: emailValue,
channelId,
};

const { isValid }: { isValid: boolean } = isBCUser
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the type definition { isValid: boolean } here because the async functions are giving back any?

If so, I'd be tempted to move it closer to the problem by adding it as a return type definition of their signatures
(rather than make this function make up for their shortcomings)

? await checkUserBCEmail(payload)
: await checkUserEmail(payload);

return isValid;
};

const emailValidation = (data: Partial<ParamProps>) => {
if (data.email !== customer.emailAddress && !data.currentPassword) {
return false;
}

return true;
};

const passwordValidation = (data: Partial<ParamProps>) => {
if (data.password !== data.confirmPassword) {
return false;
}

return true;
};

return { isBCUser, companyId, customer, validateEmailValue, emailValidation, passwordValidation };
}

function AccountSetting() {
const { isBCUser, companyId, customer } = useData();
const { isBCUser, companyId, customer, validateEmailValue, emailValidation, passwordValidation } =
useData();

const {
control,
Expand Down Expand Up @@ -87,24 +118,22 @@ function AccountSetting() {
try {
setLoading(true);

const accountFormAllFields = await getB2BAccountFormFields(isBCUser ? 1 : 2);

const fn = !isBCUser ? getB2BAccountSettings : getBCAccountSettings;
const fn = isBCUser ? getBCAccountSettings : getB2BAccountSettings;

const params = !isBCUser
? {
const params = isBCUser
? {}
: {
companyId,
}
: {};
};

const key = !isBCUser ? 'accountSettings' : 'customerAccountSettings';
const key = isBCUser ? 'customerAccountSettings' : 'accountSettings';

const { [key]: accountSettings } = await fn(params);

const accountFormAllFields = await getB2BAccountFormFields(isBCUser ? 1 : 2);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"how many fields do you want? One, two..?" 😆

const accountFormFields = getAccountFormFields(
accountFormAllFields.accountFormFields || [],
);
const { accountB2BFormFields, passwordModified } = getAccountSettingFiles(12, b3Lang);

const contactInformation = (accountFormFields?.contactInformation || []).filter(
(item: Partial<Fields>) => item.fieldId !== 'field_email_marketing_newsletter',
Expand Down Expand Up @@ -132,25 +161,18 @@ function AccountSetting() {

const { additionalInformation = [] } = accountFormFields;

const fields = !isBCUser
? initB2BInfo(
const fields = isBCUser
? initBcInfo(accountSettings, contactInformationTranslatedLabels, additionalInformation)
: initB2BInfo(
accountSettings,
contactInformationTranslatedLabels,
accountB2BFormFields,
getAccountSettingsFields(b3Lang),
additionalInformation,
)
: initBcInfo(accountSettings, contactInformationTranslatedLabels, additionalInformation);
);

const passwordModifiedTranslatedFields = JSON.parse(JSON.stringify(passwordModified)).map(
(element: { label: string; idLang: string }) => {
const passwordField = element;
passwordField.label = b3Lang(element.idLang);

return element;
},
);
const passwordModifiedFields = getPasswordModifiedFields(b3Lang);

const all = [...fields, ...passwordModifiedTranslatedFields];
const all = [...fields, ...passwordModifiedFields];

const roleItem = all.find((item) => item.name === 'role');

Expand Down Expand Up @@ -178,64 +200,17 @@ function AccountSetting() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const validateEmailValue = async (emailValue: string) => {
if (customer.emailAddress === trim(emailValue)) return true;
const payload = {
email: emailValue,
channelId,
};

const { isValid }: CustomFieldItems = isBCUser
? await checkUserBCEmail(payload)
: await checkUserEmail(payload);

if (!isValid) {
setError('email', {
type: 'custom',
message: b3Lang('accountSettings.notification.emailExists'),
});
}

return isValid;
};

const passwordValidation = (data: Partial<ParamProps>) => {
if (data.password !== data.confirmPassword) {
setError('confirmPassword', {
type: 'manual',
message: b3Lang('global.registerComplete.passwordMatchPrompt'),
});
setError('password', {
type: 'manual',
message: b3Lang('global.registerComplete.passwordMatchPrompt'),
});
return false;
}

return true;
};

const emailValidation = (data: Partial<ParamProps>) => {
if (data.email !== customer.emailAddress && !data.currentPassword) {
snackbar.error(b3Lang('accountSettings.notification.updateEmailPassword'));
return false;
}
return true;
};

const handleGetUserExtraFields = (data: CustomFieldItems) => {
let userExtraFieldsInfo: CustomFieldItems[] = [];
const handleGetUserExtraFields = (
data: CustomFieldItems,
accountInfoFormFields: Partial<Fields>[],
) => {
const userExtraFields = accountInfoFormFields.filter(
(item: CustomFieldItems) => item.custom && item.groupId === 1,
);
if (userExtraFields.length > 0) {
userExtraFieldsInfo = userExtraFields.map((item: CustomFieldItems) => ({
fieldName: deCodeField(item?.name || ''),
fieldValue: data[item.name],
}));
}

return userExtraFieldsInfo;
return userExtraFields.map((item: CustomFieldItems) => ({
fieldName: deCodeField(item?.name || ''),
fieldValue: data[item.name],
}));
};

const handleAddUserClick = () => {
Expand All @@ -245,48 +220,56 @@ function AccountSetting() {
try {
const isValid = await validateEmailValue(data.email);

if (!isValid) {
setError('email', {
type: 'custom',
message: b3Lang('accountSettings.notification.emailExists'),
});
}

const emailFlag = emailValidation(data);

if (!emailFlag) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these flag names aren't very descriptive, what do you think to turning them into something like

if (isValidEmail(data.email)) { 
    // etc

in another commit/PR/ticket?

snackbar.error(b3Lang('accountSettings.notification.updateEmailPassword'));
}

const passwordFlag = passwordValidation(data);

let userExtraFields: CustomFieldItems[] = [];
if (!isBCUser) {
userExtraFields = handleGetUserExtraFields(data);
if (!passwordFlag) {
setError('confirmPassword', {
type: 'manual',
message: b3Lang('global.registerComplete.passwordMatchPrompt'),
});
setError('password', {
type: 'manual',
message: b3Lang('global.registerComplete.passwordMatchPrompt'),
});
}

const dataProcessingFn = !isBCUser ? b2bSubmitDataProcessing : bcSubmitDataProcessing;

if (isValid && emailFlag && passwordFlag) {
const { isEdit, param } = dataProcessingFn(
data,
accountSettings,
decryptionFields,
extraFields,
);

if (isEdit) {
const dataProcessingFn = isBCUser ? bcSubmitDataProcessing : b2bSubmitDataProcessing;
const payload = dataProcessingFn(data, accountSettings, decryptionFields, extraFields);

if (payload) {
if (!isBCUser) {
param.companyId = companyId;
param.extraFields = userExtraFields;
payload.companyId = companyId;
payload.extraFields = handleGetUserExtraFields(data, accountInfoFormFields);
}

const requestFn = !isBCUser ? updateB2BAccountSettings : updateBCAccountSettings;

const newParams: CustomFieldItems = {
...param,
currentPassword: param.currentPassword,
};

if (param.newPassword === '' && param.confirmPassword === '') {
delete newParams.newPassword;
delete newParams.confirmPassword;
if (payload.newPassword === '' && payload.confirmPassword === '') {
delete payload.newPassword;
delete payload.confirmPassword;
}
await requestFn(newParams);
} else {
}

if (!payload) {
snackbar.success(b3Lang('accountSettings.notification.noEdits'));
return;
}

const requestFn = isBCUser ? updateBCAccountSettings : updateB2BAccountSettings;
await requestFn(payload);

if (
(data.password && data.currentPassword) ||
customer.emailAddress !== trim(data.email)
Expand Down
Loading