Skip to content

Commit

Permalink
fix: refactor on code review feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
mirovladimitrovski committed Oct 5, 2023
1 parent c0d9629 commit 9b6fc6b
Show file tree
Hide file tree
Showing 9 changed files with 28 additions and 38 deletions.
17 changes: 5 additions & 12 deletions src/components/Account/Account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useMutation } from 'react-query';

import styles from './Account.module.scss';

import { isTruthyCustomParamValue, isTruthy, logDev } from '#src/utils/common';
import type { FormSectionContentArgs, FormSectionProps } from '#components/Form/FormSection';
import type { Consent } from '#types/account';
import Alert from '#components/Alert/Alert';
Expand All @@ -20,10 +21,9 @@ import Checkbox from '#components/Checkbox/Checkbox';
import HelperText from '#components/HelperText/HelperText';
import CustomRegisterField from '#components/CustomRegisterField/CustomRegisterField';
import useToggle from '#src/hooks/useToggle';
import { formatConsentsFromValues, formatConsents, formatConsentValues, isNotEmptyStringEntry, formatCrfEntry } from '#src/utils/collection';
import { formatConsentsFromValues, formatConsents, formatConsentValues } from '#src/utils/collection';
import { addQueryParam } from '#src/utils/location';
import { useAccountStore } from '#src/stores/AccountStore';
import { isTruthy, logDev } from '#src/utils/common';
import { exportAccountData, updateConsents, updateUser } from '#src/stores/AccountController';

