Skip to content

Commit

Permalink
Merge branch 'master' into Jim/88557/replace-connect-with-use-store-t…
Browse files Browse the repository at this point in the history
…rader-parent
  • Loading branch information
jim-deriv committed Jun 12, 2023
2 parents e1335c2 + 54f6d7b commit 804d223
Show file tree
Hide file tree
Showing 33 changed files with 202 additions and 153 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import { Button, Icon, Modal, Text, Popover } from '@deriv/components';
import { useIsMounted } from '@deriv/shared';
import { isDesktop, useIsMounted } from '@deriv/shared';
import { localize } from '@deriv/translations';
import ApiTokenContext from './api-token-context';
import { TPopoverAlignment, TToken, TApiContext } from 'Types';
Expand All @@ -18,16 +18,16 @@ const ApiTokenDeleteButton = ({ token, popover_alignment = 'left' }: TApiTokenDe
const isMounted = useIsMounted();

const getConfirmationBeforeDelete = () => {
setIsPopoverOpen(false);
if (isDesktop()) setIsPopoverOpen(false);
setIsDeleting(true);
};

const onMouseEnterHandler = () => {
if (!is_deleting) setIsPopoverOpen(true);
if (!is_deleting && isDesktop()) setIsPopoverOpen(true);
};

const onMouseLeaveHandler = () => {
if (!is_deleting) setIsPopoverOpen(false);
if (!is_deleting && isDesktop()) setIsPopoverOpen(false);
};

const handleNo = () => setIsDeleting(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ const ProofOfAddressContainer = ({
onClick={() => {
const url = platforms[from_platform.ref]?.url;
window.location.href = url;
window.localStorage.removeItem('config.platform');
window.sessionStorage.removeItem('config.platform');
}}
>
<Localize i18n_default_text='Back to {{platform_name}}' values={{ platform_name: from_platform.name }} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ const ProofOfIdentityContainer = ({
const { is_hard_redirect = false, url = '' } = platform ?? {};
if (is_hard_redirect) {
window.location.href = url;
window.localStorage.removeItem('config.platform');
window.sessionStorage.removeItem('config.platform');
} else {
routeBackTo(from_platform.route);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const RealAccountCard = observer(() => {
.map(key => current_list[key])
.some(account => account.landing_company_short === 'maltainvest');

const get_currency = (IsIconCurrency(currency) && currency) || 'USD';
const get_currency = (IsIconCurrency(currency?.toUpperCase()) && currency) || 'USD';

return (
<CurrencySwitcherContainer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ const AccountNeedsVerification = observer(({ multipliers_account_status }: Accou
const { openModal, openFailedVerificationModal } = traders_hub;

const account = account_list?.find((acc: { loginid?: string }) => loginid === acc?.loginid);
const title = account?.title;
const icon = account?.icon;
const icon_title = account?.title;

const { text: badge_text, icon: badge_icon } = getStatusBadgeConfig(
multipliers_account_status,
Expand All @@ -32,10 +31,10 @@ const AccountNeedsVerification = observer(({ multipliers_account_status }: Accou
className='real-account-switcher__container'
title={
<Text size='xs' line_height='s'>
{title}
{icon_title}
</Text>
}
icon={IsIconCurrency(icon) ? icon : 'USD'}
icon={IsIconCurrency(icon_title) ? icon_title : 'USD'}
onClick={() => {
return openModal('currency_selection');
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { localize, Localize } from '@deriv/translations';
import { observer } from '@deriv/stores';
import { TReactChangeEvent } from '../../types';
import { useCashierStore } from '../../stores/useCashierStores';
import { useExchangeRate } from '@deriv/hooks';
import './crypto-fiat-converter.scss';

type TTimerProps = {
Expand All @@ -22,9 +23,15 @@ type TCryptoFiatConverterProps = {
onChangeConverterFromAmount: (
event: { target: { value: string } },
from_currency: string,
to_currency: string
to_currency: string,
converted_amount?: number
) => void;
onChangeConverterToAmount: (
event: TReactChangeEvent,
from_currency: string,
to_currency: string,
converted_amount?: number
) => void;
onChangeConverterToAmount: (event: TReactChangeEvent, from_currency: string, to_currency: string) => void;
resetConverter: VoidFunction;
to_currency: string;
validateFromAmount: VoidFunction;
Expand Down Expand Up @@ -75,6 +82,7 @@ const CryptoFiatConverter = observer(
validateToAmount,
}: TCryptoFiatConverterProps) => {
const { crypto_fiat_converter } = useCashierStore();
const { getRate } = useExchangeRate();

const {
converter_from_amount,
Expand Down Expand Up @@ -107,7 +115,10 @@ const CryptoFiatConverter = observer(
setArrowIconDirection('right');
}}
onChange={(e: TReactChangeEvent) => {
onChangeConverterFromAmount(e, from_currency, to_currency);
const from_rate = getRate(from_currency || '');
const to_rate = getRate(to_currency || '');
const converted_amount = (Number(e.target.value) * to_rate) / from_rate;
onChangeConverterFromAmount(e, from_currency, to_currency, converted_amount);
handleChange(e);
}}
type='text'
Expand Down Expand Up @@ -143,7 +154,10 @@ const CryptoFiatConverter = observer(
setArrowIconDirection('left');
}}
onChange={(e: TReactChangeEvent) => {
onChangeConverterToAmount(e, to_currency, from_currency);
const from_rate = getRate(from_currency || '');
const to_rate = getRate(to_currency || '');
const converted_amount = (Number(e.target.value) * from_rate) / to_rate;
onChangeConverterToAmount(e, to_currency, from_currency, converted_amount);
handleChange(e);
}}
type='text'
Expand All @@ -160,10 +174,14 @@ const CryptoFiatConverter = observer(
{is_timer_visible && (
<Timer
onComplete={() => {
const from_rate = getRate(from_currency || '');
const to_rate = getRate(to_currency || '');
const converted_amount = (Number(converter_from_amount) * to_rate) / from_rate;
onChangeConverterFromAmount(
{ target: { value: converter_from_amount } },
from_currency,
to_currency
to_currency,
converted_amount
);
}}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,52 @@
import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import PercentageSelector from '../percentage-selector';
import { mockStore } from '@deriv/stores';
import CashierProviders from '../../../cashier-providers';
import CryptoFiatConverter from '../../crypto-fiat-converter';

describe('<PercentageSelector />', () => {
const getCalculatedAmount = jest.fn();
let mockRootStore: ReturnType<typeof mockStore>, mockProps: React.ComponentProps<typeof CryptoFiatConverter>;
const percentage_selector_props = {
amount: 100,
currency: 'USD',
from_account: '',
getCalculatedAmount,
percentage: 0,
should_percentage_reset: false,
to_account: '',
from_currency: 'USD',
to_currency: 'BTC',
};
beforeEach(() => {
mockRootStore = mockStore({
exchange_rates: {
data: {
rates: {
USD: 1,
BTC: 2,
},
},
},
});
});

it('should render the component', () => {
render(<PercentageSelector {...percentage_selector_props} />);
render(
<CashierProviders store={mockRootStore}>
<PercentageSelector {...percentage_selector_props} />
</CashierProviders>
);

expect(screen.getByTestId('dt_percentage_selector_id')).toBeInTheDocument();
});

it('should calculate the percentage amount on click of percentage block', () => {
render(<PercentageSelector {...percentage_selector_props} />);
render(
<CashierProviders store={mockRootStore}>
<PercentageSelector {...percentage_selector_props} />
</CashierProviders>
);

fireEvent.click(screen.getByTestId('dt_percentage_selector_block_id_1'));
expect(screen.getByText(`25% of available balance (100.00 USD)`)).toBeInTheDocument();
Expand All @@ -37,7 +62,11 @@ describe('<PercentageSelector />', () => {
});

it('should reset the percentage block upon clicking twice', () => {
render(<PercentageSelector {...percentage_selector_props} />);
render(
<CashierProviders store={mockRootStore}>
<PercentageSelector {...percentage_selector_props} />
</CashierProviders>
);

fireEvent.click(screen.getByTestId('dt_percentage_selector_block_id_1'));
fireEvent.click(screen.getByTestId('dt_percentage_selector_block_id_1'));
Expand All @@ -61,7 +90,11 @@ describe('<PercentageSelector />', () => {
});

it('should reset the percentage', () => {
render(<PercentageSelector {...percentage_selector_props} should_percentage_reset />);
render(
<CashierProviders store={mockRootStore}>
<PercentageSelector {...percentage_selector_props} should_percentage_reset />
</CashierProviders>
);

expect(screen.getByText('0% of available balance (100.00 USD)')).toBeInTheDocument();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,33 @@ import { Text } from '@deriv/components';
import { formatMoney, getCurrencyDisplayCode, getDecimalPlaces } from '@deriv/shared';
import { Localize } from '@deriv/translations';
import { TReactMouseEvent } from '../../types';
import { useExchangeRate } from '@deriv/hooks';

type TPercentageSelectorProps = {
amount: number;
currency: string;
from_account?: string;
getCalculatedAmount: (amount: string) => void;
getCalculatedAmount: (amount: string, converted_amount: number) => void;
percentage: number;
should_percentage_reset: boolean;
to_account?: string;
from_currency: string;
to_currency: string;
};

type TCalculateAmountInputEvent = { target: { id: number } };

const PercentageSelector = ({
amount,
currency,
from_account,
getCalculatedAmount,
percentage,
should_percentage_reset,
to_account,
from_currency,
to_currency,
}: TPercentageSelectorProps) => {
const [selected_percentage, setSelectedPercentage] = React.useState<number | string>('0');

const { getRate } = useExchangeRate();
React.useEffect(() => {
if (should_percentage_reset) {
for (let i = 1; i <= 4; i++) {
Expand All @@ -48,11 +51,17 @@ const PercentageSelector = ({

const calculateAmount = (e: TCalculateAmountInputEvent | TReactMouseEvent, percent: number) => {
let new_percentage = percent;
const is_percentage_selected = percent > 0 && percent <= selected_percentage;
const is_percentage_selected = percent > 0 && percent <= Number(selected_percentage);
if (is_percentage_selected) new_percentage -= 25;

setSelectedPercentage(new_percentage || 0);
getCalculatedAmount((amount * (new_percentage / 100)).toFixed(getDecimalPlaces(currency)));
const from_rate = getRate(from_currency || '');
const to_rate = getRate(to_currency || '');
const converted_amount = (amount * (new_percentage / 100) * to_rate) / from_rate;
getCalculatedAmount(
(amount * (new_percentage / 100)).toFixed(getDecimalPlaces(from_currency)),
converted_amount
);

for (let i = 1; i <= 4; i++) {
const percentage_selector_block = document.getElementById(String(i));
Expand All @@ -68,8 +77,8 @@ const PercentageSelector = ({
}
}
};
const format_amount = formatMoney(currency, amount, true);
const currency__display_code = getCurrencyDisplayCode(currency);
const format_amount = formatMoney(from_currency, amount, true);
const currency__display_code = getCurrencyDisplayCode(from_currency);
return (
<React.Fragment>
<div className='percentage-selector' data-testid='dt_percentage_selector_id'>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const AccountOption = ({ account, idx }: TAccountsList) => {
<Money
amount={account.balance}
currency={account.currency}
has_sign={Boolean(account.balance && account.balance < 0)}
has_sign={Boolean(account.balance && Number(account.balance) < 0)}
show_currency
/>
</span>
Expand Down Expand Up @@ -529,12 +529,13 @@ const AccountTransferForm = observer(
<div className='account-transfer-form__crypto--percentage-selector'>
<PercentageSelector
amount={selected_from.balance ? Number(selected_from.balance) : 0}
currency={selected_from.currency || ''}
from_account={selected_from.value}
getCalculatedAmount={setTransferPercentageSelectorResult}
percentage={percentage}
should_percentage_reset={should_percentage_reset}
to_account={selected_to.value}
from_currency={selected_from.currency || ''}
to_currency={selected_to.currency || ''}
/>
</div>
<CryptoFiatConverter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,11 @@ const CryptoWithdrawForm = observer(() => {
<div className='crypto-withdraw-form__percentage-selector'>
<PercentageSelector
amount={Number(balance)}
currency={currency}
getCalculatedAmount={setWithdrawPercentageSelectorResult}
percentage={percentage}
should_percentage_reset={should_percentage_reset}
from_currency={crypto_currency}
to_currency={current_fiat_currency || DEFAULT_FIAT_CURRENCY}
/>
</div>
<CryptoFiatConverter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -749,39 +749,39 @@ describe('AccountTransferStore', () => {
const spyValidateTransferFromAmount = jest.spyOn(account_transfer_store, 'validateTransferFromAmount');
account_transfer_store.setSelectedFrom({ currency: 'USD' });
account_transfer_store.setSelectedTo({ currency: 'BTC' });
account_transfer_store.setTransferPercentageSelectorResult('10');
account_transfer_store.setTransferPercentageSelectorResult('10', 11.01);
const { onChangeConverterFromAmount, setConverterFromAmount } =
account_transfer_store.root_store.modules.cashier.crypto_fiat_converter;

expect(setConverterFromAmount).toHaveBeenCalledWith('10');
expect(spyValidateTransferFromAmount).toHaveBeenCalledTimes(1);
expect(onChangeConverterFromAmount).toHaveBeenCalledWith({ target: { value: '10' } }, 'USD', 'BTC');
expect(onChangeConverterFromAmount).toHaveBeenCalledWith({ target: { value: '10' } }, 'USD', 'BTC', 11.01);
});

it('should set transfer percentage selector result if selected_from.balance = 0', () => {
const spyValidateTransferFromAmount = jest.spyOn(account_transfer_store, 'validateTransferFromAmount');
account_transfer_store.setSelectedFrom({ balance: 0, currency: 'USD' });
account_transfer_store.setSelectedTo({ currency: 'BTC' });
account_transfer_store.setTransferPercentageSelectorResult('0');
account_transfer_store.setTransferPercentageSelectorResult('0', 11.01);
const { onChangeConverterFromAmount, setConverterFromAmount } =
account_transfer_store.root_store.modules.cashier.crypto_fiat_converter;

expect(setConverterFromAmount).toHaveBeenCalledWith('0');
expect(spyValidateTransferFromAmount).toHaveBeenCalledTimes(1);
expect(onChangeConverterFromAmount).toHaveBeenCalledWith({ target: { value: '0' } }, 'USD', 'BTC');
expect(onChangeConverterFromAmount).toHaveBeenCalledWith({ target: { value: '0' } }, 'USD', 'BTC', 11.01);
});

it('should reset crypto fiat converter if amount = 0 and selected_from.balance > 0', () => {
account_transfer_store.setSelectedFrom({ balance: 10, currency: 'USD' });
account_transfer_store.setTransferPercentageSelectorResult('0');
account_transfer_store.setTransferPercentageSelectorResult('0', 11.01);

expect(
account_transfer_store.root_store.modules.cashier.crypto_fiat_converter.resetConverter
).toHaveBeenCalledTimes(1);
});

it('should set timer visibility and percentage selector selection status to false when calling setTransferPercentageSelectorResult method', () => {
account_transfer_store.setTransferPercentageSelectorResult('10');
account_transfer_store.setTransferPercentageSelectorResult('10', 11.01);
const { crypto_fiat_converter, general_store } = account_transfer_store.root_store.modules.cashier;

expect(crypto_fiat_converter.setIsTimerVisible).toHaveBeenCalledWith(false);
Expand Down
Loading

0 comments on commit 804d223

Please sign in to comment.