diff --git a/backend/src/app/controllers/appointment.controller.ts b/backend/src/app/controllers/appointment.controller.ts index 5cccc6ce..4cdf5b14 100644 --- a/backend/src/app/controllers/appointment.controller.ts +++ b/backend/src/app/controllers/appointment.controller.ts @@ -13,6 +13,7 @@ import { PatientModel } from '../models/patient.model' import { DoctorModel } from '../models/doctor.model' import { type HydratedDocument } from 'mongoose' import { type UserDocument, UserModel } from '../models/user.model' +import { getApprovedDoctorById } from '../services/doctor.service' export const appointmentsRouter = Router() @@ -34,12 +35,17 @@ appointmentsRouter.get( } const filterAppointments = await getfilteredAppointments(query) - res.send( - new GetFilteredAppointmentsResponse( - filterAppointments.map((appointment) => ({ + const appointmentResponses = await Promise.all( + filterAppointments.map(async (appointment) => { + const doctor = await getApprovedDoctorById( + appointment.doctorID.toString() + ) + + return { id: appointment.id, patientID: appointment.patientID.toString(), doctorID: appointment.doctorID.toString(), + doctorName: doctor.name, date: appointment.date, familyID: appointment.familyID || '', reservedFor: appointment.reservedFor || 'Me', @@ -47,9 +53,10 @@ appointmentsRouter.get( new Date(appointment.date) > new Date() ? AppointmentStatus.Upcoming : AppointmentStatus.Completed, - })) - ) + } + }) ) + res.send(new GetFilteredAppointmentsResponse(appointmentResponses)) }) ) diff --git a/backend/src/app/controllers/healthPackage.controller.ts b/backend/src/app/controllers/healthPackage.controller.ts index f91e42c8..4c7d3f9c 100644 --- a/backend/src/app/controllers/healthPackage.controller.ts +++ b/backend/src/app/controllers/healthPackage.controller.ts @@ -146,22 +146,11 @@ healthPackagesRouter.post( '/unsubscribe', [allowAuthenticated, asyncWrapper(allowPatients)], asyncWrapper(async (req, res) => { - const patient = await getPatientByUsername(req.username!) - if (!patient) throw new NotFoundError() - await unSubscribeToHealthPackage({ - id: patient.id, - }) - console.log(patient.healthPackageHistory) - res.status(200).send() - }) -) + const { subscriberId, isFamilyMember } = req.body -healthPackagesRouter.post( - '/:id/unsubscribe', - [allowAuthenticated, asyncWrapper(allowPatients)], - asyncWrapper(async (req, res) => { await unSubscribeToHealthPackage({ - id: req.params.id, + id: subscriberId, + isFamilyMember, }) res.status(200).send() }) @@ -257,10 +246,17 @@ healthPackagesRouter.post( healthPackagesRouter.post( '/patient-cancelled', asyncWrapper(async (req, res) => { - const patient = await getPatientByUsername(req.username!) + const { id, isFamilyMember } = req.body + const model = isFamilyMember + ? await FamilyMemberModel.findById(id) + : await PatientModel.findById(id) + + if (!model) { + throw new NotFoundError() + } + const cancelled: Types.ObjectId[] = [] - if (!patient) throw new NotFoundError() - patient.healthPackageHistory.forEach((healthPackage) => { + model.healthPackageHistory.forEach((healthPackage) => { cancelled.push(healthPackage.healthPackage) }) res.send(cancelled) @@ -270,17 +266,15 @@ healthPackagesRouter.post( healthPackagesRouter.post( '/cancellation-date/:healthPackageId', asyncWrapper(async (req, res) => { - if (!req.username) throw new NotFoundError() - const patient = await getPatientByUsername(req.username) - if (!patient) throw new NotFoundError() - console.log('looking for' + req.params.healthPackageId) - patient.healthPackageHistory.forEach((healthPackage) => { - console.log('history' + healthPackage.healthPackage.toString()) - + const { id, isFamilyMember } = req.body + const model = isFamilyMember + ? await FamilyMemberModel.findById(id) + : await PatientModel.findById(id) + if (!model) throw new NotFoundError() + model.healthPackageHistory.forEach((healthPackage) => { if ( healthPackage.healthPackage.toString() === req.params.healthPackageId ) { - console.log(healthPackage.date.toDateString()) res.send(healthPackage.date.toDateString()) } }) diff --git a/backend/src/app/controllers/patient.controller.ts b/backend/src/app/controllers/patient.controller.ts index 714db71c..20195940 100644 --- a/backend/src/app/controllers/patient.controller.ts +++ b/backend/src/app/controllers/patient.controller.ts @@ -35,9 +35,10 @@ import { type Relation, } from 'clinic-common/types/familyMember.types' import { - AppointmentResponseBase, + AppointmentStatus, GetFilteredAppointmentsResponse, } from 'clinic-common/types/appointment.types' +import { getApprovedDoctorById } from '../services/doctor.service' import { changePassowrd } from '../services/changePassword' import { SUCCESS } from '../utils/httpStatusText' import AppError from '../utils/appError' @@ -298,21 +299,33 @@ patientRouter.get( const { patient, appointments, prescriptions } = await getPatientByID(id) - const filteredAppointments = appointments - .filter((appointment) => appointment.doctorID.toString() === doctor?.id) - .map((appointment) => { - return new AppointmentResponseBase( - appointment.id, - appointment.patientID.toString(), - appointment.doctorID.toString(), - appointment.date, - appointment.familyID, - appointment.reservedFor + const filteredAppointments = appointments.filter( + (appointment) => appointment.doctorID.toString() === doctor?.id + ) + const appointmentResponses = await Promise.all( + filteredAppointments.map(async (appointment) => { + const doctor = await getApprovedDoctorById( + appointment.doctorID.toString() ) + + return { + id: appointment.id, + patientID: appointment.patientID.toString(), + doctorID: appointment.doctorID.toString(), + doctorName: doctor.name, + date: appointment.date, + familyID: appointment.familyID || '', + reservedFor: appointment.reservedFor || 'Me', + status: + new Date(appointment.date) > new Date() + ? AppointmentStatus.Upcoming + : AppointmentStatus.Completed, + } }) + ) const appointmentsRefactored = new GetFilteredAppointmentsResponse( - filteredAppointments + appointmentResponses ) res.send( new GetAPatientResponse( diff --git a/backend/src/app/services/patient.service.ts b/backend/src/app/services/patient.service.ts index 9d35c9fe..4f89a341 100644 --- a/backend/src/app/services/patient.service.ts +++ b/backend/src/app/services/patient.service.ts @@ -201,69 +201,59 @@ export async function subscribeToHealthPackage({ throw new NotFoundError() } + if (model.healthPackage) + await unSubscribeToHealthPackage({ id: patientId, isFamilyMember }) + model.healthPackage = healthPackage.id // Set renewal date to 1 year from now const renewalDate = new Date() renewalDate.setFullYear(renewalDate.getFullYear() + 1) model.healthPackageRenewalDate = renewalDate + const historyIndex = model.healthPackageHistory.findIndex( + (entry) => entry.healthPackage.toString() === healthPackage.id + ) - await model.save() //removed console.log + if (historyIndex !== -1) { + model.healthPackageHistory.splice(historyIndex, 1) + } + + await model.save() } export async function unSubscribeToHealthPackage(params: { id: string + isFamilyMember: boolean }): Promise { - const patient = await PatientModel.findById(params.id) - const familyMember = await FamilyMemberModel.findById(params.id) + const model = params.isFamilyMember + ? await FamilyMemberModel.findById(params.id) + : await PatientModel.findById(params.id) - if (!patient && !familyMember) { + if (!model) { throw new NotFoundError() } - if (patient && patient.healthPackage) { + if (model && model.healthPackage) { // Check if there is existing history with the same healthPackage - const existingItemIndex = patient.healthPackageHistory.findIndex( - (item) => - item.healthPackage.toString() === patient.healthPackage?.toString() - ) - - if (existingItemIndex !== -1) { - // Update the date attribute of the existing item - patient.healthPackageHistory[existingItemIndex].date = new Date() - } else { - // If no existing item, push a new item - patient.healthPackageHistory.push({ - healthPackage: patient.healthPackage, - date: new Date(), - }) - } - - patient.healthPackage = undefined - patient.healthPackageRenewalDate = undefined - await patient.save() - } - - if (familyMember && familyMember.healthPackage) { - const existingItemIndex = familyMember.healthPackageHistory.findIndex( + const existingItemIndex = model.healthPackageHistory.findIndex( (item) => - item.healthPackage.toString() === familyMember.healthPackage?.toString() + item.healthPackage.toString() === model.healthPackage?.toString() ) if (existingItemIndex !== -1) { // Update the date attribute of the existing item - familyMember.healthPackageHistory[existingItemIndex].date = new Date() + model.healthPackageHistory[existingItemIndex].date = new Date() } else { // If no existing item, push a new item - familyMember.healthPackageHistory.push({ - healthPackage: familyMember.healthPackage, + model.healthPackageHistory.push({ + healthPackage: model.healthPackage, date: new Date(), }) } - familyMember.healthPackage = undefined - familyMember.healthPackageRenewalDate = undefined - await familyMember.save() + model.healthPackage = undefined + model.healthPackageRenewalDate = undefined + await model.save() } } diff --git a/clinic-common/types/appointment.types.ts b/clinic-common/types/appointment.types.ts index 901df128..8fe99793 100644 --- a/clinic-common/types/appointment.types.ts +++ b/clinic-common/types/appointment.types.ts @@ -17,6 +17,7 @@ export class AppointmentResponseBase { public id: string, public patientID: string, public doctorID: string, + public doctorName: string, public date: string, public familyID: string, public reservedFor: string diff --git a/clinic-common/types/healthPackage.types.ts b/clinic-common/types/healthPackage.types.ts index 5852a5ea..05c7a28c 100644 --- a/clinic-common/types/healthPackage.types.ts +++ b/clinic-common/types/healthPackage.types.ts @@ -61,3 +61,9 @@ export interface SubscribeToHealthPackageRequest { isFamilyMember: boolean healthPackageId: string } + +export interface UnsubscribeToHealthPackageRequest { + subscriberId: string + payerUsername: string + isFamilyMember: boolean +} diff --git a/frontend/src/api/healthPackages.ts b/frontend/src/api/healthPackages.ts index 3d7ed9f8..bb1675d2 100644 --- a/frontend/src/api/healthPackages.ts +++ b/frontend/src/api/healthPackages.ts @@ -6,6 +6,7 @@ import { GetHealthPackageForPatientResponse, GetHealthPackageResponse, SubscribeToHealthPackageRequest, + UnsubscribeToHealthPackageRequest, UpdateHealthPackageRequest, UpdateHealthPackageResponse, createHealthPackageRequest, @@ -68,9 +69,11 @@ export async function subscribeCreditToHealthPackage( .then((res) => res.data) } -export async function unsubscribeToHealthPackage(): Promise { +export async function unsubscribeToHealthPackage( + params: UnsubscribeToHealthPackageRequest +): Promise { return await api - .post(`/health-packages/unsubscribe`) + .post(`/health-packages/unsubscribe`, params) .then((res) => res.data) } @@ -85,18 +88,23 @@ export async function getHealthPackageForPatient( .then((res) => res.data) } -export async function getCancelledHealthPackagesForPatient(): Promise< - string[] -> { +export async function getCancelledHealthPackagesForPatient(params: { + id: string + isFamilyMember: boolean +}): Promise { return await api - .post(`/health-packages/patient-cancelled`) + .post(`/health-packages/patient-cancelled`, params) .then((res) => res.data) } export async function getCanellationDate( - healthPackageId: string + healthPackageId: string, + params: { id: string; isFamilyMember: boolean } ): Promise { return await api - .post(`/health-packages/cancellation-date/${healthPackageId}`) + .post( + `/health-packages/cancellation-date/${healthPackageId}`, + params + ) .then((res) => res.data) } diff --git a/frontend/src/features/patient-dashboard/routes/Appointments.tsx b/frontend/src/features/patient-dashboard/routes/Appointments.tsx index 45884650..7ab40077 100644 --- a/frontend/src/features/patient-dashboard/routes/Appointments.tsx +++ b/frontend/src/features/patient-dashboard/routes/Appointments.tsx @@ -110,7 +110,7 @@ export function Appointments() { Doctor Name - {appointment.doctorID} + {appointment.doctorName} diff --git a/frontend/src/features/patient-dashboard/routes/FamilyMemberDetails.tsx b/frontend/src/features/patient-dashboard/routes/FamilyMemberDetails.tsx index a62de37e..b4475b7a 100644 --- a/frontend/src/features/patient-dashboard/routes/FamilyMemberDetails.tsx +++ b/frontend/src/features/patient-dashboard/routes/FamilyMemberDetails.tsx @@ -30,7 +30,7 @@ export function FamilyMemberDetails() { label: 'Related to', value: query.data?.patient.name, }, - { + /*{ label: 'Health Package', value: query.data?.familyMember.healthPackage.name || @@ -49,7 +49,7 @@ export function FamilyMemberDetails() { `${historyEntry.package} was cancelled on (${historyEntry.date})` ) .join(', ') || 'No cancelled health packages yet', - }, + },*/ ]} /> diff --git a/frontend/src/features/patient-dashboard/routes/SubscribeToHealthPackages.tsx b/frontend/src/features/patient-dashboard/routes/SubscribeToHealthPackages.tsx index a6904fa3..e7479b46 100644 --- a/frontend/src/features/patient-dashboard/routes/SubscribeToHealthPackages.tsx +++ b/frontend/src/features/patient-dashboard/routes/SubscribeToHealthPackages.tsx @@ -72,26 +72,12 @@ export function SubscribeToHealthPackages({ }), }) const cancelledHealthPackagesQuery = useQuery({ - queryKey: ['cancelled-health-packages'], - queryFn: () => getCancelledHealthPackagesForPatient(), + queryKey: ['cancelled-health-packages', id, isFamilyMember], + queryFn: () => getCancelledHealthPackagesForPatient({ id, isFamilyMember }), }) useEffect(() => { - console.log( - 'cancelledHealthPackagesQuery', - cancelledHealthPackagesQuery.data - ) - }, [cancelledHealthPackagesQuery.data]) - useEffect(() => { - console.log( - 'subscribedHealthPackageQuery', - cancelledHealthPackagesQuery.data - ) - console.log('query.data', query.data) - }, [cancelledHealthPackagesQuery.data, query.data]) - //execute the query - useEffect(() => { - console.log('query', cancelledHealthPackagesQuery.data) - }, [cancelledHealthPackagesQuery.data]) + cancelledHealthPackagesQuery.refetch() + }, [subscribedHealthPackageQuery.data, cancelledHealthPackagesQuery]) const onSuccess = (message: string = 'Subscribed to health package successfully.') => @@ -159,7 +145,10 @@ export function SubscribeToHealthPackages({ try { const dates = await Promise.all( cancelledHealthPackagesQuery.data?.map(async (healthPackage) => { - const date = await getCanellationDate(healthPackage) + const date = await getCanellationDate(healthPackage, { + id, + isFamilyMember, + }) return { id: healthPackage, date } }) ?? [] @@ -177,7 +166,7 @@ export function SubscribeToHealthPackages({ } fetchCancellationDates() - }, [cancelledHealthPackagesQuery.data]) // Dependency on query.data + }, [cancelledHealthPackagesQuery.data, id, isFamilyMember]) // Dependency on query.data if (query.isLoading || subscribedHealthPackageQuery.isLoading) { return @@ -302,7 +291,13 @@ export function SubscribeToHealthPackages({ fullWidth color="secondary" startIcon={} // Replace with cancel icon - onClick={() => cancelMutation.mutateAsync()} + onClick={() => + cancelMutation.mutateAsync({ + subscriberId: id, + payerUsername, + isFamilyMember, + }) + } > Unsubscribe