Skip to content

Commit

Permalink
Reapply "farrah/integrate buildship" (#399) (#403)
Browse files Browse the repository at this point in the history
This reverts commit 76caa57.
  • Loading branch information
azmib-developer authored Nov 13, 2024
1 parent 6a058f9 commit 60d72b6
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 119 deletions.
16 changes: 4 additions & 12 deletions src/components/AppHeader/Notifications/Notifications.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from 'react';
import { useMemo, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { getNotification, MY_PROFILE_URL } from '@/constants';
import { api } from '@/hooks';
Expand All @@ -10,9 +10,8 @@ const Notifications = () => {
const [isOpen, setIsOpen] = useState(false);
const { localize } = useTranslations();
const { isDesktop, isMobile } = useDevice();
const { data: activeAccountData } = api.account.useActiveAccount();
const { data: notifications, subscribe } = api.notification.useGetList();
const { mutate: updateNotification } = api.notification.useUpdate();
const { data: notifications } = api.notification.useGetList();
const { readAllNotifications } = api.notification.useUpdate();
const history = useHistory();

const modifiedNotifications = useMemo(() => {
Expand All @@ -38,13 +37,6 @@ const Notifications = () => {
});
}, [notifications]);

Check warning on line 38 in src/components/AppHeader/Notifications/Notifications.tsx

View workflow job for this annotation

GitHub Actions / build_to_cloudflare_pages

React Hook useMemo has missing dependencies: 'history', 'isDesktop', and 'localize'. Either include them or remove the dependency array

Check warning on line 38 in src/components/AppHeader/Notifications/Notifications.tsx

View workflow job for this annotation

GitHub Actions / build_to_cloudflare_pages

React Hook useMemo has missing dependencies: 'history', 'isDesktop', and 'localize'. Either include them or remove the dependency array

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

return (
<>
<Tooltip
Expand Down Expand Up @@ -75,7 +67,7 @@ const Notifications = () => {
<UINotifications
className={isMobile ? '' : 'absolute top-20 right-80 z-10 w-[26.4rem]'}
clearNotificationsCallback={() => {
updateNotification({ ids: [], notifications_update_status: 'remove' });
readAllNotifications();
}}
componentConfig={{
clearButtonText: localize('Clear all'),
Expand Down
4 changes: 2 additions & 2 deletions src/components/Modals/DailyLimitModal/DailyLimitModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type TDailyLimitModalProps = {

const DailyLimitModal = ({ currency, isModalOpen, onRequestClose }: TDailyLimitModalProps) => {
const { data, error, isPending: isLoading, isSuccess, mutate } = api.advertiser.useUpdate();
const { mutate: updateNotification } = api.notification.useUpdate();
const { readAllNotifications } = api.notification.useUpdate();
const { daily_buy_limit: dailyBuyLimit, daily_sell_limit: dailySellLimit } = data ?? {};
const { isDesktop } = useDevice();
const textSize = isDesktop ? 'sm' : 'md';
Expand Down Expand Up @@ -40,7 +40,7 @@ const DailyLimitModal = ({ currency, isModalOpen, onRequestClose }: TDailyLimitM
mutate({ upgrade_limits: 1 });

//TODO: Remove this once implemented in BE
updateNotification({ ids: [], notifications_update_status: 'remove' });
readAllNotifications();
}}
size='lg'
textSize={textSize}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jest.mock('@/hooks', () => ({
useUpdate: jest.fn(() => mockUseAdvertiserUpdate),
},
notification: {
useUpdate: jest.fn(() => ({ mutate: jest.fn() })),
useUpdate: jest.fn(() => ({ readAllNotifications: jest.fn() })),
},
},
}));
Expand Down
39 changes: 0 additions & 39 deletions src/hooks/api/notification/__tests__/useNotificationList.spec.ts

This file was deleted.

84 changes: 34 additions & 50 deletions src/hooks/api/notification/useNotificationList.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useEffect, useMemo, useState } from 'react';
import { useSubscribe } from '@deriv-com/api-hooks';
import { useEffect, useState } from 'react';

type TNotificationLinks = {
href: string;
Expand All @@ -8,69 +7,54 @@ type TNotificationLinks = {
type TNotification = {
category: string;
id: number;
links: TNotificationLinks[];
links?: TNotificationLinks[];
message_key: string;
payload: string;
read: boolean;
removed: boolean;
};

const handleData = (incomingMessages: TNotification[], prevMessages: TNotification[]) => {
if (!incomingMessages) return prevMessages;

let notifications = prevMessages;
for (let updateIdx = 0; updateIdx < incomingMessages.length; updateIdx++) {
const update = incomingMessages[updateIdx];

const existingMessageIndex = notifications.findIndex((message: TNotification) => message.id === update.id);
const existingMessage = notifications[existingMessageIndex];

if (existingMessage) {
if (update.removed)
notifications = notifications.filter((message: TNotification) => message.id !== update.id);
else notifications[existingMessageIndex] = { ...existingMessage, ...update };
} else notifications.unshift(update);
}

notifications.sort((a: TNotification, b: TNotification) => b.id - a.id);

return [...notifications];
};

/**
* Hook that returns the list of notifications.
*
* @example const { data: notifications } = useNotificationList();
*/
const useNotificationList = () => {
// @ts-expect-error Type undefined. This endpoint will be added to api-hooks.
const { data, ...rest } = useSubscribe('notifications_list');
const [messages, setMessages] = useState<TNotification[]>([]);

const modified_data = useMemo(() => {
if (!messages) return undefined;

// TODO: Remove this filter once all the notifications are implemented
const notifications = messages.filter((notification: { message_key: string }) =>
['p2p-limit-upgrade-available'].includes(notification.message_key)
);

return notifications;
}, [messages]);
const [notifications, setNotifications] = useState<TNotification[]>([]);

useEffect(() => {
// @ts-expect-error Type undefined.
if (data?.notifications_list) {
setMessages(prevMessages => {
// @ts-expect-error Type undefined.
return handleData(data.notifications_list.messages, prevMessages);
});
}
}, [data]);
const fetchNotifications = async () => {
try {
const response = await fetch('https://fs191x.buildship.run/v4/notification/list', {
headers: {
'Content-Type': 'application/json',
token: localStorage.getItem('authToken') || '',
},
method: 'GET',
});

if (response.ok) {
const data = await response.json();

// TODO: Remove this filter once all the notifications are implemented
const messages = data.filter((notification: { message_key: string }) =>
['p2p-limit-upgrade-available'].includes(notification.message_key)
);
setNotifications(messages);
} else {
// eslint-disable-next-line no-console
console.error('Failed to fetch notifications');
}
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
};

fetchNotifications();
}, []);

return {
data: modified_data || [],
...rest,
data: notifications || [],
};
};

Expand Down
32 changes: 17 additions & 15 deletions src/hooks/api/notification/useNotificationUpdate.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
import { useMutation } from '@deriv-com/api-hooks';

/**
* Hook that updates the status of a notification. The notification can be removed or marked as read or unread.
*
* @example
* const { data, mutate } = useNotificationUpdate();
* mutate({ notifications_update_status: 'read', ids: [notification_id]});
* mutate({ notifications_update_status: 'unread', ids: [notification_id]});
* mutate({ notifications_update_status: 'remove', ids: []});
*/
const useNotificationUpdate = () => {
const { data, ...rest } = useMutation({
// @ts-expect-error Type undefined. This endpoint will be added to api-hooks.
name: 'notifications_update_status',
});

const readAllNotifications = async () => {
try {
await fetch('https://fs191x.buildship.run/v4/notification/read', {
body: JSON.stringify({
authorize: localStorage.getItem('authToken'),
}),
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
});
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
};
return {
// @ts-expect-error Type undefined.
data: data?.notifications_update_status,
...rest,
readAllNotifications,
};
};

Expand Down

0 comments on commit 60d72b6

Please sign in to comment.