Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added an option to upload cover image while facility registration (#7297) #9572

Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/Routers/routes/FacilityRoutes.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import CentralNursingStation from "@/components/Facility/CentralNursingStation";
import DischargedPatientsList from "@/components/Facility/DischargedPatientsList";
import { FacilityConfigure } from "@/components/Facility/FacilityConfigure";
import { FacilityCover } from "@/components/Facility/FacilityCover";
import { FacilityCreate } from "@/components/Facility/FacilityCreate";
import { FacilityHome } from "@/components/Facility/FacilityHome";
import { FacilityList } from "@/components/Facility/FacilityList";
Expand All @@ -14,6 +15,9 @@ import FacilityLocationRoutes from "@/Routers/routes/FacilityLocationRoutes";
const FacilityRoutes: AppRoutes = {
"/facility": () => <FacilityList />,
"/facility/create": () => <FacilityCreate />,
"/facility/:facilityId/cover": ({ facilityId }) => (
Copy link
Member

@rithviknishad rithviknishad Dec 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/cover is not very meaningful.

Suggested change
"/facility/:facilityId/cover": ({ facilityId }) => (
"/facility/:facilityId/upload-cover-image": ({ facilityId }) => (

<FacilityCover facilityId={facilityId} />
),
"/facility/:facilityId/update": ({ facilityId }) => (
<FacilityCreate facilityId={facilityId} />
),
Expand Down
104 changes: 104 additions & 0 deletions src/components/Facility/CoverImage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import careConfig from "@careConfig";
import { navigate } from "raviger";
import { useState } from "react";
import { useTranslation } from "react-i18next";

import { LocalStorageKeys } from "@/common/constants";

import * as Notification from "@/Utils/Notifications";
import routes from "@/Utils/request/api";
import request from "@/Utils/request/request";
import uploadFile from "@/Utils/request/uploadFile";
import useTanStackQueryInstead from "@/Utils/request/useQuery";
import { sleep } from "@/Utils/utils";

import AvatarEditModal from "../Common/AvatarEditModal";
import AvatarEditable from "../Common/AvatarEditable";

interface CoverImageProps {
facilityId: string;
}

export const CoverImage = ({ facilityId }: CoverImageProps) => {
const { t } = useTranslation();

const [openUploadModal, setOpenUploadModal] = useState(false);

const { data: facilityData, refetch: facilityFetch } =
useTanStackQueryInstead(routes.getPermittedFacility, {
pathParams: {
id: facilityId,
},
onResponse: ({ res }) => {
if (!res?.ok) {
navigate("/not-found");
}
},
});

const handleCoverImageUpload = async (file: File, onError: () => void) => {
const formData = new FormData();
formData.append("cover_image", file);
const url = `${careConfig.apiUrl}/api/v1/facility/${facilityId}/cover_image/`;

uploadFile(
url,
formData,
"POST",
{
Authorization:
"Bearer " + localStorage.getItem(LocalStorageKeys.accessToken),
},
async (xhr: XMLHttpRequest) => {
if (xhr.status === 200) {
await sleep(1000);
facilityFetch();
Notification.Success({ msg: "Cover image updated." });
setOpenUploadModal(false);
} else {
onError();
}
},
null,
() => {
onError();
},
);
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve upload implementation robustness

Several concerns in the upload implementation:

  1. The API URL construction should use route configuration instead of string concatenation
  2. The artificial sleep delay seems unnecessary
  3. The error handling could be more specific about what went wrong

Consider these improvements:

-const url = `${careConfig.apiUrl}/api/v1/facility/${facilityId}/cover_image/`;
+const url = routes.uploadFacilityCoverImage.path.replace(':id', facilityId);

 uploadFile(
   url,
   formData,
   "POST",
   {
     Authorization:
       "Bearer " + localStorage.getItem(LocalStorageKeys.accessToken),
   },
   async (xhr: XMLHttpRequest) => {
     if (xhr.status === 200) {
-      await sleep(1000);
       facilityFetch();
       Notification.Success({ msg: "Cover image updated." });
       setOpenUploadModal(false);
     } else {
-      onError();
+      const errorMessage = xhr.responseText ? JSON.parse(xhr.responseText).detail : "Failed to upload image";
+      Notification.Error({ msg: errorMessage });
+      onError();
     }
   },
   null,
   () => {
-    onError();
+    Notification.Error({ msg: "Network error while uploading image" });
+    onError();
   },
 );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleCoverImageUpload = async (file: File, onError: () => void) => {
const formData = new FormData();
formData.append("cover_image", file);
const url = `${careConfig.apiUrl}/api/v1/facility/${facilityId}/cover_image/`;
uploadFile(
url,
formData,
"POST",
{
Authorization:
"Bearer " + localStorage.getItem(LocalStorageKeys.accessToken),
},
async (xhr: XMLHttpRequest) => {
if (xhr.status === 200) {
await sleep(1000);
facilityFetch();
Notification.Success({ msg: "Cover image updated." });
setOpenUploadModal(false);
} else {
onError();
}
},
null,
() => {
onError();
},
);
};
const handleCoverImageUpload = async (file: File, onError: () => void) => {
const formData = new FormData();
formData.append("cover_image", file);
const url = routes.uploadFacilityCoverImage.path.replace(':id', facilityId);
uploadFile(
url,
formData,
"POST",
{
Authorization:
"Bearer " + localStorage.getItem(LocalStorageKeys.accessToken),
},
async (xhr: XMLHttpRequest) => {
if (xhr.status === 200) {
facilityFetch();
Notification.Success({ msg: "Cover image updated." });
setOpenUploadModal(false);
} else {
const errorMessage = xhr.responseText ? JSON.parse(xhr.responseText).detail : "Failed to upload image";
Notification.Error({ msg: errorMessage });
onError();
}
},
null,
() => {
Notification.Error({ msg: "Network error while uploading image" });
onError();
},
);
};


const handleCoverImageDelete = async (onError: () => void) => {
const { res } = await request(routes.deleteFacilityCoverImage, {
pathParams: { id: facilityId },
});
if (res?.ok) {
Notification.Success({ msg: "Cover image deleted" });
facilityFetch();
setOpenUploadModal(false);
} else {
onError();
}
};

return (
<div className="my-auto mx-auto flex">
<AvatarEditModal
title={t("edit_cover_photo")}
open={openUploadModal}
imageUrl={facilityData?.read_cover_image_url}
handleUpload={handleCoverImageUpload}
handleDelete={handleCoverImageDelete}
onClose={() => setOpenUploadModal(false)}
/>
<div>
<AvatarEditable
id="facility-coverimage"
imageUrl={facilityData?.read_cover_image_url}
name={facilityData?.name ? facilityData.name : ""}
editable={true}
onClick={() => setOpenUploadModal(true)}
className="md:mr-2 lg:mr-6 md:w-80 md:h-80 lg:h-100 lg:w-100"
/>
</div>
</div>
);
};
75 changes: 75 additions & 0 deletions src/components/Facility/FacilityCover.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { navigate } from "raviger";
import { useEffect } from "react";

import useAuthUser from "@/hooks/useAuthUser";

import * as Notification from "@/Utils/Notifications";

import { Cancel, Submit } from "../Common/ButtonV2";
import Page from "../Common/Page";
import { CoverImage } from "./CoverImage";

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use absolute imports

interface FacilityProps {
facilityId?: string;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why nullable? won't we always have facilityId?

Suggested change
facilityId?: string;
facilityId: string;

}

export const FacilityCover = (props: FacilityProps) => {
const { facilityId } = props;

const authUser = useAuthUser();
useEffect(() => {
if (
authUser &&
authUser.user_type !== "StateAdmin" &&
authUser.user_type !== "DistrictAdmin" &&
authUser.user_type !== "DistrictLabAdmin"
) {
navigate("/facility");
Notification.Error({
msg: "You don't have permission to perform this action. Contact the admin",
});
}
}, [authUser]);

return (
<Page
title="Cover Image"
className="h-[90vh]"
crumbsReplacements={{
[facilityId || "????"]: { name: "Upload" },
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

show the facility name instead of "Upload"

Suggested change
[facilityId || "????"]: { name: "Upload" },
[facilityId]: { name: "Upload" },

}}
>
<div className="md:pt-[10vh] md:pr-[5vw] pt-[5vh]">
<div className="flex flex-col md:flex-row gap-5 relative">
<CoverImage facilityId={facilityId ? facilityId : ""} />
<div className="w-full h-full sm:px-[10vh] md:px-0">
<p className="text-2xl font-extrabold mb-3">
Hover the default cover image to upload a new cover image for your
facility
</p>
<h5>Guidelines for cover image selection</h5>
<ul className="list-disc pl-6 text-sm text-color-body-dark">
<li>Max size for image uploaded should be 1mb</li>
<li>Allowed formats are jpg,png,jpeg</li>
<li>Recommended aspect ratio for the image is 1:1</li>
</ul>
<div className="mt-20 flex flex-col-reverse justify-end gap-3 sm:flex-row md:absolute md:right-0 md:bottom-5">
<Cancel
onClick={() => {
navigate(`/facility/${facilityId}`);
}}
/>
<Submit
type="button"
onClick={() => {
navigate(`/facility/${facilityId}`);
}}
label={"Update Cover Image"}
/>
Comment on lines +72 to +78
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix Submit button behavior

The Submit button currently behaves the same as Cancel, just navigating away. Since it's labeled "Update Cover Image", it should trigger an image update action before navigation.

Consider removing the Submit button since the actual upload is handled by the CoverImage component, or modify it to trigger the upload modal:

 <Submit
   type="button"
   onClick={() => {
-    navigate(`/facility/${facilityId}`);
+    setOpenUploadModal(true);
   }}
   label={"Update Cover Image"}
 />

Committable suggestion skipped: line range outside the PR's diff.

</div>
</div>
</div>
</div>
</Page>
);
};
2 changes: 1 addition & 1 deletion src/components/Facility/FacilityCreate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ export const FacilityCreate = (props: FacilityProps) => {
msg: "Facility updated successfully",
});
}
navigate(`/facility/${id}`);
navigate(`/facility/${id}/cover`);
}
setIsLoading(false);
}
Expand Down
Loading