type Props = {
Expand Down Expand Up @@ -262,17 +262,14 @@ const Account = ({ panelClassName, panelHeaderClassName, canUpdateEmail = true }
formSection({
label: t('account.terms_and_tracking'),
saveButton: t('account.update_consents'),
onSubmit: (values) => {
const cleanConsentValues = Object.fromEntries(Object.entries(values.consentsValues).filter(isNotEmptyStringEntry).map(formatCrfEntry));
return updateConsents(formatConsentsFromValues(publisherConsents, { ...cleanConsentValues, terms: true }), cleanConsentValues);
},
onSubmit: (values) => updateConsents(formatConsentsFromValues(publisherConsents, { ...values.consentsValues, terms: true })),
content: (section) => (
<>
{termsConsents?.map((consent, index) => (
<Checkbox
key={index}
name={`consentsValues.${consent.name}`}
checked={[true, 'on'].includes(section.values.consentsValues?.[consent.name])}
checked={isTruthyCustomParamValue(section.values.consentsValues?.[consent.name])}
onChange={section.onChange}
label={formatConsentLabel(consent.label)}
disabled={consent.required || section.isBusy}
Expand All @@ -285,11 +282,7 @@ const Account = ({ panelClassName, panelHeaderClassName, canUpdateEmail = true }
formSection({
label: t('account.other_registration_details'),
saveButton: t('account.update_consents'),
onSubmit: (values) => {
const cleanConsentValues = Object.fromEntries(Object.entries(values.consentsValues).filter(isNotEmptyStringEntry).map(formatCrfEntry));
return updateConsents(formatConsentsFromValues(publisherConsents, cleanConsentValues), cleanConsentValues);
},

onSubmit: (values) => updateConsents(formatConsentsFromValues(publisherConsents, values.consentsValues)),
content: (section) => (
<div className={styles.customFields}>
{nonTermsConsents.map((consent) => (
Expand Down
3 changes: 2 additions & 1 deletion src/components/CustomRegisterField/CustomRegisterField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import type { GetRegisterFieldOption } from '@inplayer-org/inplayer.js';

import type { CustomRegisterFieldVariant } from '#types/account';
import { isTruthyCustomParamValue } from '#src/utils/common';
import Checkbox from '#components/Checkbox/Checkbox';
import TextField from '#components/TextField/TextField';
import Radio from '#components/Radio/Radio';
Expand Down Expand Up @@ -62,7 +63,7 @@ export const CustomRegisterField: FC<Props> = ({ type, value = '', ...props }) =
case 'datepicker':
return <DateField {...props} value={value as string} />;
default:
return <Checkbox {...props} checked={[true, 'on'].includes(value)} />;
return <Checkbox {...props} checked={isTruthyCustomParamValue(value)} />;
}
};

Expand Down
6 changes: 1 addition & 5 deletions src/containers/AccountModal/forms/PersonalDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { mixed, object, string } from 'yup';
import { useQuery } from 'react-query';

import { useConfigStore } from '#src/stores/ConfigStore';
import { useAccountStore } from '#src/stores/AccountStore';
import useForm, { UseFormOnSubmitHandler } from '#src/hooks/useForm';
import PersonalDetailsForm from '#components/PersonalDetailsForm/PersonalDetailsForm';
import LoadingOverlay from '#components/LoadingOverlay/LoadingOverlay';
Expand All @@ -24,7 +23,6 @@ const PersonalDetails = () => {
const { t } = useTranslation('account');
const accessModel = useConfigStore((s) => s.accessModel);
const { data, isLoading } = useQuery('captureStatus', () => getCaptureStatus());
const { user } = useAccountStore();
const { hasTVODOffers } = useOffers();
const [questionValues, setQuestionValues] = useState<Record<string, string>>({});
const [questionErrors, setQuestionErrors] = useState<Record<string, string>>({});
Expand Down Expand Up @@ -120,9 +118,7 @@ const PersonalDetails = () => {
} as CaptureCustomAnswer),
);

const metadata = removeEmpty({ ...user?.metadata });

await updateCaptureAnswers(removeEmpty({ ...formData, customAnswers, metadata }));
await updateCaptureAnswers(removeEmpty({ ...formData, customAnswers }));

nextStep();
} catch (error: unknown) {
Expand Down
6 changes: 3 additions & 3 deletions src/containers/AccountModal/forms/Registration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useQuery, useQueryClient } from 'react-query';

import useForm, { UseFormOnSubmitHandler } from '#src/hooks/useForm';
import RegistrationForm from '#components/RegistrationForm/RegistrationForm';
import { extractConsentValues, checkConsentsFromValues, isNotEmptyStringEntry, formatCrfEntry } from '#src/utils/collection';
import { extractConsentValues, checkConsentsFromValues, formatConsentsToRegisterFields } from '#src/utils/collection';
import { addQueryParam } from '#src/utils/location';
import type { RegistrationFormData } from '#types/account';
import { getPublisherConsents, register, updateConsents } from '#src/stores/AccountController';
Expand Down Expand Up @@ -57,11 +57,11 @@ const Registration = () => {
return;
}

const cleanConsentValues = Object.fromEntries(Object.entries(consentValues).filter(isNotEmptyStringEntry).map(formatCrfEntry));
const cleanConsentValues = formatConsentsToRegisterFields(customerConsents);

await register(email, password, cleanConsentValues);

await updateConsents(customerConsents, cleanConsentValues).catch(() => {
await updateConsents(customerConsents).catch(() => {
// error caught while updating the consents, but continue the registration flow
});

Expand Down
9 changes: 5 additions & 4 deletions src/services/inplayer.account.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import InPlayer, { AccountData, Env, FavoritesData, UpdateAccountData, WatchHistory } from '@inplayer-org/inplayer.js';
import i18next from 'i18next';

import { formatConsentsToRegisterFields } from '#src/utils/collection';
import { getCommonResponseData } from '#src/utils/api';
import type { Config } from '#types/Config';
import type {
Expand Down Expand Up @@ -211,15 +212,15 @@ export const getCustomerConsents: GetCustomerConsents = async (payload) => {

export const updateCustomerConsents: UpdateCustomerConsents = async (payload) => {
try {
const { customer, consents, consentValues } = payload;
const { customer, consents } = payload;

const existingAccountData = formatUpdateAccount(customer);

const params = {
...existingAccountData,
metadata: {
...existingAccountData.metadata,
...consentValues,
...formatConsentsToRegisterFields(consents),
consents: JSON.stringify(consents),
},
};
Expand Down Expand Up @@ -255,8 +256,8 @@ export const getCaptureStatus: GetCaptureStatus = async ({ customer }) => {
};
};

export const updateCaptureAnswers: UpdateCaptureAnswers = async ({ ...metadata }) => {
return (await updateCustomer(metadata, true)) as ServiceResponse<Capture>;
export const updateCaptureAnswers: UpdateCaptureAnswers = async ({ customer, ...newAnswers }) => {
return (await updateCustomer({ ...customer, ...newAnswers }, true)) as ServiceResponse<Capture>;
};

export const changePasswordWithOldPassword: ChangePasswordWithOldPassword = async (payload) => {
Expand Down
6 changes: 1 addition & 5 deletions src/stores/AccountController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,7 @@ export const updatePersonalShelves = async () => {
});
};

export const updateConsents = async (
customerConsents: CustomerConsent[],
consentValues: Record<string, string | boolean>,
): Promise<ServiceResponse<CustomerConsent[]>> => {
export const updateConsents = async (customerConsents: CustomerConsent[]): Promise<ServiceResponse<CustomerConsent[]>> => {
return await useAccount(async ({ customer }) => {
return await useService(async ({ accountService, config }) => {
useAccountStore.setState({ loading: true });
Expand All @@ -241,7 +238,6 @@ export const updateConsents = async (
config,
customer,
consents: customerConsents,
consentValues,
});

if (response?.consents) {
Expand Down
14 changes: 9 additions & 5 deletions src/utils/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,12 @@ const checkConsentsFromValues = (publisherConsents: Consent[], consents: Record<
return { customerConsents, consentsErrors };
};

const isNotEmptyStringEntry = <T>([, value]: [string, T]) => value !== '';
const isNotEmptyConsent = (consent: CustomerConsent) => consent.value !== '';

const formatCrfEntry = <T>([name, value]: [string, T], _: number, collection: [string, T][]) => {
const formatConsentToRegisterField = ({ name, value = '' }: CustomerConsent, _: number, collection: CustomerConsent[]) => {
const val = (() => {
if (name === 'us_state') {
if (Object.fromEntries(collection).country === 'us') {
if (collection.find(({ name, value }) => name === 'country' && value === 'us')) {
return value === 'n/a' ? '' : value;
}

Expand All @@ -166,6 +166,9 @@ const formatCrfEntry = <T>([name, value]: [string, T], _: number, collection: [s
return [name, val] as const;
};

const formatConsentsToRegisterFields = (consents: CustomerConsent[]) =>
Object.fromEntries(consents.filter(isNotEmptyConsent).map(formatConsentToRegisterField));

const deepCopy = (obj: unknown) => {
if (Array.isArray(obj) || (typeof obj === 'object' && obj !== null)) {
return JSON.parse(JSON.stringify(obj));
Expand Down Expand Up @@ -201,6 +204,7 @@ export {
deepCopy,
parseAspectRatio,
parseTilesDelta,
isNotEmptyStringEntry,
formatCrfEntry,
isNotEmptyConsent,
formatConsentToRegisterField,
formatConsentsToRegisterFields,
};
4 changes: 2 additions & 2 deletions src/utils/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ export function getOverrideIP() {
.trim();
}

export const isTruthyCustomParamValue = (value: unknown): boolean => ['true', '1', 'yes'].includes(String(value)?.toLowerCase());
export const isTruthyCustomParamValue = (value: unknown): boolean => ['true', '1', 'yes', 'on'].includes(String(value)?.toLowerCase());

export const isFalsyCustomParamValue = (value: unknown): boolean => ['false', '0', 'no'].includes(String(value)?.toLowerCase());
export const isFalsyCustomParamValue = (value: unknown): boolean => ['false', '0', 'no', 'off'].includes(String(value)?.toLowerCase());

export function testId(value: string | undefined) {
return IS_DEVELOPMENT_BUILD || IS_TEST_MODE || IS_PREVIEW_MODE ? value : undefined;
Expand Down
1 change: 0 additions & 1 deletion types/account.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,6 @@ export type UpdateCustomerConsentsArgs = {
config: Config;
customer: Customer;
consents: CustomerConsent[];
consentValues: Record<string, string | boolean>;
};

export type LocalesData = {
Expand Down

0 comments on commit 9b6fc6b

Please sign in to comment.