Skip to content

Commit

Permalink
view requests only for a specific user
Browse files Browse the repository at this point in the history
  • Loading branch information
abdulrhman500 committed Nov 14, 2023
1 parent 7da797c commit 5bc6b09
Show file tree
Hide file tree
Showing 9 changed files with 300 additions and 65 deletions.
11 changes: 9 additions & 2 deletions client/src/layouts/dashboard/config-navigation.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,13 @@ const navConfig = [
title: 'Doctors',
path: '/doctors',
icon: icon('ic_user')
}, {
},
{
title: 'Upload Documents',
path: '/upload-document',
icon: icon('ic_disabled')
}, {
},
{
title: 'Medical History',
path: '/medical-history',
icon: icon('ic_disabled')
Expand All @@ -52,6 +54,11 @@ const navConfig = [
title: 'Not found',
path: '/404',
icon: icon('ic_disabled')
},
{
title: 'View Requests',
path: '/requests-list',
icon: icon('ic_disabled')
}
];

Expand Down
10 changes: 10 additions & 0 deletions client/src/pages/requests-list.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { DisplayRequestsView } from 'src/sections/upload/displayRequests';

function RequestsListPage() {
return (
<div>
<DisplayRequestsView doctorID={'6551d527e41106082ab7e925'} />
</div>
);
}
export default RequestsListPage;
12 changes: 4 additions & 8 deletions client/src/routes/sections.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const RegisterPage = lazy(() => import('src/pages/register'));
export const ProductsPage = lazy(() => import('src/pages/products'));
export const Page404 = lazy(() => import('src/pages/page-not-found'));
export const DoctorDocumentUploadPage = lazy(() => import('src/pages/doctor-document-upload'));

export const RequestsListPage = lazy(() => import('src/pages/requests-list'));
export const MedicalHistoryPage = lazy(() => import('src/pages/medical-history'));
// ----------------------------------------------------------------------

