Skip to content

Commit

Permalink
fix: ts errors
Browse files Browse the repository at this point in the history
  • Loading branch information
ameerul-deriv committed Apr 25, 2024
1 parent b75546b commit 834bd8e
Show file tree
Hide file tree
Showing 21 changed files with 84 additions and 48 deletions.
2 changes: 1 addition & 1 deletion src/components/AdvertiserName/AdvertiserNameStats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { OnlineStatusIcon, OnlineStatusLabel, StarRating } from '@/components';
import { getCurrentRoute } from '@/utils';
import { Text, useDevice } from '@deriv-com/ui';
import ThumbUpIcon from '../../public/ic-thumb-up.svg';
import BlockedUserOutlineIcon from '../../public/ic-user-blocked-outline.svg?react';
import BlockedUserOutlineIcon from '../../public/ic-user-blocked-outline.svg';
import './AdvertiserNameStats.scss';

/**
Expand Down
4 changes: 2 additions & 2 deletions src/components/BuySellForm/BuySellForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,14 @@ const BuySellForm = ({
type,
} = advert;

const avertiserPaymentMethodObjects = getPaymentMethodObjects(advertiserPaymentMethods);
const advertiserPaymentMethodObjects = getPaymentMethodObjects(advertiserPaymentMethods);

const paymentMethodObjects = getPaymentMethodObjects(paymentMethods);

const availablePaymentMethods = payment_method_names?.map(paymentMethod => {
const isAvailable = advertiserPaymentMethods?.some(method => method.display_name === paymentMethod);
return {
...(isAvailable ? avertiserPaymentMethodObjects[paymentMethod] : paymentMethodObjects[paymentMethod]),
...(isAvailable ? advertiserPaymentMethodObjects[paymentMethod] : paymentMethodObjects[paymentMethod]),
isAvailable,
};
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('BuySellFormFooter', () => {
expect(mockProps.onClickCancel).toHaveBeenCalled();
});
it('should handle onclick for confirm button', () => {
const newProps = { mockProps, onSubmit: jest.fn() };
const newProps = { ...mockProps, onSubmit: jest.fn() };
render(<BuySellFormFooter {...newProps} />);
const confirmButton = screen.getByRole('button', { name: 'Confirm' });
confirmButton.click();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import BuySellPaymentSection from '../BuySellPaymentSection';
const mockProps = {
availablePaymentMethods: [],
onSelectPaymentMethodCard: jest.fn(),
selectedPaymentMethodIds: ['123'],
selectedPaymentMethodIds: [123],
};

const mockAvailablePaymentMethods = {
Expand Down
3 changes: 2 additions & 1 deletion src/components/Dropdown/Dropdown.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { FC, ReactNode, useCallback, useEffect, useState } from 'react';
import clsx from 'clsx';
import { useCombobox } from 'downshift';
import { TextField, TextFieldProps } from '@/components';
import { TextField } from '@/components';
import { reactNodeToString } from '@/utils';
import { LabelPairedChevronDownMdRegularIcon } from '@deriv/quill-icons';
import { Text } from '@deriv-com/ui';
import { TextFieldProps } from '../TextField/TextField';
import './Dropdown.scss';

type TGenericSizes = '2xl' | '2xs' | '3xl' | '3xs' | '4xl' | '5xl' | '6xl' | 'lg' | 'md' | 'sm' | 'xl' | 'xs';
Expand Down
5 changes: 3 additions & 2 deletions src/components/FloatingRate/__tests__/FloatingRate.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { TCurrency } from 'types';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import FloatingRate from '../FloatingRate';
Expand Down Expand Up @@ -33,9 +34,9 @@ const mockProps = {
changeHandler: jest.fn(),
errorMessages: '',
fiatCurrency: 'USD',
localCurrency: 'IDR',
localCurrency: 'IDR' as TCurrency,
onChange: jest.fn(),
value: 1.1,
value: '1.1',
};

describe('FloatingRate', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type TAdCreateEditErrorModalProps = {
onRequestClose: () => void;
};

type ErrorCodes = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
export type ErrorCodes = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];

type ErrorContent = {
[key in ErrorCodes]?: {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import AdCreateEditErrorModal from '../AdCreateEditErrorModal';
import AdCreateEditErrorModal, { ErrorCodes } from '../AdCreateEditErrorModal';

const mockProps = {
errorCode: 'AdvertSameLimits',
errorCode: 'AdvertSameLimits' as ErrorCodes,
isModalOpen: true,
onRequestClose: jest.fn(),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const mockProps = {
setSelectedPaymentMethods: jest.fn(),
};

let mockData = [
let mockData: { display_name: string; id: string }[] | undefined = [
{
display_name: 'Alipay',
id: 'alipay',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,19 @@ jest.mock('@/providers/AdvertiserInfoStateProvider', () => ({
}),
}));

const mockProps = {
isModalOpen: true,
onRequestClose: jest.fn(),
};

describe('NicknameModal', () => {
it('should render title and description correctly', () => {
render(<NicknameModal isModalOpen setIsModalOpen={jest.fn()} />);
render(<NicknameModal {...mockProps} />);
expect(screen.getByText('What’s your nickname?')).toBeVisible();
expect(screen.getByText('Others will see this on your profile, ads and charts.')).toBeVisible();
});
it('should allow users to type and submit nickname', async () => {
render(<NicknameModal isModalOpen setIsModalOpen={jest.fn()} />);
render(<NicknameModal {...mockProps} />);

const nicknameInput = screen.getByTestId('dt_nickname_modal_input');

Expand Down Expand Up @@ -85,7 +90,7 @@ describe('NicknameModal', () => {
}));

await (() => {
render(<NicknameModal isModalOpen setIsModalOpen={jest.fn()} />);
render(<NicknameModal {...mockProps} />);
});

expect(mockedReset).toBeCalled();
Expand All @@ -98,15 +103,15 @@ describe('NicknameModal', () => {
mutate: mockedMutate,
reset: mockedReset,
}));
const mockIsModalOpen = jest.fn();
render(<NicknameModal isModalOpen setIsModalOpen={mockIsModalOpen} />);

render(<NicknameModal {...mockProps} />);

const cancelBtn = screen.getByRole('button', {
name: 'Cancel',
});
await userEvent.click(cancelBtn);

expect(mockPush).toBeCalledWith('/buy-sell');
expect(mockIsModalOpen).toBeCalledWith(false);
expect(mockProps.onRequestClose).toBeCalledWith(false);
});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { ComponentType, SVGAttributes } from 'react';
import { THooks } from 'types';
import { FlyoutMenu } from '@/components';
import { LabelPairedEllipsisVerticalXlRegularIcon } from '@deriv/quill-icons';
Expand Down Expand Up @@ -33,19 +32,19 @@ const PaymentMethodCardHeader = ({
small = false,
type,
}: TPaymentMethodCardHeaderProps) => {
let Icon: ComponentType<SVGAttributes<SVGElement>> = IcCashierOther;
let Icon = IcCashierOther;
if (type === 'bank') {
Icon = IcCashierBankTransfer;
} else if (type === 'ewallet') {
Icon = IcCashierEwallet;
}
// TODO: Remember to translate these
const flyoutMenuItems = [
<Button color='black' key={0} onClick={() => onEditPaymentMethod?.()} size='xs' textSize='xs' variant='ghost'>
<Button color='black' key={0} onClick={() => onEditPaymentMethod?.()} size='sm' textSize='xs' variant='ghost'>
Edit
</Button>,

<Button color='black' key={1} onClick={() => onDeletePaymentMethod?.()} size='xs' textSize='xs' variant='ghost'>
<Button color='black' key={1} onClick={() => onDeletePaymentMethod?.()} size='sm' textSize='xs' variant='ghost'>
Delete
</Button>,
];
Expand Down
8 changes: 4 additions & 4 deletions src/hooks/custom-hooks/useExtendedOrderDetails.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { THooks, TServerTime } from 'types';
import { TCurrency, THooks, TServerTime } from 'types';
import { BUY_SELL, ORDERS_STATUS } from '@/constants'; // Update your import path
import {
convertToMillis,
Expand All @@ -15,7 +15,7 @@ type TOrder = THooks.Order.Get;
type TUserDetails = TOrder['advertiser_details'] | TOrder['client_details'];

type TObject = Record<string, string>;
interface ExtendedOrderDetails extends TOrder {
export interface ExtendedOrderDetails extends TOrder {
counterpartyAdStatusString: TObject;
displayPaymentAmount: string;
hasReviewDetails: boolean;
Expand Down Expand Up @@ -93,7 +93,7 @@ const useExtendedOrderDetails = ({
return removeTrailingZeros(
FormatUtils.formatMoney(
Number(this.amount_display) * Number(roundOffDecimal(this.rate, setDecimalPlaces(this.rate, 6))),
{ currency: this.local_currency }
{ currency: this.local_currency as TCurrency }
)
);
},
Expand Down Expand Up @@ -203,7 +203,7 @@ const useExtendedOrderDetails = ({
get rateAmount() {
return removeTrailingZeros(
FormatUtils.formatMoney(this.rate, {
currency: this.local_currency,
currency: this.local_currency as TCurrency,
decimalPlaces: setDecimalPlaces(this.rate, 6),
})
);
Expand Down
29 changes: 22 additions & 7 deletions src/pages/my-ads/screens/CreateEditAd/CreateEditAd.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const CreateEditAd = () => {
'min-order': '',
'order-completion-time': `${orderPaymentPeriod ? (orderPaymentPeriod * 60).toString() : '3600'}`,
'payment-method': [],
'preferred-countries': Object.keys(countryList),
'preferred-countries': Object.keys(countryList as object),
'rate-type-string': rateType,
'rate-value': rateType === RATE_TYPE.FLOAT ? '-0.01' : '',
},
Expand All @@ -82,15 +82,30 @@ const CreateEditAd = () => {
setValue,
} = methods;
useEffect(() => {
if (Object.keys(countryList).length > 0 && getValues('preferred-countries').length === 0) {
setValue('preferred-countries', Object.keys(countryList));
if (Object.keys(countryList as object).length > 0 && getValues('preferred-countries').length === 0) {
setValue('preferred-countries', Object.keys(countryList as object));
}
}, [countryList, getValues, setValue]);

const shouldNotShowArchiveMessageAgain = localStorage.getItem('should_not_show_auto_archive_message_again');

const onSubmit = () => {
const payload = {
type TPayload = {
amount?: number;
eligible_countries: string[];
max_order_amount: number;
min_order_amount: number;
rate: number;
rate_type: string;
type?: 'buy' | 'sell';
payment_method_names?: number[] | string[];
contact_info?: string;
payment_method_ids?: number[] | string[];
description?: string;
min_completion_rate?: number;
min_join_days?: number;
};
const payload: TPayload = {
amount: Number(getValues('amount')),
eligible_countries: getValues('preferred-countries'),
max_order_amount: Number(getValues('max-order')),
Expand Down Expand Up @@ -159,7 +174,7 @@ const CreateEditAd = () => {
setValue('min-join-days', advertInfo.min_join_days.toString());
setValue('min-order', advertInfo.min_order_amount.toString());
setValue('rate-value', setInitialAdRate() as string);
setValue('preferred-countries', advertInfo.eligible_countries ?? Object.keys(countryList));
setValue('preferred-countries', advertInfo.eligible_countries ?? Object.keys(countryList as object));
setValue('order-completion-time', `${advertInfo.order_expiry_period}`);
if (advertInfo.type === 'sell') {
setValue('contact-details', advertInfo.contact_info);
Expand All @@ -177,7 +192,7 @@ const CreateEditAd = () => {

useEffect(() => {
if (advertInfo && isEdit) {
setFormValues(advertInfo);
setFormValues(advertInfo as NonUndefinedValues<THooks.Advert.Get>);
}
}, [advertInfo, isEdit, setFormValues]);

Expand All @@ -195,7 +210,7 @@ const CreateEditAd = () => {
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)}>
<AdWizard
countryList={countryList}
countryList={countryList as object}
currency={activeAccount?.currency ?? 'USD'}
localCurrency={p2pSettings?.localCurrency}
onCancel={onClickCancel}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { memo, useEffect, useRef, useState } from 'react';
import clsx from 'clsx';
import { TCurrency, TExchangeRate } from 'types';
import { NonUndefinedValues, TCurrency, TExchangeRate } from 'types';
import { PaymentMethodLabel, PopoverDropdown } from '@/components';
import { AD_ACTION, ADVERT_TYPE, RATE_TYPE } from '@/constants';
import { useFloatingRate } from '@/hooks/custom-hooks';
Expand Down Expand Up @@ -31,7 +31,7 @@ type TProps = {
type TMyAdsTableProps = Omit<TMyAdsTableRowRendererProps, 'balanceAvailable' | 'dailyBuyLimit' | 'dailySellLimit'> &
TProps;

const MyAdsTableRow = ({ currentRateType, showModal, ...rest }: TMyAdsTableProps) => {
const MyAdsTableRow = ({ currentRateType, showModal, ...rest }: NonUndefinedValues<TMyAdsTableProps>) => {
const { isMobile } = useDevice();
const { subscribeRates } = useExchangeRates();

Expand Down Expand Up @@ -133,7 +133,8 @@ const MyAdsTableRow = ({ currentRateType, showModal, ...rest }: TMyAdsTableProps
</div>
<div className='my-ads-table-row__line-details'>
<Text color='success' size='sm'>
{`${FormatUtils.formatMoney(amountDealt, { currency: accountCurrency })}`} {accountCurrency}
{`${FormatUtils.formatMoney(amountDealt, { currency: accountCurrency as TCurrency })}`}{' '}
{accountCurrency}
&nbsp;
{advertType === 'Buy' ? 'Bought' : 'Sold'}
</Text>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ const mockProps = {
min_rating: 4,
order_expiry_period: 900,
payment_info: '',
is_floating: false,
balanceAvailable: 0,
dailyBuyLimit: '',
dailySellLimit: '',
};
const mockHistory = {
push: jest.fn(),
Expand Down
3 changes: 2 additions & 1 deletion src/pages/orders/screens/OrderDetails/OrderDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useHistory, useLocation, useParams } from 'react-router-dom';
import { FullPageMobileWrapper, PageReturn } from '@/components';
import { api } from '@/hooks';
import { useExtendedOrderDetails } from '@/hooks/custom-hooks';
import { ExtendedOrderDetails } from '@/hooks/custom-hooks/useExtendedOrderDetails';
import { OrderDetailsProvider } from '@/providers/OrderDetailsProvider';
import { useAuthData } from '@deriv-com/api-hooks';
import { Button, InlineMessage, Loader, Text, useDevice } from '@deriv-com/ui';
Expand All @@ -25,7 +26,7 @@ const OrderDetails = () => {
const { data: serverTime } = api.account.useServerTime();
const { data: orderDetails } = useExtendedOrderDetails({
loginId: activeAccount?.loginid,
orderDetails: orderInfo,
orderDetails: orderInfo as ExtendedOrderDetails,
serverTime,
});
const { isBuyOrderForUser, shouldShowLostFundsBanner } = orderDetails;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ describe('<OrderDetails />', () => {
isLoading: false,
});

render(<OrderDetails orderId='1' />);
render(<OrderDetails />);

expect(screen.getByTestId('dt_derivs-loader')).toBeInTheDocument();
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import clsx from 'clsx';
import { useHistory } from 'react-router-dom';
import { THooks } from 'types';
import { DeepPartial, THooks } from 'types';
import { ORDERS_STATUS, ORDERS_URL } from '@/constants';
import { api } from '@/hooks';
import { useExtendedOrderDetails, useQueryString } from '@/hooks/custom-hooks';
import { ExtendedOrderDetails } from '@/hooks/custom-hooks/useExtendedOrderDetails';
import { OrderRatingButton, OrderStatusTag, OrderTimer } from '@/pages/orders/components';
import { getDistanceToServerTime } from '@/utils';
import { Button, Text, useDevice } from '@deriv-com/ui';
import ChatIcon from '../../../../../public/ic-chat.svg';
import './OrdersTableRow.scss';

const OrdersTableRow = ({ ...props }: THooks.Order.GetList[number]) => {
const OrdersTableRow = ({ ...props }: DeepPartial<THooks.Order.GetList[number]>) => {
const { isMobile } = useDevice();
const { queryString } = useQueryString();
const history = useHistory();
Expand All @@ -19,7 +20,7 @@ const OrdersTableRow = ({ ...props }: THooks.Order.GetList[number]) => {
const { data: serverTime } = api.account.useServerTime();
const { data: orderDetails } = useExtendedOrderDetails({
loginId: activeAccount?.loginid,
orderDetails: props,
orderDetails: props as ExtendedOrderDetails,
serverTime,
});

Expand Down
Loading

0 comments on commit 834bd8e

Please sign in to comment.