Skip to content

Commit

Permalink
fix: save changes button, something went wrong, you've created popup
Browse files Browse the repository at this point in the history
  • Loading branch information
nada-deriv committed Aug 2, 2024
1 parent db7a958 commit 33445c1
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 69 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 @@ -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 @@ -41,6 +51,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 @@ -70,7 +84,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 @@ -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
69 changes: 34 additions & 35 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 @@ -44,6 +44,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 @@ -59,9 +60,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 @@ -92,10 +92,11 @@ const CreateEditAd = () => {
formState: { isDirty },
getValues,
handleSubmit,
reset,
setValue,
} = 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]);
Expand Down Expand Up @@ -158,19 +159,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 @@ -189,28 +185,31 @@ const CreateEditAd = () => {

const setFormValues = useCallback(
(formValues: TFormValuesInfo) => {
setValue('form-type', 'edit');
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);
}
// 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 @@ -239,6 +238,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 @@ -255,7 +255,6 @@ const CreateEditAd = () => {
/>
<AdCreateEditSuccessModal
advertsArchivePeriod={advertsArchivePeriod}
data={isEdit ? updateResponse : createResponse}
isModalOpen={!!isModalOpenFor('AdCreateEditSuccessModal')}
onRequestClose={hideModal}
/>
Expand Down
18 changes: 3 additions & 15 deletions src/pages/my-ads/screens/MyAds/MyAdsTableRow/MyAdsTableRowView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import { AD_ACTION, MY_ADS_URL } from '@/constants';
import { api } from '@/hooks';
import useInvalidateQuery from '@/hooks/api/useInvalidateQuery';
import { useFloatingRate, useModalManager, useQueryString } from '@/hooks/custom-hooks';
import { useFloatingRate, useModalManager } from '@/hooks/custom-hooks';
import { getPaymentMethodObjects, getVisibilityErrorCodes } from '@/utils';
import { LocalStorageConstants, LocalStorageUtils } from '@deriv-com/utils';
import { TMyAdsTableRowRendererProps } from '../MyAdsTable/MyAdsTable';
Expand Down Expand Up @@ -50,14 +50,13 @@ const MyAdsTableRowView = ({
const { data: p2pSettings } = api.settings.useSettings();
const { order_payment_period: orderPaymentPeriod } = p2pSettings ?? {};
const {
data: createResponse,
error: createError,
isError: isCreateError,
isSuccess: isCreateSuccess,
mutate: createAd,
} = api.advert.useCreate();
const { rateType: currentRateType, reachedTargetDate } = useFloatingRate();
const { data: updateResponse, error: updateError, isError: isErrorUpdate, mutate } = api.advert.useUpdate();
const { error: updateError, isError: isErrorUpdate, mutate } = api.advert.useUpdate();
const { error, isError, mutate: deleteAd } = api.advert.useDelete();
const shouldNotShowArchiveMessageAgain = LocalStorageUtils.getValue<boolean>(
LocalStorageConstants.p2pArchiveMessage
Expand All @@ -74,16 +73,6 @@ const MyAdsTableRowView = ({
const advertiserPaymentMethodObjects = getPaymentMethodObjects(
advertiserPaymentMethods as THooks.AdvertiserPaymentMethods.Get
);
const { queryString } = useQueryString();

const createAdvisibilityStatus = (location.state as TState)?.visibilityStatus;

useEffect(() => {
if (createAdvisibilityStatus) {
showModal('AdVisibilityErrorModal');
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [createAdvisibilityStatus]);

const {
account_currency: accountCurrency = '',
Expand Down Expand Up @@ -158,7 +147,7 @@ const MyAdsTableRowView = ({

useEffect(() => {
if (isCreateSuccess) {
if (shouldNotShowArchiveMessageAgain) {
if (!shouldNotShowArchiveMessageAgain) {
showModal('AdCreateEditSuccessModal');
} else {
invalidate('p2p_advertiser_adverts');
Expand Down Expand Up @@ -287,7 +276,6 @@ const MyAdsTableRowView = ({
{!!isModalOpenFor('AdCreateEditSuccessModal') && (
<AdCreateEditSuccessModal
advertsArchivePeriod={orderPaymentPeriod}
data={queryString.formAction === 'edit' ? updateResponse : createResponse}
isModalOpen
onRequestClose={() => hideModal({ shouldHideAllModals: true })}
/>
Expand Down

0 comments on commit 33445c1

Please sign in to comment.