Skip to content

Commit

Permalink
Merge pull request #239 from nada-deriv/nada/advert-issues
Browse files Browse the repository at this point in the history
fix: save changes button, something went wrong, you've created popup
  • Loading branch information
farrah-deriv authored Aug 2, 2024
2 parents 57b1153 + d63b7f2 commit 9321cd1
Show file tree
Hide file tree
Showing 12 changed files with 84 additions and 85 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useCallback, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { MY_ADS_URL } from '@/constants';
import { api } from '@/hooks';
import useInvalidateQuery from '@/hooks/api/useInvalidateQuery';
import { Localize } from '@deriv-com/translations';
import { Button, Checkbox, Modal, Text, useDevice } from '@deriv-com/ui';
Expand All @@ -10,14 +9,12 @@ import './AdCreateEditSuccessModal.scss';

export type TAdCreateEditSuccessModalProps = {
advertsArchivePeriod?: number;
data: ReturnType<typeof api.advert.useCreate>['data'] | ReturnType<typeof api.advert.useUpdate>['data'];
isModalOpen: boolean;
onRequestClose: () => void;
};

const AdCreateEditSuccessModal = ({
advertsArchivePeriod,
data,
isModalOpen,
onRequestClose,
}: TAdCreateEditSuccessModalProps) => {
Expand All @@ -32,16 +29,8 @@ const AdCreateEditSuccessModal = ({

const onClickOk = () => {
LocalStorageUtils.setValue<boolean>(LocalStorageConstants.p2pArchiveMessage, isChecked);
if (data?.visibility_status && data?.account_currency && data.max_order_amount_limit_display) {
history.push(MY_ADS_URL, {
currency: data.account_currency,
from: '',
limit: data.max_order_amount_limit_display,
visibilityStatus: data.visibility_status[0],
});
} else {
history.push(MY_ADS_URL);
}
history.push(MY_ADS_URL);

invalidate('p2p_advertiser_adverts');
onRequestClose();
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@

@include mobile-or-tablet-screen {
height: unset;
max-height: calc(100vh - 28rem);
max-height: calc(100% - 28rem);
}

&--no-footer {
height: 44rem;
@include mobile-or-tablet-screen {
height: 100vh;
height: 100%;
max-height: unset;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
left: 0;
background: #fff;
z-index: 1;
height: calc(100vh - 7.5rem);
height: calc(100% - 7.5rem);

& .mobile-wrapper {
&__header {
Expand Down
6 changes: 4 additions & 2 deletions src/components/PaymentMethodCard/PaymentMethodCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,13 @@ const PaymentMethodCard = ({
})}
>
{!toAdd ? (
<div className='flex flex-col items-center justify-center w-full h-full'>
<div
className='flex flex-col items-center justify-center w-full h-full'
onClick={() => onClickAdd?.(paymentMethod)}
>
<Button
className='flex items-center justify-center w-[3.2rem] h-[3.2rem] mb-[0.8rem] rounded-full bg-[#ff444f]'
data-testid='dt_payment_method_add_button'
onClick={() => onClickAdd?.(paymentMethod)}
>
<LabelPairedPlusLgBoldIcon fill='white' />
</Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { MouseEventHandler } from 'react';
import { useFormContext } from 'react-hook-form';
import { TCountryListItem, TCurrency } from 'types';
import { AD_CONDITION_TYPES } from '@/constants';
import { isEmptyObject } from '@/utils';
import { Localize } from '@deriv-com/translations';
import { Text, useDevice } from '@deriv-com/ui';
import { AdConditionBlockSelector } from '../AdConditionBlockSelector';
Expand All @@ -17,18 +18,27 @@ type TAdConditionsSection = {
getTotalSteps: () => number;
goToNextStep: MouseEventHandler<HTMLButtonElement>;
goToPreviousStep: () => void;
initialPaymentMethods: number[] | string[];
localCurrency?: TCurrency;
rateType: string;
};

const AdConditionsSection = ({ countryList, currency, localCurrency, rateType, ...props }: TAdConditionsSection) => {
const AdConditionsSection = ({
countryList,
currency,
initialPaymentMethods,
localCurrency,
rateType,
...props
}: TAdConditionsSection) => {
const {
formState: { errors },
formState: { errors, isDirty },
getValues,
setValue,
watch,
} = useFormContext();
const { isDesktop } = useDevice();
const selectedMethods = getValues('payment-method') ?? [];
const labelSize = isDesktop ? 'sm' : 'md';

const onClickBlockSelector = (value: number, type: string) => {
Expand All @@ -47,6 +57,10 @@ const AdConditionsSection = ({ countryList, currency, localCurrency, rateType, .

const minJoinDays = watch('min-join-days');
const minCompletionRate = watch('min-completion-rate');

const isPaymentMethodsSame = () =>
initialPaymentMethods.length === selectedMethods.length &&
initialPaymentMethods.sort().every((value, index) => value === selectedMethods.sort()[index]);
return (
<div className='ad-conditions-section'>
<AdSummary
Expand Down Expand Up @@ -77,7 +91,10 @@ const AdConditionsSection = ({ countryList, currency, localCurrency, rateType, .
type={AD_CONDITION_TYPES.COMPLETION_RATE}
/>
<PreferredCountriesSelector countryList={countryList} type={AD_CONDITION_TYPES.PREFERRED_COUNTRIES} />
<AdFormController {...props} isNextButtonDisabled={!!errors} />
<AdFormController
{...props}
isNextButtonDisabled={!isEmptyObject(errors) || (!isDirty && isPaymentMethodsSame())}
/>
</div>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

@include mobile {
padding: 1.6rem;
height: calc(100vh - 20rem);
height: calc(100% - 20rem);
overflow: auto;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const mockProps = {
getTotalSteps: jest.fn(),
goToNextStep: jest.fn(),
goToPreviousStep: jest.fn(),
initialPaymentMethods: [],
localCurrency: 'USD' as TCurrency,
rateType: 'fixed',
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const AdFormController = ({
<Localize i18n_default_text='Next' />
</Button>
) : (
<Button size='lg' textSize={textSize}>
<Button disabled={isEdit ? isNextButtonDisabled : false} size='lg' textSize={textSize}>
{isEdit ? <Localize i18n_default_text='Save changes' /> : <Localize i18n_default_text='Post ad' />}
</Button>
)}
Expand Down
17 changes: 15 additions & 2 deletions src/pages/my-ads/components/AdWizard/AdWizard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,22 @@ import './AdWizard.scss';
type TAdWizardNav = {
countryList: TCountryListItem;
currency: TCurrency;
initialPaymentMethods: number[] | string[];
localCurrency?: TCurrency;
onCancel: () => void;
orderExpiryOptions: TOrderExpiryOptions;
rateType: string;
steps: TStep[];
};

const AdWizard = ({ countryList, onCancel, orderExpiryOptions, steps, ...rest }: TAdWizardNav) => {
const AdWizard = ({
countryList,
initialPaymentMethods,
onCancel,
orderExpiryOptions,
steps,
...rest
}: TAdWizardNav) => {
const { isDesktop } = useDevice();
const [currentStep, setCurrentStep] = useState(0);
const wizardProps = {
Expand Down Expand Up @@ -71,7 +79,12 @@ const AdWizard = ({ countryList, onCancel, orderExpiryOptions, steps, ...rest }:
>
<AdTypeSection onCancel={onCancel} {...wizardProps} {...rest} />
<AdPaymentDetailsSection {...wizardProps} {...rest} orderExpiryOptions={orderExpiryOptions} />
<AdConditionsSection {...wizardProps} countryList={countryList} {...rest} />
<AdConditionsSection
{...wizardProps}
countryList={countryList}
{...rest}
initialPaymentMethods={initialPaymentMethods}
/>
</Wizard>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ jest.mock('../../AdProgressBar', () => ({
const mockProps = {
countryList: {},
currency: 'usd' as TCurrency,
initialPaymentMethods: [],
localCurrency: 'usd' as TCurrency,
onCancel: jest.fn(),
orderExpiryOptions: [900, 1800],
Expand Down
78 changes: 33 additions & 45 deletions src/pages/my-ads/screens/CreateEditAd/CreateEditAd.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useHistory } from 'react-router-dom';
import { NonUndefinedValues, TCountryListItem, TCurrency, TErrorCodes, THooks, TLocalize } from 'types';
Expand Down Expand Up @@ -45,6 +45,7 @@ type TMutatePayload = Parameters<THooks.Advert.Create>[0];
type TFormValuesInfo = NonUndefinedValues<THooks.Advert.Get>;

const CreateEditAd = () => {
const [initialPaymentMethods, setInitialPaymentMethods] = useState<number[] | string[]>([]);
const { queryString } = useQueryString();
const { localize } = useTranslations();
const { advertId = '' } = queryString;
Expand All @@ -60,9 +61,8 @@ const CreateEditAd = () => {
const { data: p2pSettings } = api.settings.useSettings();
const { adverts_archive_period: advertsArchivePeriod, order_expiry_options: orderExpiryOptions = [] } =
p2pSettings ?? {};
const { data: createResponse, error, isError, isSuccess, mutate } = api.advert.useCreate();
const { error, isError, isSuccess, mutate } = api.advert.useCreate();
const {
data: updateResponse,
error: updateError,
isError: isUpdateError,
isSuccess: isUpdateSuccess,
Expand Down Expand Up @@ -95,21 +95,13 @@ const CreateEditAd = () => {
handleSubmit,
reset,
setValue,
trigger,
} = methods;
useEffect(() => {
if (Object.keys(countryList as object).length > 0 && getValues('preferred-countries').length === 0) {
if (Object.keys(countryList as object).length > 0 && getValues('preferred-countries')?.length === 0) {
setValue('preferred-countries', Object.keys(countryList as object));
}
}, [countryList, getValues, setValue]);

useEffect(() => {
return () => {
reset();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const shouldNotShowArchiveMessageAgain = LocalStorageUtils.getValue<boolean>(
LocalStorageConstants.p2pArchiveMessage
);
Expand Down Expand Up @@ -168,19 +160,14 @@ const CreateEditAd = () => {
};

useEffect(() => {
if (isSuccess || isUpdateSuccess) {
if (isSuccess) {
if (!shouldNotShowArchiveMessageAgain) {
showModal('AdCreateEditSuccessModal');
} else if (createResponse?.visibility_status) {
history.push(MY_ADS_URL, {
currency: createResponse?.account_currency,
from: '',
limit: createResponse?.max_order_amount_limit_display,
visibilityStatus: createResponse?.visibility_status[0],
});
} else {
history.push(MY_ADS_URL);
}
} else if (isUpdateSuccess) {
history.push(MY_ADS_URL);
} else if (isError || isUpdateError) {
showModal('AdCreateEditErrorModal');
}
Expand All @@ -199,30 +186,31 @@ const CreateEditAd = () => {

const setFormValues = useCallback(
(formValues: TFormValuesInfo) => {
setValue('form-type', 'edit');
setValue('ad-rate-type', formValues.rate_type);
setValue('ad-type', formValues.type);
setValue('amount', formValues.amount.toString());
setValue('instructions', formValues.description);
setValue('max-order', formValues.max_order_amount.toString());
setValue('min-completion-rate', formValues.min_completion_rate?.toString() ?? '');
setValue('min-join-days', formValues.min_join_days?.toString() ?? '');
setValue('min-order', formValues.min_order_amount.toString());
setValue('rate-value', setInitialAdRate(formValues) as string);
setValue('preferred-countries', formValues.eligible_countries ?? Object.keys(countryList as object));
setValue('order-completion-time', `${formValues.order_expiry_period}`);
if (formValues.type === 'sell') {
setValue('contact-details', formValues.contact_info);
setValue('payment-method', Object.keys(formValues.payment_method_details ?? {}).map(Number));
} else {
const paymentMethodNames = formValues?.payment_method_names;
const paymentMethodKeys =
paymentMethodNames?.map(
name => paymentMethodList.find(method => method.display_name === name)?.id ?? ''
) ?? [];
setValue('payment-method', paymentMethodKeys);
}
trigger();
// Prepare the default values object
const defaultValues = {
'ad-type': formValues.type,
amount: formValues.amount.toString(),
'contact-details': formValues.type === 'sell' ? formValues.contact_info : undefined,
'form-type': 'edit' as const,
instructions: formValues.description,
'max-order': formValues.max_order_amount.toString(),
'min-completion-rate': formValues.min_completion_rate?.toString() ?? '',
'min-join-days': formValues.min_join_days?.toString() ?? '',
'min-order': formValues.min_order_amount.toString(),
'order-completion-time': `${formValues.order_expiry_period}`,
'payment-method':
formValues.type === 'sell'
? Object.keys(formValues.payment_method_details ?? {}).map(Number)
: formValues?.payment_method_names?.map(
name => paymentMethodList.find(method => method.display_name === name)?.id ?? ''
) ?? [],
'preferred-countries': formValues.eligible_countries ?? Object.keys(countryList as object),
'rate-value': setInitialAdRate(formValues) as string,
};

// Use reset to set default values and mark the form as not dirty
reset(defaultValues);
setInitialPaymentMethods(defaultValues['payment-method']);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[paymentMethodList, countryList]
Expand Down Expand Up @@ -251,6 +239,7 @@ const CreateEditAd = () => {
<AdWizard
countryList={countryList as TCountryListItem}
currency={activeAccount?.currency as TCurrency}
initialPaymentMethods={initialPaymentMethods}
localCurrency={p2pSettings?.localCurrency as TCurrency}
onCancel={onClickCancel}
orderExpiryOptions={orderExpiryOptions}
Expand All @@ -267,7 +256,6 @@ const CreateEditAd = () => {
/>
<AdCreateEditSuccessModal
advertsArchivePeriod={advertsArchivePeriod}
data={isEdit ? updateResponse : createResponse}
isModalOpen={!!isModalOpenFor('AdCreateEditSuccessModal')}
onRequestClose={hideModal}
/>
Expand Down
Loading

0 comments on commit 9321cd1

Please sign in to comment.