Expand All @@ -35,13 +35,9 @@ export default function Router() {
{ path: 'products', element: <ProductsPage /> },
{ path: 'blog', element: <BlogPage /> },
{ path: 'doctors', element: <DoctorsPage /> },
{
path: '/upload-document',
element: <DoctorDocumentUploadPage />
}, {
path: '/medical-history',
element: <MedicalHistoryPage />
}
{ path: '/upload-document', element: <DoctorDocumentUploadPage /> },
{ path: '/medical-history', element: <MedicalHistoryPage /> },
{ path: 'requests-list', element: <RequestsListPage /> },
]
},
{
Expand Down
190 changes: 190 additions & 0 deletions client/src/sections/upload/displayRequests.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@

import React, { useEffect, useState } from 'react';
import Modal from '@mui/material/Modal';
import PDFViewer from './viewPDF';
import ImageViewer from './viewImage.jsx';
import IconButton from '@mui/material/IconButton';
import Button from '@mui/material/Button'
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import { axiosInstance } from '../../utils/axiosInstance';
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box';

const List = ({ field, array, doctorID }) => {
const [rows, setRows] = useState([]);

useEffect(() => {
const newRows = array?.map((item, index) => {
let spitedFileName = String(item).split('.');
let extension = spitedFileName[spitedFileName.length - 1];

return (
<Row key={index} doctorID={doctorID} text={index} field={field} extension={extension} />
);
});

setRows(newRows);
}, [array, doctorID, field]);

return (
<div>
{rows}
</div>
);
};

const Row = ({ text, doctorID, field, extension }) => {
const [isExpanded, setIsExpanded] = useState(false);
const [isHovered, setIsHovered] = useState(false);

const toggleExpand = () => {
setIsExpanded(!isExpanded);
};

const rowStyle = {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '10px',
backgroundColor: isExpanded || isHovered ? '#e0f7fa' : 'transparent',
transition: 'background-color 0.3s',
cursor: 'pointer',
border: '1px solid #b2ebf2',
borderRadius: '5px',
marginBottom: '5px',
};

return (
<div>
<div
style={rowStyle}
onClick={toggleExpand}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<div style={{ flex: 1 }}>{text}</div>
<IconButton>
{isExpanded ? <ExpandLessIcon /> : <ExpandMoreIcon />}
</IconButton>
</div>
{isExpanded && <AdditionalContent doctorID={doctorID} text={text} field={field} extension={extension} />}
</div>
);
};

const AdditionalContent = ({ doctorID, text, field, extension }) => {
const [comp, setComp] = useState(<p>{text}</p>);
const [url, setUrl] = useState(`http://localhost:3000/upload/doctor/registration/${doctorID}/${field}/${text}`);

useEffect(() => {
setUrl(`http://localhost:3000/upload/doctor/registration/${doctorID}/${field}/${text}`);
}, [])

useEffect(() => {
console.log("----------", extension, text, "----------")
if (['pdf', 'jpg', 'jpeg', 'png'].includes(String(extension).toLowerCase())) {
setComp(
String(extension).toLowerCase() === 'pdf'
? <PDFViewer pdfURL={url} />
: <ImageViewer url={url} />
);
}
}, [extension, text]);

const contentStyle = {
marginTop: '10px',
marginLeft: '20px',
border: '1px solid #b2ebf2',
borderRadius: '5px',
padding: '10px',
backgroundColor: '#e0f7fa',
};

return (
<div style={contentStyle}>
{comp}
</div>
);
};

const DisplayRequests = ({ doctorID }) => {
const [requests, setRequests] = useState({});

useEffect(() => {
const fetchData = async () => {
try {
const res = await axiosInstance.get(`/upload/doctor/registration/${doctorID}`);
setRequests(res.data.result);
} catch (err) {
console.error(err);
}
};
fetchData();
}, [doctorID]);

const labelStyle = {
fontSize: '18px',
fontWeight: 'bold',
marginBottom: '5px',
};

return (
<div>
<div style={labelStyle}>ID</div>
<List field={"ID"} array={[requests.ID]} doctorID={doctorID} />

<div style={labelStyle}>Licenses</div>
<List field={"licenses"} array={requests.licenses} doctorID={doctorID} />

<div style={labelStyle}>Degree</div>
<List field={"degree"} array={requests.degree} doctorID={doctorID} />
</div>
);
};




const DisplayRequestsView = ({ doctorID }) => {
const [isModalOpen, setIsModalOpen] = useState(false);

const handleOpenModal = () => {
setIsModalOpen(true);
};

const handleCloseModal = () => {
setIsModalOpen(false);
};

return (
<div>
<Button onClick={handleOpenModal}>Open Requests</Button>

<Modal
open={isModalOpen}
onClose={handleCloseModal}
>
<Box sx={{ // Use sx instead of style for styling with Material-UI
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '80%',
maxHeight: '80vh',
overflowY: 'auto',
backgroundColor: 'white', // Add background color if needed
padding: '20px', // Add padding if needed
boxShadow: 24, // Add box shadow if needed
borderRadius: '8px', // Add border radius if needed
}}>
<Typography variant="h6" sx={{ marginBottom: '20px' }}>
Requests
</Typography>
<DisplayRequests doctorID={doctorID} />
</Box>
</Modal>
</div>
);
};
export { DisplayRequestsView };
1 change: 1 addition & 0 deletions client/src/sections/upload/viewImage.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

function ImageViewer({ url }) {
console.log('Image URL:', url); // Log the URL
return (
<div>
<img crossOrigin="use-credentials" src={url} alt="Health record " />
Expand Down
24 changes: 18 additions & 6 deletions server/src/routes/upload.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,19 @@ import multer from 'multer';
import path from 'path';
import { isAuthenticated, isAuthorized } from '../middlewares';
import { medicalHistoryUpload , registrationUpload ,allowedRegistrationFields} from '../middlewares';
import {saveMedicalHistory,removeMedicalHistory,saveRegistrationFiles,getMedicalHistoryURL,getMedicalHistory,getAllRequests} from '../services'
import {saveMedicalHistory,removeMedicalHistory,saveRegistrationFiles,getMedicalHistoryURL,getMedicalHistory,getAllRequests,getRequestFileUrl} from '../services'
const uploadRouter = Router();

uploadRouter.use(isAuthenticated);
uploadRouter.get("/patient/medicalHistory/:recordName", async (req, res) => {

const recordName: string = req.params["recordName"];
console.log(recordName, "-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+")
const fileUrl: any = await getMedicalHistoryURL({ recordName, _id: req.decoded.id });
if (!fileUrl)
return res.status(StatusCodes.NOT_FOUND).send("File not found");

res.status(200).sendFile(fileUrl!);

});
uploadRouter.delete("/patient/medicalHistory/:recordName", (req, res) => {
controller(res)(removeMedicalHistory)(req.decoded.id,req.params.recordName);
Expand All @@ -25,20 +29,28 @@ uploadRouter.get("/patient/medicalHistory/",async (req, res) => {
})
uploadRouter.post("/patient/medicalHistory", medicalHistoryUpload.array("medicalHistory"), (req, res) => {
const fileName = req.body.fileName;
console.log(fileName,"-+-+-+-+-+-");
controller(res)(saveMedicalHistory)( req.decoded.id,req.files,fileName);
});



//-------------------------------------------------------------------------------------------------------------------
uploadRouter.get("/doctor/registration/:doctorID",async (req, res) => {
controller(res)(getAllRequests)(req.params.doctorID);
})
uploadRouter.get("/doctor/registration/:doctorID/:type/:fileIDX",async (req, res) => {
const url = await getRequestFileUrl(req.params.doctorID, req.params.type, req.params.fileIDX);
// console.log(url," ----* -*-*-*-*-*-")
if (!url)
res.status(StatusCodes.NOT_FOUND).send("url not found");
res.status(StatusCodes.OK).sendFile(url!);
})

uploadRouter.use(isAuthorized("Doctor"));
uploadRouter.post("/doctor/registration", registrationUpload.fields(allowedRegistrationFields as any[]),(req, res) => {
controller(res)(saveRegistrationFiles)(req.decoded.id, req.files);
});
uploadRouter.get("/doctor/registration/",async (req, res) => {
controller(res)(getAllRequests)(req.decoded.id);
})

uploadRouter.use((err: any, req: Request, res: Response) => {
if (err instanceof multer.MulterError) {
res.status(500).send(err.message);
Expand Down
44 changes: 1 addition & 43 deletions server/src/services/doctor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,50 +44,8 @@ const getDoctors = async (query: any) => {

return { result: doctors, status: StatusCodes.OK };
};
const getPath = (files: any) => {
console.log(files)

let results = [];
for (let i = 0; i < files.length; i++) {
const idx = files[i].path.indexOf('uploads');
results.push(files[i].path.slice(idx));
}
return results;

}
const saveRegistrationFiles = async (doctorID: string, files: any) => {

const IDFiles = files.ID;
const degreeFiles = files.medicalDegree;
const licensesFields = files.medicalLicenses;

let IDPath: any = IDFiles ? (getPath(IDFiles)![0]) : undefined;
let degreePath: any[] = degreeFiles ? getPath(degreeFiles) : [];
let licensePath: any[] = licensesFields ? getPath(licensesFields) : [];
// Construct the updates object
let updates: any = {
ID: IDPath,
$push: {
degree: { $each: degreePath }, // Use $each for pushing multiple elements
licenses: { $each: licensePath } // Use $each for pushing multiple elements
}
};

// Remove the 'ID' field if it doesn't exist
if (!IDPath) {
delete updates.ID;
}
console.log(updates, "------------");
const results = await Request.findOneAndUpdate({ medicID: doctorID }, updates, { new: true });
// const results = await Request.findOneAndUpdate({ medicID: doctorID }, updates, {new:true});
console.log(results);
return {
result: results,
status: StatusCodes.OK,
message: "Registration Documents uploaded successfully"
}

}
const viewAvailableAppointments = async (doctorID: string) => {
const doctor = await Doctor.findById(doctorID);
if (!doctor) throw new HttpError(StatusCodes.NOT_FOUND, 'Doctor not found');
Expand Down Expand Up @@ -192,4 +150,4 @@ const viewAvailableAppointments = async (doctorID: string) => {
};
};

export { getDoctors, getMyPatients, viewAvailableAppointments, saveRegistrationFiles };
export { getDoctors, getMyPatients, viewAvailableAppointments, };
4 changes: 2 additions & 2 deletions server/src/services/patient.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,14 @@ const getMedicalHistory = async (patientID: String) => {

}
const resolveURL = (url: string) => {
console.log(url, "-----------");
if (!url)
return null;
const parentURL = path.dirname(__dirname);
url = path.join(parentURL, url!);
return url;
}
const getMedicalHistoryURL = async (body: any) => {
let result = await Patient.findOne({ _id: body._id }).select("medicalHistory").lean();
console.log(body,"++++++***-+-+-+-*****--*-*-*-*-")
if (!result)
throw new HttpError(StatusCodes.NOT_FOUND, "not found");
let records = result!["medicalHistory"];
Expand Down
Loading

0 comments on commit 5bc6b09

Please sign in to comment.