Skip to content

Commit 0b26fce

Browse files
author
Wojciech Brygola
committed
Revert "Reapply "farrah/integrate buildship" (#399) (#403)"
This reverts commit 60d72b6.
1 parent 60d72b6 commit 0b26fce

File tree

6 files changed

+119
-58
lines changed

6 files changed

+119
-58
lines changed

src/components/AppHeader/Notifications/Notifications.tsx

+12-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useMemo, useState } from 'react';
1+
import { useEffect, useMemo, useState } from 'react';
22
import { useHistory } from 'react-router-dom';
33
import { getNotification, MY_PROFILE_URL } from '@/constants';
44
import { api } from '@/hooks';
@@ -10,8 +10,9 @@ const Notifications = () => {
1010
const [isOpen, setIsOpen] = useState(false);
1111
const { localize } = useTranslations();
1212
const { isDesktop, isMobile } = useDevice();
13-
const { data: notifications } = api.notification.useGetList();
14-
const { readAllNotifications } = api.notification.useUpdate();
13+
const { data: activeAccountData } = api.account.useActiveAccount();
14+
const { data: notifications, subscribe } = api.notification.useGetList();
15+
const { mutate: updateNotification } = api.notification.useUpdate();
1516
const history = useHistory();
1617

1718
const modifiedNotifications = useMemo(() => {
@@ -37,6 +38,13 @@ const Notifications = () => {
3738
});
3839
}, [notifications]);
3940

