Auspicious14 commited on
Commit
0cde88f
·
1 Parent(s): 9037c9f

refactor: update referrals auth, routes, fix facility filtering

Browse files

- relocate referrals controller to /health-worker/referrals route and enable JWT auth guard
- extract facility ID from authenticated health worker's user session instead of query params
- fix referral service queries to use correct fromFacilityId field instead of facilityId
- add missing facilityId field to referral creation data
- clean up formatting and indentation in health-worker service files
- fix trailing newline in health-worker controller file

src/health-worker/health-worker.controller.ts CHANGED
@@ -126,4 +126,4 @@ export class HealthWorkerController {
126
  facilityId,
127
  );
128
  }
129
- }
 
126
  facilityId,
127
  );
128
  }
129
+ }
src/health-worker/health-worker.service.ts CHANGED
@@ -16,19 +16,15 @@ export class HealthWorkerService {
16
  private readonly monitoringEngine: MonitoringEngineService,
17
  ) {}
18
 
19
- async getDashboardStats(
20
- facilityId: string,
21
- ) {
22
- const totalPatients =
23
- await this.prisma.patient.count({
24
  where: {
25
  facilityId,
26
  isActive: true,
27
  },
28
  });
29
 
30
- const highRiskPatients =
31
- await this.prisma.patient.count({
32
  where: {
33
  facilityId,
34
  latestRiskLevel: {
@@ -37,16 +33,14 @@ export class HealthWorkerService {
37
  },
38
  });
39
 
40
- const emergencyAlerts =
41
- await this.prisma.alert.count({
42
  where: {
43
  facilityId,
44
  isResolved: false,
45
  },
46
  });
47
 
48
- const upcomingAppointments =
49
- await this.prisma.appointment.count({
50
  where: {
51
  facilityId,
52
  status: "SCHEDULED",
@@ -56,21 +50,17 @@ export class HealthWorkerService {
56
  },
57
  });
58
 
59
- const missedAppointments =
60
- await this.prisma.appointment.count({
61
  where: {
62
  facilityId,
63
  status: "MISSED",
64
  },
65
  });
66
 
67
- const sevenDaysAgo = new Date();
68
- sevenDaysAgo.setDate(
69
- sevenDaysAgo.getDate() - 7,
70
- );
71
 
72
- const newRegistrations =
73
- await this.prisma.patient.count({
74
  where: {
75
  facilityId,
76
  createdAt: {
@@ -79,219 +69,201 @@ export class HealthWorkerService {
79
  },
80
  });
81
 
82
- return {
83
- totalPregnantWomen: totalPatients,
84
- highRiskPatients,
85
- emergencyAlerts,
86
- upcomingAppointments,
87
- missedAppointments,
88
- newRegistrations,
89
- };
90
- }
91
 
92
  /**
93
  * Returns all patients across both registration paths:
94
  * - Health worker registered: sourced from Patient model
95
  * - Self-registered: sourced from UserAuth where role=PATIENT and no Patient record
96
  */
97
- async getAllPatients(
98
- facilityId: string,
99
- ) {
100
- return this.prisma.patient.findMany({
101
- where: {
102
- facilityId,
103
- isActive: true,
104
- },
105
- include: {
106
- facility: {
107
- select: {
108
- name: true,
109
- },
110
  },
111
- userAuth: {
112
- include: {
113
- monitoringStateRecord: true,
114
- bloodPressureReadings: {
115
- orderBy: {
116
- recordedAt: "desc",
117
- },
118
- take: 1,
119
  },
120
- symptomRecords: {
121
- orderBy: {
122
- recordedAt: "desc",
 
 
 
 
 
 
 
 
 
 
 
 
123
  },
124
- take: 1,
125
  },
126
  },
127
  },
128
- },
129
- orderBy: {
130
- createdAt: "desc",
131
- },
132
- });
133
- }
134
 
135
- async getHighRiskPatients(
136
- facilityId: string,
137
- ) {
138
- return this.prisma.patient.findMany({
139
- where: {
140
- facilityId,
141
- latestRiskLevel: {
142
- in: [
143
- "HIGH",
144
- "EMERGENCY",
145
- ],
146
  },
147
- },
148
- include: {
149
- facility: true,
150
- userAuth: {
151
- include: {
152
- monitoringStateRecord: true,
153
- bloodPressureReadings: {
154
- orderBy: {
155
- recordedAt: "desc",
 
156
  },
157
- take: 1,
158
  },
159
  },
160
  },
161
- },
162
- orderBy: {
163
- updatedAt: "desc",
164
- },
165
- });
166
- }
167
 
168
- async getEmergencyAlerts(
169
- facilityId: string,
170
- ) {
171
- return this.prisma.alert.findMany({
172
- where: {
173
- facilityId,
174
- isResolved: false,
175
- },
176
- include: {
177
- patient: {
178
- include: {
179
- userAuth: {
180
- include: {
181
- monitoringStateRecord: true,
182
- symptomRecords: {
183
- orderBy: {
184
- recordedAt: "desc",
185
  },
186
- take: 5,
187
  },
188
  },
189
  },
190
  },
191
  },
192
- },
193
- orderBy: {
194
- createdAt: "desc",
195
- },
196
- });
197
- }
198
 
199
- async getAppointments(
200
- facilityId: string,
201
- ) {
202
- return this.prisma.appointment.findMany({
203
- where: {
204
- facilityId,
205
- },
206
- include: {
207
- patient: true,
208
- facility: true,
209
- userAuth: {
210
- select: {
211
- email: true,
212
- phone: true,
213
  },
214
  },
215
- },
216
- orderBy: {
217
- dateTime: "asc",
218
- },
219
- });
220
- }
221
 
222
- async getPatientById(
223
- id: string,
224
- facilityId: string,
225
- ) {
226
- return this.prisma.patient.findFirst({
227
- where: {
228
- id,
229
- facilityId,
230
- },
231
- include: {
232
- facility: true,
233
- appointments: {
234
- orderBy: {
235
- dateTime: "desc",
236
- },
237
  },
238
- ancVisits: {
239
- orderBy: {
240
- visitDate: "desc",
 
 
 
241
  },
242
- },
243
- alerts: {
244
- orderBy: {
245
- createdAt: "desc",
246
  },
247
- },
248
- referrals: true,
249
- userAuth: {
250
- include: {
251
- profile: true,
252
- monitoringStateRecord: true,
253
- bloodPressureReadings: {
254
- orderBy: {
255
- recordedAt: "desc",
256
- },
257
- take: 20,
258
  },
259
- symptomRecords: {
260
- orderBy: {
261
- recordedAt: "desc",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
  },
263
- take: 20,
264
  },
265
  },
266
  },
267
- },
268
- });
269
- }
270
 
271
- async logPatientBP(
272
- patientId: string,
273
- facilityId: string,
274
- systolic: number,
275
- diastolic: number,
276
- ) {
277
- const patient =
278
- await this.prisma.patient.findFirst({
279
  where: {
280
  id: patientId,
281
  facilityId,
282
  },
283
  });
284
 
285
- if (!patient) {
286
- throw new NotFoundException(
287
- "Patient not found",
288
- );
289
- }
290
 
291
- const userId = patient.userId;
292
 
293
- const previousReadings =
294
- await this.prisma.bloodPressureReading.findMany({
295
  where: {
296
  userId,
297
  },
@@ -301,8 +273,7 @@ export class HealthWorkerService {
301
  take: 5,
302
  });
303
 
304
- const reading =
305
- await this.prisma.bloodPressureReading.create({
306
  data: {
307
  userId,
308
  systolic,
@@ -310,63 +281,48 @@ export class HealthWorkerService {
310
  },
311
  });
312
 
313
- const monitoringResult =
314
- await this.monitoringEngine.evaluate(
315
- userId,
316
- );
317
-
318
- const trend =
319
- this.calculateTrend(
320
- previousReadings,
321
- systolic,
322
- diastolic,
323
- );
324
-
325
- return {
326
- reading,
327
- monitoringResult,
328
- trend,
329
- pointOfCareAlert:
330
- this.buildPointOfCareAlert(
331
  systolic,
332
  diastolic,
333
  trend,
334
  monitoringResult.state,
335
  ),
336
- };
337
- }
338
 
339
  /**
340
  * Resolve an emergency alert
341
  */
342
- async resolveAlert(
343
- alertId: string,
344
- facilityId: string,
345
- ) {
346
- const alert =
347
- await this.prisma.alert.findFirst({
348
  where: {
349
  id: alertId,
350
  facilityId,
351
  },
352
  });
353
 
354
- if (!alert) {
355
- throw new NotFoundException(
356
- "Alert not found",
357
- );
358
- }
359
 
360
- return this.prisma.alert.update({
361
- where: {
362
- id: alertId,
363
- },
364
- data: {
365
- isResolved: true,
366
- resolvedAt: new Date(),
367
- },
368
- });
369
- }
370
 
371
  /**
372
  * Calculate BP trend compared to previous readings
@@ -394,14 +350,12 @@ export class HealthWorkerService {
394
  const systolicChange = currentSystolic - lastReading.systolic;
395
  const diastolicChange = currentDiastolic - lastReading.diastolic;
396
 
397
- const msAgo =
398
- new Date().getTime() - new Date(lastReading.recordedAt).getTime();
399
  const weeksAgo = Math.round(msAgo / (7 * 24 * 60 * 60 * 1000));
400
 
401
  let direction: "rising" | "falling" | "stable";
402
  if (systolicChange >= 5 || diastolicChange >= 5) direction = "rising";
403
- else if (systolicChange <= -5 || diastolicChange <= -5)
404
- direction = "falling";
405
  else direction = "stable";
406
 
407
  return { systolicChange, diastolicChange, direction, weeksAgo };
@@ -427,9 +381,7 @@ export class HealthWorkerService {
427
  level: "emergency",
428
  title: "Severe Hypertension",
429
  message: `BP ${systolic}/${diastolic} mmHg — severely elevated.${
430
- trend.systolicChange !== null
431
- ? ` Rose ${trend.systolicChange} points since last visit.`
432
- : ""
433
  }`,
434
  action:
435
  "Administer antihypertensive immediately. Do not discharge. Prepare for referral to higher facility.",
@@ -446,8 +398,7 @@ export class HealthWorkerService {
446
  level: "urgent",
447
  title: "Rising Blood Pressure",
448
  message: `BP ${systolic}/${diastolic} mmHg — elevated and rising ${trend.systolicChange} points in ${trend.weeksAgo} week(s).`,
449
- action:
450
- "Schedule follow-up within 48 hours. Review symptoms. Consider referral.",
451
  };
452
  }
453
 
@@ -457,8 +408,7 @@ export class HealthWorkerService {
457
  level: "urgent",
458
  title: "Elevated Blood Pressure",
459
  message: `BP ${systolic}/${diastolic} mmHg — above normal threshold.`,
460
- action:
461
- "Recheck in 15 minutes. If still elevated, initiate high-risk protocol.",
462
  };
463
  }
464
 
@@ -467,9 +417,10 @@ export class HealthWorkerService {
467
  return {
468
  level: "warning",
469
  title: "Borderline — Watch Trend",
470
- message: `BP ${systolic}/${diastolic} mmHg — borderline, rising ${trend.systolicChange ?? 0} points since last visit.`,
471
- action:
472
- "Increase monitoring frequency. Recheck at next visit in 2 weeks.",
 
473
  };
474
  }
475
 
 
16
  private readonly monitoringEngine: MonitoringEngineService,
17
  ) {}
18
 
19
+ async getDashboardStats(facilityId: string) {
20
+ const totalPatients = await this.prisma.patient.count({
 
 
 
21
  where: {
22
  facilityId,
23
  isActive: true,
24
  },
25
  });
26
 
27
+ const highRiskPatients = await this.prisma.patient.count({
 
28
  where: {
29
  facilityId,
30
  latestRiskLevel: {
 
33
  },
34
  });
35
 
36
+ const emergencyAlerts = await this.prisma.alert.count({
 
37
  where: {
38
  facilityId,
39
  isResolved: false,
40
  },
41
  });
42
 
43
+ const upcomingAppointments = await this.prisma.appointment.count({
 
44
  where: {
45
  facilityId,
46
  status: "SCHEDULED",
 
50
  },
51
  });
52
 
53
+ const missedAppointments = await this.prisma.appointment.count({
 
54
  where: {
55
  facilityId,
56
  status: "MISSED",
57
  },
58
  });
59
 
60
+ const sevenDaysAgo = new Date();
61
+ sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
 
 
62
 
63
+ const newRegistrations = await this.prisma.patient.count({
 
64
  where: {
65
  facilityId,
66
  createdAt: {
 
69
  },
70
  });
71
 
72
+ return {
73
+ totalPregnantWomen: totalPatients,
74
+ highRiskPatients,
75
+ emergencyAlerts,
76
+ upcomingAppointments,
77
+ missedAppointments,
78
+ newRegistrations,
79
+ };
80
+ }
81
 
82
  /**
83
  * Returns all patients across both registration paths:
84
  * - Health worker registered: sourced from Patient model
85
  * - Self-registered: sourced from UserAuth where role=PATIENT and no Patient record
86
  */
87
+ async getAllPatients(facilityId: string) {
88
+ return this.prisma.patient.findMany({
89
+ where: {
90
+ facilityId,
91
+ isActive: true,
 
 
 
 
 
 
 
 
92
  },
93
+ include: {
94
+ facility: {
95
+ select: {
96
+ name: true,
 
 
 
 
97
  },
98
+ },
99
+ userAuth: {
100
+ include: {
101
+ monitoringStateRecord: true,
102
+ bloodPressureReadings: {
103
+ orderBy: {
104
+ recordedAt: "desc",
105
+ },
106
+ take: 1,
107
+ },
108
+ symptomRecords: {
109
+ orderBy: {
110
+ recordedAt: "desc",
111
+ },
112
+ take: 1,
113
  },
 
114
  },
115
  },
116
  },
117
+ orderBy: {
118
+ createdAt: "desc",
119
+ },
120
+ });
121
+ }
 
122
 
123
+ async getHighRiskPatients(facilityId: string) {
124
+ return this.prisma.patient.findMany({
125
+ where: {
126
+ facilityId,
127
+ latestRiskLevel: {
128
+ in: ["HIGH", "EMERGENCY"],
129
+ },
 
 
 
 
130
  },
131
+ include: {
132
+ facility: true,
133
+ userAuth: {
134
+ include: {
135
+ monitoringStateRecord: true,
136
+ bloodPressureReadings: {
137
+ orderBy: {
138
+ recordedAt: "desc",
139
+ },
140
+ take: 1,
141
  },
 
142
  },
143
  },
144
  },
145
+ orderBy: {
146
+ updatedAt: "desc",
147
+ },
148
+ });
149
+ }
 
150
 
151
+ async getEmergencyAlerts(facilityId: string) {
152
+ return this.prisma.alert.findMany({
153
+ where: {
154
+ facilityId,
155
+ isResolved: false,
156
+ },
157
+ include: {
158
+ patient: {
159
+ include: {
160
+ userAuth: {
161
+ include: {
162
+ monitoringStateRecord: true,
163
+ symptomRecords: {
164
+ orderBy: {
165
+ recordedAt: "desc",
166
+ },
167
+ take: 5,
168
  },
 
169
  },
170
  },
171
  },
172
  },
173
  },
174
+ orderBy: {
175
+ createdAt: "desc",
176
+ },
177
+ });
178
+ }
 
179
 
180
+ async getAppointments(facilityId: string) {
181
+ return this.prisma.appointment.findMany({
182
+ where: {
183
+ facilityId,
184
+ },
185
+ include: {
186
+ patient: true,
187
+ facility: true,
188
+ userAuth: {
189
+ select: {
190
+ email: true,
191
+ phone: true,
192
+ },
 
193
  },
194
  },
195
+ orderBy: {
196
+ dateTime: "asc",
197
+ },
198
+ });
199
+ }
 
200
 
201
+ async getPatientById(id: string, facilityId: string) {
202
+ return this.prisma.patient.findFirst({
203
+ where: {
204
+ id,
205
+ facilityId,
 
 
 
 
 
 
 
 
 
 
206
  },
207
+ include: {
208
+ facility: true,
209
+ appointments: {
210
+ orderBy: {
211
+ dateTime: "desc",
212
+ },
213
  },
214
+ ancVisits: {
215
+ orderBy: {
216
+ visitDate: "desc",
217
+ },
218
  },
219
+ alerts: {
220
+ orderBy: {
221
+ createdAt: "desc",
 
 
 
 
 
 
 
 
222
  },
223
+ },
224
+ referrals: true,
225
+ userAuth: {
226
+ include: {
227
+ profile: true,
228
+ monitoringStateRecord: true,
229
+ bloodPressureReadings: {
230
+ orderBy: {
231
+ recordedAt: "desc",
232
+ },
233
+ take: 20,
234
+ },
235
+ symptomRecords: {
236
+ orderBy: {
237
+ recordedAt: "desc",
238
+ },
239
+ take: 20,
240
  },
 
241
  },
242
  },
243
  },
244
+ });
245
+ }
 
246
 
247
+ async logPatientBP(
248
+ patientId: string,
249
+ facilityId: string,
250
+ systolic: number,
251
+ diastolic: number,
252
+ ) {
253
+ const patient = await this.prisma.patient.findFirst({
 
254
  where: {
255
  id: patientId,
256
  facilityId,
257
  },
258
  });
259
 
260
+ if (!patient) {
261
+ throw new NotFoundException("Patient not found");
262
+ }
 
 
263
 
264
+ const userId = patient.userId;
265
 
266
+ const previousReadings = await this.prisma.bloodPressureReading.findMany({
 
267
  where: {
268
  userId,
269
  },
 
273
  take: 5,
274
  });
275
 
276
+ const reading = await this.prisma.bloodPressureReading.create({
 
277
  data: {
278
  userId,
279
  systolic,
 
281
  },
282
  });
283
 
284
+ const monitoringResult = await this.monitoringEngine.evaluate(userId);
285
+
286
+ const trend = this.calculateTrend(previousReadings, systolic, diastolic);
287
+
288
+ return {
289
+ reading,
290
+ monitoringResult,
291
+ trend,
292
+ pointOfCareAlert: this.buildPointOfCareAlert(
 
 
 
 
 
 
 
 
 
293
  systolic,
294
  diastolic,
295
  trend,
296
  monitoringResult.state,
297
  ),
298
+ };
299
+ }
300
 
301
  /**
302
  * Resolve an emergency alert
303
  */
304
+ async resolveAlert(alertId: string, facilityId: string) {
305
+ const alert = await this.prisma.alert.findFirst({
 
 
 
 
306
  where: {
307
  id: alertId,
308
  facilityId,
309
  },
310
  });
311
 
312
+ if (!alert) {
313
+ throw new NotFoundException("Alert not found");
314
+ }
 
 
315
 
316
+ return this.prisma.alert.update({
317
+ where: {
318
+ id: alertId,
319
+ },
320
+ data: {
321
+ isResolved: true,
322
+ resolvedAt: new Date(),
323
+ },
324
+ });
325
+ }
326
 
327
  /**
328
  * Calculate BP trend compared to previous readings
 
350
  const systolicChange = currentSystolic - lastReading.systolic;
351
  const diastolicChange = currentDiastolic - lastReading.diastolic;
352
 
353
+ const msAgo = new Date().getTime() - new Date(lastReading.recordedAt).getTime();
 
354
  const weeksAgo = Math.round(msAgo / (7 * 24 * 60 * 60 * 1000));
355
 
356
  let direction: "rising" | "falling" | "stable";
357
  if (systolicChange >= 5 || diastolicChange >= 5) direction = "rising";
358
+ else if (systolicChange <= -5 || diastolicChange <= -5) direction = "falling";
 
359
  else direction = "stable";
360
 
361
  return { systolicChange, diastolicChange, direction, weeksAgo };
 
381
  level: "emergency",
382
  title: "Severe Hypertension",
383
  message: `BP ${systolic}/${diastolic} mmHg — severely elevated.${
384
+ trend.systolicChange !== null ? ` Rose ${trend.systolicChange} points since last visit.` : ""
 
 
385
  }`,
386
  action:
387
  "Administer antihypertensive immediately. Do not discharge. Prepare for referral to higher facility.",
 
398
  level: "urgent",
399
  title: "Rising Blood Pressure",
400
  message: `BP ${systolic}/${diastolic} mmHg — elevated and rising ${trend.systolicChange} points in ${trend.weeksAgo} week(s).`,
401
+ action: "Schedule follow-up within 48 hours. Review symptoms. Consider referral.",
 
402
  };
403
  }
404
 
 
408
  level: "urgent",
409
  title: "Elevated Blood Pressure",
410
  message: `BP ${systolic}/${diastolic} mmHg — above normal threshold.`,
411
+ action: "Recheck in 15 minutes. If still elevated, initiate high-risk protocol.",
 
412
  };
413
  }
414
 
 
417
  return {
418
  level: "warning",
419
  title: "Borderline — Watch Trend",
420
+ message: `BP ${systolic}/${diastolic} mmHg — borderline, rising ${
421
+ trend.systolicChange ?? 0
422
+ } points since last visit.`,
423
+ action: "Increase monitoring frequency. Recheck at next visit in 2 weeks.",
424
  };
425
  }
426
 
src/referral/referral.controller.ts CHANGED
@@ -5,44 +5,49 @@ import {
5
  Patch,
6
  Param,
7
  Body,
8
- Query,
9
  UseGuards,
 
10
  } from "@nestjs/common";
 
11
  import { ReferralsService, UpdateReferralDto } from "./referral.service";
12
  import { CreateReferralDto } from "./dto/create-referral-dto";
13
- // import { JwtAuthGuard } from "../auth/guards/jwt-auth.guard";
14
- // import { RolesGuard } from "../auth/guards/roles.guard";
15
 
16
- // @UseGuards(JwtAuthGuard, RolesGuard)
17
- @Controller("referrals")
18
  export class ReferralsController {
19
  constructor(private readonly referralsService: ReferralsService) {}
20
 
21
- /** POST /referrals */
22
  @Post()
23
- create(@Body() dto: CreateReferralDto, facilityId: string) {
 
24
  return this.referralsService.create(dto, facilityId);
25
  }
26
 
27
- /** GET /referrals?facilityId=xxx */
28
  @Get()
29
- findAll(@Query("facilityId") facilityId?: string) {
 
30
  return this.referralsService.findAll(facilityId);
31
  }
32
 
33
- /** GET /referrals/stats?facilityId=xxx */
34
  @Get("stats")
35
- getStats(@Query("facilityId") facilityId?: string) {
 
36
  return this.referralsService.getReferralStats(facilityId);
37
  }
38
 
39
  @Get(":id")
40
- findOne(@Param("id") id: string) {
41
- return this.referralsService.findOne(id);
 
42
  }
43
 
44
  @Patch(":id/status")
45
- updateStatus(@Param("id") id: string, @Body() dto: UpdateReferralDto) {
46
- return this.referralsService.updateStatus(id, dto);
 
47
  }
48
  }
 
5
  Patch,
6
  Param,
7
  Body,
 
8
  UseGuards,
9
+ Req,
10
  } from "@nestjs/common";
11
+ import { Request } from "express";
12
  import { ReferralsService, UpdateReferralDto } from "./referral.service";
13
  import { CreateReferralDto } from "./dto/create-referral-dto";
14
+ import { JwtAuthGuard } from "../auth/guards/jwt-auth.guard";
 
15
 
16
+ @Controller("health-worker/referrals")
17
+ @UseGuards(JwtAuthGuard)
18
  export class ReferralsController {
19
  constructor(private readonly referralsService: ReferralsService) {}
20
 
21
+ /** POST /health-worker/referrals */
22
  @Post()
23
+ create(@Body() dto: CreateReferralDto, @Req() req: Request & { user: any }) {
24
+ const facilityId = req.user.healthcareWorker?.facilityId;
25
  return this.referralsService.create(dto, facilityId);
26
  }
27
 
28
+ /** GET /health-worker/referrals */
29
  @Get()
30
+ findAll(@Req() req: Request & { user: any }) {
31
+ const facilityId = req.user.healthcareWorker?.facilityId;
32
  return this.referralsService.findAll(facilityId);
33
  }
34
 
35
+ /** GET /health-worker/referrals/stats */
36
  @Get("stats")
37
+ getStats(@Req() req: Request & { user: any }) {
38
+ const facilityId = req.user.healthcareWorker?.facilityId;
39
  return this.referralsService.getReferralStats(facilityId);
40
  }
41
 
42
  @Get(":id")
43
+ findOne(@Param("id") id: string, @Req() req: Request & { user: any }) {
44
+ const facilityId = req.user.healthcareWorker?.facilityId;
45
+ return this.referralsService.findOne(id, facilityId);
46
  }
47
 
48
  @Patch(":id/status")
49
+ updateStatus(@Param("id") id: string, @Body() dto: UpdateReferralDto, @Req() req: Request & { user: any }) {
50
+ const facilityId = req.user.healthcareWorker?.facilityId;
51
+ return this.referralsService.updateStatus(id, dto, facilityId);
52
  }
53
  }
src/referral/referral.service.ts CHANGED
@@ -38,6 +38,7 @@ export class ReferralsService {
38
  patientId: patient.id,
39
  fromFacilityId: facilityId,
40
  toFacilityId: dto.toFacilityId,
 
41
  reason: dto.reason,
42
  notes: dto.notes,
43
  },
@@ -70,7 +71,7 @@ export class ReferralsService {
70
 
71
  async findAll(facilityId?: string) {
72
  return this.prisma.referral.findMany({
73
- where: facilityId ? { facilityId } : undefined,
74
  include: {
75
  patient: {
76
  select: {
@@ -87,15 +88,18 @@ export class ReferralsService {
87
  },
88
  },
89
  },
90
- facility: { select: { name: true, address: true } },
91
  },
92
  orderBy: { createdAt: "desc" },
93
  });
94
  }
95
 
96
- async findOne(id: string) {
 
 
 
97
  const referral = await this.prisma.referral.findUnique({
98
- where: { id },
99
  include: {
100
  patient: {
101
  include: {
@@ -110,7 +114,7 @@ export class ReferralsService {
110
  },
111
  },
112
  },
113
- facility: true,
114
  },
115
  });
116
 
@@ -118,8 +122,8 @@ export class ReferralsService {
118
  return referral;
119
  }
120
 
121
- async updateStatus(id: string, dto: UpdateReferralDto) {
122
- await this.findOne(id);
123
  return this.prisma.referral.update({
124
  where: { id },
125
  data: { status: dto.status },
@@ -127,13 +131,13 @@ export class ReferralsService {
127
  patient: {
128
  select: { firstName: true, lastName: true, patientId: true },
129
  },
130
- facility: { select: { name: true } },
131
  },
132
  });
133
  }
134
 
135
  async getReferralStats(facilityId?: string) {
136
- const where = facilityId ? { facilityId } : {};
137
 
138
  const [total, pending, accepted, completed, cancelled] = await Promise.all([
139
  this.prisma.referral.count({ where }),
 
38
  patientId: patient.id,
39
  fromFacilityId: facilityId,
40
  toFacilityId: dto.toFacilityId,
41
+ facilityId: facilityId,
42
  reason: dto.reason,
43
  notes: dto.notes,
44
  },
 
71
 
72
  async findAll(facilityId?: string) {
73
  return this.prisma.referral.findMany({
74
+ where: facilityId ? { fromFacilityId: facilityId } : undefined,
75
  include: {
76
  patient: {
77
  select: {
 
88
  },
89
  },
90
  },
91
+ fromFacility: { select: { name: true, address: true } },
92
  },
93
  orderBy: { createdAt: "desc" },
94
  });
95
  }
96
 
97
+ async findOne(id: string, facilityId?: string) {
98
+ const where: any = { id };
99
+ if (facilityId) where.fromFacilityId = facilityId;
100
+
101
  const referral = await this.prisma.referral.findUnique({
102
+ where,
103
  include: {
104
  patient: {
105
  include: {
 
114
  },
115
  },
116
  },
117
+ fromFacility: true,
118
  },
119
  });
120
 
 
122
  return referral;
123
  }
124
 
125
+ async updateStatus(id: string, dto: UpdateReferralDto, facilityId?: string) {
126
+ await this.findOne(id, facilityId);
127
  return this.prisma.referral.update({
128
  where: { id },
129
  data: { status: dto.status },
 
131
  patient: {
132
  select: { firstName: true, lastName: true, patientId: true },
133
  },
134
+ fromFacility: { select: { name: true } },
135
  },
136
  });
137
  }
138
 
139
  async getReferralStats(facilityId?: string) {
140
+ const where = facilityId ? { fromFacilityId: facilityId } : {};
141
 
142
  const [total, pending, accepted, completed, cancelled] = await Promise.all([
143
  this.prisma.referral.count({ where }),