Skip to content

Commit

Permalink
Replace useDispatch w. useQuery/request: Notifications (src/Component…
Browse files Browse the repository at this point in the history
…s/Notifications/**) #6392 (#6543)

* Add only imports. other functionality and changes in code to be complited later

* ShowPushNotification - change useDispatch with useQuery, old code is on the comments, add model.tsx in to folder notifications and add references into api.tsx

* Complete ShowPushNotification.tsx and NoticeBoard.tsx - change useDispatch with useQuery

* Complete ShowPushNotification.tsx and NoticeBoard.tsx - change useDispatch with useQuery, delete all commnets of old code

* Complete NotificationsList.tsx - change useDispatch with useQuery, delete all commnets of old code

* deleting all comments

* code modification according to requests

* back the original content of package-lock.json from origin branch

---------

Co-authored-by: Adrián Sliva <[email protected]>
  • Loading branch information
adriansliva and Adrián Sliva authored Nov 7, 2023
1 parent e8091bf commit bf932d5
Show file tree
Hide file tree
Showing 6 changed files with 106 additions and 82 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 8 additions & 28 deletions src/Components/Notifications/NoticeBoard.tsx
Original file line number Diff line number Diff line change
@@ -1,43 +1,23 @@
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { getNotifications } from "../../Redux/actions";
import Page from "../Common/components/Page";
import Loading from "../Common/Loading";
import { formatDateTime } from "../../Utils/utils";
import { useTranslation } from "react-i18next";
import CareIcon from "../../CAREUI/icons/CareIcon";
import useQuery from "../../Utils/request/useQuery";
import routes from "../../Redux/api";

export const NoticeBoard = () => {
const dispatch: any = useDispatch();
const [isLoading, setIsLoading] = useState(true);
const [data, setData] = useState<any[]>([]);
const { t } = useTranslation();

useEffect(() => {
setIsLoading(true);
dispatch(
getNotifications(
{ offset: 0, event: "MESSAGE", medium_sent: "SYSTEM" },
new Date().getTime().toString()
)
)
.then((res: any) => {
if (res && res.data) {
setData(res.data.results);
}
setIsLoading(false);
})
.catch(() => {
setIsLoading(false);
});
}, [dispatch]);
const { data, loading } = useQuery(routes.getNotifications, {
query: { offset: 0, event: "MESSAGE", medium_sent: "SYSTEM" },
});

let notices;

if (data?.length) {
if (data?.results.length) {
notices = (
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-3">
{data.map((item) => (
{data.results.map((item) => (
<div
key={`usr_${item.id}`}
className="overflow-hidden rounded shadow-md"
Expand Down Expand Up @@ -71,7 +51,7 @@ export const NoticeBoard = () => {
);
}

if (isLoading) return <Loading />;
if (loading) return <Loading />;
return (
<Page title={t("Notice Board")} hideBack={true} breadcrumbs={false}>
<div>{notices}</div>
Expand Down
63 changes: 33 additions & 30 deletions src/Components/Notifications/NotificationsList.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
import { navigate } from "raviger";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import {
getNotifications,
markNotificationAsRead,
getUserPnconfig,
updateUserPnconfig,
getPublicKey,
} from "../../Redux/actions";
import Spinner from "../Common/Spinner";
import { NOTIFICATION_EVENTS } from "../../Common/constants";
import { Error } from "../../Utils/Notifications.js";
Expand All @@ -24,6 +16,8 @@ import SelectMenuV2 from "../Form/SelectMenuV2";
import { useTranslation } from "react-i18next";
import CircularProgress from "../Common/components/CircularProgress";
import useAuthUser from "../../Common/hooks/useAuthUser";
import request from "../../Utils/request/request";
import routes from "../../Redux/api";

const RESULT_LIMIT = 14;

Expand All @@ -38,14 +32,16 @@ const NotificationTile = ({
onClickCB,
setShowNotifications,
}: NotificationTileProps) => {
const dispatch: any = useDispatch();
const [result, setResult] = useState(notification);
const [isMarkingAsRead, setIsMarkingAsRead] = useState(false);
const { t } = useTranslation();

const handleMarkAsRead = async () => {
setIsMarkingAsRead(true);
await dispatch(markNotificationAsRead(result.id));
await request(routes.markNotificationAsRead, {
pathParams: { id: result.id },
body: { read_at: new Date() },
});
setResult({ ...result, read_at: new Date() });
setIsMarkingAsRead(false);
};
Expand Down Expand Up @@ -153,7 +149,6 @@ export default function NotificationsList({
handleOverflow,
}: NotificationsListProps) {
const { username } = useAuthUser();
const dispatch: any = useDispatch();
const [data, setData] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [offset, setOffset] = useState(0);
Expand All @@ -180,12 +175,14 @@ export default function NotificationsList({

const intialSubscriptionState = async () => {
try {
const res = await dispatch(getUserPnconfig({ username: username }));
const res = await request(routes.getUserPnconfig, {
pathParams: { username: username },
});
const reg = await navigator.serviceWorker.ready;
const subscription = await reg.pushManager.getSubscription();
if (!subscription && !res?.data?.pf_endpoint) {
if (!subscription && !res.data?.pf_endpoint) {
setIsSubscribed("NotSubscribed");
} else if (subscription?.endpoint === res?.data?.pf_endpoint) {
} else if (subscription?.endpoint === res.data?.pf_endpoint) {
setIsSubscribed("SubscribedOnThisDevice");
} else {
setIsSubscribed("SubscribedOnAnotherDevice");
Expand Down Expand Up @@ -247,9 +244,11 @@ export default function NotificationsList({
pf_p256dh: "",
pf_auth: "",
};
await dispatch(
updateUserPnconfig(data, { username: username })
);

await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});

setIsSubscribed("NotSubscribed");
setIsSubscribing(false);
Expand All @@ -271,8 +270,8 @@ export default function NotificationsList({

async function subscribe() {
setIsSubscribing(true);
const response = await dispatch(getPublicKey());
const public_key = response.data.public_key;
const response = await request(routes.getPublicKey);
const public_key = response.data?.public_key;
const sw = await navigator.serviceWorker.ready;
const push = await sw.pushManager.subscribe({
userVisibleOnly: true,
Expand All @@ -297,11 +296,12 @@ export default function NotificationsList({
pf_auth: auth,
};

const res = await dispatch(
updateUserPnconfig(data, { username: username })
);
const { res } = await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});

if (res.status >= 200 && res.status <= 300) {
if (res?.ok) {
setIsSubscribed("SubscribedOnThisDevice");
}
setIsSubscribing(false);
Expand All @@ -310,8 +310,11 @@ export default function NotificationsList({
const handleMarkAllAsRead = async () => {
setIsMarkingAllAsRead(true);
await Promise.all(
data.map(async (notification) => {
return await dispatch(markNotificationAsRead(notification.id));
data.map((notification) => {
return request(routes.markNotificationAsRead, {
pathParams: { id: notification.id },
body: { read_at: new Date() },
});
})
);
setReload(!reload);
Expand All @@ -320,10 +323,10 @@ export default function NotificationsList({

useEffect(() => {
setIsLoading(true);
dispatch(
getNotifications({ offset, event: eventFilter, medium_sent: "SYSTEM" })
)
.then((res: any) => {
request(routes.getNotifications, {
query: { offset, event: eventFilter, medium_set: "SYSTEM" },
})
.then((res) => {
if (res && res.data) {
setData(res.data.results);
setUnreadCount(
Expand All @@ -341,7 +344,7 @@ export default function NotificationsList({
setOffset((prev) => prev - RESULT_LIMIT);
});
intialSubscriptionState();
}, [dispatch, reload, open, offset, eventFilter, isSubscribed]);
}, [reload, open, offset, eventFilter, isSubscribed]);

if (!offset && isLoading) {
manageResults = (
Expand Down
43 changes: 20 additions & 23 deletions src/Components/Notifications/ShowPushNotification.tsx
Original file line number Diff line number Diff line change
@@ -1,43 +1,40 @@
import { useDispatch } from "react-redux";
import { getNotificationData } from "../../Redux/actions";
import { useEffect } from "react";
import { DetailRoute } from "../../Routers/types";
import useQuery from "../../Utils/request/useQuery";
import routes from "../../Redux/api";
import { NotificationData } from "./models";

export default function ShowPushNotification({ id }: DetailRoute) {
const dispatch: any = useDispatch();
useQuery(routes.getNotificationData, {
pathParams: { id },
onResponse(res) {
if (res.data) {
window.location.href = resultUrl(res.data);
}
},
});

const resultUrl = async () => {
const res = await dispatch(getNotificationData({ id }));
const data = res.data.caused_objects;
switch (res.data.event) {
const resultUrl = ({ caused_objects, event }: NotificationData) => {
switch (event) {
case "PATIENT_CREATED":
return `/facility/${data.facility}/patient/${data.patient}`;
return `/facility/${caused_objects?.facility}/patient/${caused_objects?.patient}`;
case "PATIENT_UPDATED":
return `/facility/${data.facility}/patient/${data.patient}`;
return `/facility/${caused_objects?.facility}/patient/${caused_objects?.patient}`;
case "PATIENT_CONSULTATION_CREATED":
return `/facility/${data.facility}/patient/${data.patient}/consultation/${data.consultation}`;
return `/facility/${caused_objects?.facility}/patient/${caused_objects?.patient}/consultation/${caused_objects?.consultation}`;
case "PATIENT_CONSULTATION_UPDATED":
return `/facility/${data.facility}/patient/${data.patient}/consultation/${data.consultation}`;
return `/facility/${caused_objects?.facility}/patient/${caused_objects?.patient}/consultation/${caused_objects?.consultation}`;
case "PATIENT_CONSULTATION_UPDATE_CREATED":
return `/facility/${data.facility}/patient/${data.patient}/consultation/${data.consultation}/daily-rounds/${data.daily_round}`;
return `/facility/${caused_objects?.facility}/patient/${caused_objects?.patient}/consultation/${caused_objects?.consultation}/daily-rounds/${caused_objects?.daily_round}`;
case "PATIENT_CONSULTATION_UPDATE_UPDATED":
return `/facility/${data.facility}/patient/${data.patient}/consultation/${data.consultation}/daily-rounds/${data.daily_round}`;
return `/facility/${caused_objects?.facility}/patient/${caused_objects?.patient}/consultation/${caused_objects?.consultation}/daily-rounds/${caused_objects?.daily_round}`;
case "INVESTIGATION_SESSION_CREATED":
return `/facility/${data.facility}/patient/${data.patient}/consultation/${data.consultation}/investigation/${data.session}`;
return `/facility/${caused_objects?.facility}/patient/${caused_objects?.patient}/consultation/${caused_objects?.consultation}/investigation/${caused_objects?.session}`;
case "MESSAGE":
return "/notice_board/";
default:
return "#";
}
};

useEffect(() => {
resultUrl()
.then((url) => {
window.location.href = url;
})
.catch((err) => console.log(err));
}, []);

return <></>;
}
29 changes: 29 additions & 0 deletions src/Components/Notifications/models.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export interface NotificationData {
id: string;
title: string;
caused_objects: cause_object;
caused_by: any;
content: string;
offset: number;
event: string;
event_type: string;
medium_sent: string;
created_date: string;
read_at: string;
message: string;
public_key: string;
}

export interface cause_object {
facility: string;
patient: string;
consultation: string;
daily_round: string;
session: string;
}

export interface PNconfigData {
pf_auth: string;
pf_endpoint: string;
pf_p256dh: string;
}
15 changes: 15 additions & 0 deletions src/Redux/api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ import {
} from "../Components/ExternalResult/models";
import { UserModel } from "../Components/Users/models";
import { PaginatedResponse } from "../Utils/request/types";
import {
NotificationData,
PNconfigData,
} from "../Components/Notifications/models";
import { PatientModel } from "../Components/Patient/models";
import { IComment, IResource } from "../Components/Resource/models";

Expand Down Expand Up @@ -204,11 +208,14 @@ const routes = {

getUserPnconfig: {
path: "/api/v1/users/{username}/pnconfig/",
method: "GET",
TRes: Type<PNconfigData>(),
},

updateUserPnconfig: {
path: "/api/v1/users/{username}/pnconfig/",
method: "PATCH",
TRes: Type<PNconfigData>(),
},

// Skill Endpoints
Expand Down Expand Up @@ -770,19 +777,27 @@ const routes = {
path: "/api/v1/shift/{id}/comment/",
method: "POST",
},

// Notifications
getNotifications: {
path: "/api/v1/notification/",
method: "GET",
TRes: Type<PaginatedResponse<NotificationData>>(),
},
getNotificationData: {
path: "/api/v1/notification/{id}/",
method: "GET",
TRes: Type<NotificationData>(),
},
markNotificationAsRead: {
path: "/api/v1/notification/{id}/",
method: "PATCH",
TRes: Type<NotificationData>(),
},
getPublicKey: {
path: "/api/v1/notification/public_key/",
method: "GET",
TRes: Type<NotificationData>(),
},
sendNotificationMessages: {
path: "/api/v1/notification/notify/",
Expand Down

0 comments on commit bf932d5

Please sign in to comment.