41+
useEffect(() => {
42+
if (activeAccountData) {
43+
subscribe({});
44+
}
45+
// eslint-disable-next-line react-hooks/exhaustive-deps
46+
}, [activeAccountData]);
47+
4048
return (
4149
<>
4250
<Tooltip
@@ -67,7 +75,7 @@ const Notifications = () => {
6775
<UINotifications
6876
className={isMobile ? '' : 'absolute top-20 right-80 z-10 w-[26.4rem]'}
6977
clearNotificationsCallback={() => {
70-
readAllNotifications();
78+
updateNotification({ ids: [], notifications_update_status: 'remove' });
7179
}}
7280
componentConfig={{
7381
clearButtonText: localize('Clear all'),

src/components/Modals/DailyLimitModal/DailyLimitModal.tsx

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ type TDailyLimitModalProps = {
1212

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

4242
//TODO: Remove this once implemented in BE
43-
readAllNotifications();
43+
updateNotification({ ids: [], notifications_update_status: 'remove' });
4444
}}
4545
size='lg'
4646
textSize={textSize}

src/components/Modals/DailyLimitModal/__tests__/DailyLimitModal.spec.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ jest.mock('@/hooks', () => ({
2222
useUpdate: jest.fn(() => mockUseAdvertiserUpdate),
2323
},
2424
notification: {
25-
useUpdate: jest.fn(() => ({ readAllNotifications: jest.fn() })),
25+
useUpdate: jest.fn(() => ({ mutate: jest.fn() })),
2626
},
2727
},
2828
}));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { renderHook } from '@testing-library/react';
2+
import useNotificationList from '../useNotificationList';
3+
4+
const mockNotificationListData = {
5+
data: {
6+
notifications_list: {
7+
messages: [
8+
{
9+
category: 'see',
10+
id: 1,
11+
message_key: 'p2p-limit-upgrade-available',
12+
},
13+
{
14+
category: 'see',
15+
id: 2,
16+
message_key: 'poi-verified',
17+
},
18+
],
19+
},
20+
},
21+
};
22+
23+
jest.mock('@deriv-com/api-hooks', () => ({
24+
useSubscribe: jest.fn(() => mockNotificationListData),
25+
}));
26+
27+
describe('useNotificationList', () => {
28+
it('should return the list of p2p-related notifications', () => {
29+
const { result } = renderHook(() => useNotificationList());
30+
31+
expect(result.current.data).toEqual([
32+
{
33+
category: 'see',
34+
id: 1,
35+
message_key: 'p2p-limit-upgrade-available',
36+
},
37+
]);
38+
});
39+
});

src/hooks/api/notification/useNotificationList.ts

+50-34
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { useEffect, useState } from 'react';
1+
import { useEffect, useMemo, useState } from 'react';
2+
import { useSubscribe } from '@deriv-com/api-hooks';
23

34
type TNotificationLinks = {
45
href: string;
@@ -7,54 +8,69 @@ type TNotificationLinks = {
78
type TNotification = {
89
category: string;
910
id: number;
10-
links?: TNotificationLinks[];
11+
links: TNotificationLinks[];
1112
message_key: string;
1213
payload: string;
1314
read: boolean;
1415
removed: boolean;
1516
};
1617

18+
const handleData = (incomingMessages: TNotification[], prevMessages: TNotification[]) => {
19+
if (!incomingMessages) return prevMessages;
20+
21+
let notifications = prevMessages;
22+
for (let updateIdx = 0; updateIdx < incomingMessages.length; updateIdx++) {
23+
const update = incomingMessages[updateIdx];
24+
25+
const existingMessageIndex = notifications.findIndex((message: TNotification) => message.id === update.id);
26+
const existingMessage = notifications[existingMessageIndex];
27+
28+
if (existingMessage) {
29+
if (update.removed)
30+
notifications = notifications.filter((message: TNotification) => message.id !== update.id);
31+
else notifications[existingMessageIndex] = { ...existingMessage, ...update };
32+
} else notifications.unshift(update);
33+
}
34+
35+
notifications.sort((a: TNotification, b: TNotification) => b.id - a.id);
36+
37+
return [...notifications];
38+
};
39+
1740
/**
1841
* Hook that returns the list of notifications.
1942
*
43+
* @example const { data: notifications } = useNotificationList();
2044
*/
2145
const useNotificationList = () => {
22-
const [notifications, setNotifications] = useState<TNotification[]>([]);
46+
// @ts-expect-error Type undefined. This endpoint will be added to api-hooks.
47+
const { data, ...rest } = useSubscribe('notifications_list');
48+
const [messages, setMessages] = useState<TNotification[]>([]);
49+
50+
const modified_data = useMemo(() => {
51+
if (!messages) return undefined;
52+
53+
// TODO: Remove this filter once all the notifications are implemented
54+
const notifications = messages.filter((notification: { message_key: string }) =>
55+
['p2p-limit-upgrade-available'].includes(notification.message_key)
56+
);
57+
58+
return notifications;
59+
}, [messages]);
2360

2461
useEffect(() => {
25-
const fetchNotifications = async () => {
26-
try {
27-
const response = await fetch('https://fs191x.buildship.run/v4/notification/list', {
28-
headers: {
29-
'Content-Type': 'application/json',
30-
token: localStorage.getItem('authToken') || '',
31-
},
32-
method: 'GET',
33-
});
34-
35-
if (response.ok) {
36-
const data = await response.json();
37-
38-
// TODO: Remove this filter once all the notifications are implemented
39-
const messages = data.filter((notification: { message_key: string }) =>
40-
['p2p-limit-upgrade-available'].includes(notification.message_key)
41-
);
42-
setNotifications(messages);
43-
} else {
44-
// eslint-disable-next-line no-console
45-
console.error('Failed to fetch notifications');
46-
}
47-
} catch (error) {
48-
// eslint-disable-next-line no-console
49-
console.error(error);
50-
}
51-
};
52-
53-
fetchNotifications();
54-
}, []);
62+
// @ts-expect-error Type undefined.
63+
if (data?.notifications_list) {
64+
setMessages(prevMessages => {
65+
// @ts-expect-error Type undefined.
66+
return handleData(data.notifications_list.messages, prevMessages);
67+
});
68+
}
69+
}, [data]);
5570

5671
return {
57-
data: notifications || [],
72+
data: modified_data || [],
73+
...rest,
5874
};
5975
};
6076

src/hooks/api/notification/useNotificationUpdate.ts

+15-17
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,24 @@
1+
import { useMutation } from '@deriv-com/api-hooks';
2+
13
/**
24
* Hook that updates the status of a notification. The notification can be removed or marked as read or unread.
35
*
6+
* @example
7+
* const { data, mutate } = useNotificationUpdate();
8+
* mutate({ notifications_update_status: 'read', ids: [notification_id]});
9+
* mutate({ notifications_update_status: 'unread', ids: [notification_id]});
10+
* mutate({ notifications_update_status: 'remove', ids: []});
411
*/
512
const useNotificationUpdate = () => {
6-
const readAllNotifications = async () => {
7-
try {
8-
await fetch('https://fs191x.buildship.run/v4/notification/read', {
9-
body: JSON.stringify({
10-
authorize: localStorage.getItem('authToken'),
11-
}),
12-
headers: {
13-
'Content-Type': 'application/json',
14-
},
15-
method: 'POST',
16-
});
17-
} catch (error) {
18-
// eslint-disable-next-line no-console
19-
console.error(error);
20-
}
21-
};
13+
const { data, ...rest } = useMutation({
14+
// @ts-expect-error Type undefined. This endpoint will be added to api-hooks.
15+
name: 'notifications_update_status',
16+
});
17+
2218
return {
23-
readAllNotifications,
19+
// @ts-expect-error Type undefined.
20+
data: data?.notifications_update_status,
21+
...rest,
2422
};
2523
};
2624

0 commit comments

Comments
 (0)