@blackcode_sa/metaestetics-api 1.6.2 → 1.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/admin/index.d.mts +228 -25
  2. package/dist/admin/index.d.ts +228 -25
  3. package/dist/admin/index.js +35867 -2493
  4. package/dist/admin/index.mjs +35856 -2464
  5. package/dist/backoffice/index.d.mts +252 -1
  6. package/dist/backoffice/index.d.ts +252 -1
  7. package/dist/backoffice/index.js +86 -12
  8. package/dist/backoffice/index.mjs +86 -13
  9. package/dist/index.d.mts +1417 -554
  10. package/dist/index.d.ts +1417 -554
  11. package/dist/index.js +1393 -687
  12. package/dist/index.mjs +1423 -711
  13. package/package.json +1 -1
  14. package/src/admin/index.ts +15 -1
  15. package/src/admin/notifications/notifications.admin.ts +1 -1
  16. package/src/admin/requirements/README.md +128 -0
  17. package/src/admin/requirements/patient-requirements.admin.service.ts +482 -0
  18. package/src/index.ts +16 -1
  19. package/src/services/appointment/appointment.service.ts +315 -86
  20. package/src/services/clinic/clinic-admin.service.ts +3 -0
  21. package/src/services/clinic/clinic-group.service.ts +8 -0
  22. package/src/services/documentation-templates/documentation-template.service.ts +24 -16
  23. package/src/services/documentation-templates/filled-document.service.ts +253 -136
  24. package/src/services/patient/patient.service.ts +31 -1
  25. package/src/services/patient/patientRequirements.service.ts +285 -0
  26. package/src/services/patient/utils/practitioner.utils.ts +79 -1
  27. package/src/types/appointment/index.ts +134 -10
  28. package/src/types/documentation-templates/index.ts +34 -2
  29. package/src/types/notifications/README.md +77 -0
  30. package/src/types/notifications/index.ts +154 -27
  31. package/src/types/patient/index.ts +6 -0
  32. package/src/types/patient/patient-requirements.ts +81 -0
  33. package/src/validations/appointment.schema.ts +300 -62
  34. package/src/validations/documentation-templates/template.schema.ts +55 -0
  35. package/src/validations/documentation-templates.schema.ts +9 -14
  36. package/src/validations/notification.schema.ts +3 -3
  37. package/src/validations/patient/patient-requirements.schema.ts +75 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@blackcode_sa/metaestetics-api",
3
3
  "private": false,
4
- "version": "1.6.2",
4
+ "version": "1.6.4",
5
5
  "description": "Firebase authentication service with anonymous upgrade support",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.mjs",
@@ -30,6 +30,9 @@ import { PractitionerInviteMailingService } from "./mailing/practitionerInvite/p
30
30
  // Import booking services
31
31
  import { BookingAdmin } from "./booking/booking.admin";
32
32
 
33
+ // Import patient requirements services
34
+ import { PatientRequirementsAdminService } from "./requirements/patient-requirements.admin.service";
35
+
33
36
  // Re-export types
34
37
  export type {
35
38
  Notification,
@@ -37,7 +40,6 @@ export type {
37
40
  PreRequirementNotification,
38
41
  PostRequirementNotification,
39
42
  AppointmentReminderNotification,
40
- AppointmentNotification,
41
43
  } from "../types/notifications";
42
44
 
43
45
  // Re-export types needed by cloud functions
@@ -64,6 +66,7 @@ export {
64
66
  PractitionerAggregationService,
65
67
  ProcedureAggregationService,
66
68
  PatientAggregationService,
69
+ PatientRequirementsAdminService,
67
70
  };
68
71
 
69
72
  // Export mailing services
@@ -75,6 +78,17 @@ export { BookingAdmin };
75
78
  // Also export booking types
76
79
  export * from "./booking/booking.types";
77
80
 
81
+ // Re-export types needed by admin services that might not be covered by general type exports
82
+ export type {
83
+ PatientRequirementInstance,
84
+ PatientRequirementInstruction,
85
+ } from "../types/patient/patient-requirements";
86
+ export {
87
+ PatientInstructionStatus,
88
+ PatientRequirementOverallStatus,
89
+ PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME,
90
+ } from "../types/patient/patient-requirements";
91
+
78
92
  /**
79
93
  * Main entry point for the Admin module.
80
94
  * This module contains services and utilities intended for administrative tasks,
@@ -56,7 +56,7 @@ export class NotificationsAdmin {
56
56
  /**
57
57
  * Ažurira status notifikacije
58
58
  */
59
- private async updateNotificationStatus(
59
+ public async updateNotificationStatus(
60
60
  notificationId: string,
61
61
  status: NotificationStatus,
62
62
  error?: string
@@ -0,0 +1,128 @@
1
+ # Patient Requirements Admin Service (`patient-requirements.admin.service.ts`)
2
+
3
+ ## Overview
4
+
5
+ The `PatientRequirementsAdminService` is a backend service responsible for managing administrative tasks related to `PatientRequirementInstance` documents, primarily focusing on the lifecycle of associated patient notifications. This service is designed to be primarily invoked by Cloud Functions that trigger on Create, Update, and Delete events of `PatientRequirementInstance` documents in Firestore.
6
+
7
+ It ensures that patients receive timely notifications for instructions they need to follow before an appointment and that these notifications are appropriately updated or cancelled if the appointment or requirement details change.
8
+
9
+ ## Core Dependencies
10
+
11
+ - **Firebase Admin SDK**: For interacting with Firestore.
12
+ - **`NotificationsAdmin` Service**: For creating, fetching, and updating notification documents.
13
+ - **Shared Types**: Uses types defined in `Api/src/types/` for `PatientRequirementInstance`, `PatientInstruction`, `Notification`, `PatientProfile`, etc., ensuring consistency across the application. This includes using client-side `Timestamp` types (`@firebase/firestore.Timestamp`) for data stored in Firestore documents that are also accessed by the client.
14
+
15
+ ## Methods
16
+
17
+ ### 1. `constructor(firestore?: admin.firestore.Firestore)`
18
+
19
+ - **Purpose**: Initializes the service.
20
+ - **Parameters**:
21
+ - `firestore` (optional): An instance of `admin.firestore.Firestore`. If not provided, it initializes a new default instance.
22
+ - **Core Logic**:
23
+ 1. Sets up the Firestore database connection (`this.db`).
24
+ 2. Initializes an instance of the `NotificationsAdmin` service (`this.notificationsAdmin`), passing the Firestore instance to it.
25
+
26
+ ### 2. `async processRequirementInstanceAndScheduleNotifications(patientId: string, instance: PatientRequirementInstance, previousInstanceData?: PatientRequirementInstance)`
27
+
28
+ - **Purpose**: This is the primary method for handling the creation and updates of a `PatientRequirementInstance`. It iterates through the instructions within the instance, schedules new notifications, cancels outdated ones, and updates the instruction statuses and notification IDs within the `PatientRequirementInstance` document.
29
+ - **Parameters**:
30
+ - `patientId: string`: The ID of the patient to whom the requirement instance belongs.
31
+ - `instance: PatientRequirementInstance`: The current (new or updated) data of the patient requirement instance.
32
+ - `previousInstanceData?: PatientRequirementInstance` (optional): The state of the instance _before_ the current change. This is crucial for determining if due times have changed or if instructions were cancelled/reactivated, necessitating changes to existing notifications.
33
+ - **Core Logic Flow**:
34
+ 1. **Fetch Patient Expo Tokens**: Retrieves the patient's Expo push notification tokens from their `PatientProfile`. If no tokens are found, notification scheduling for that patient is skipped.
35
+ 2. **Iterate Through Instructions**: Loops through each `PatientRequirementInstruction` in the `instance.instructions` array.
36
+ - A copy of the instructions array (`updatedInstructions`) is made to track changes without mutating the input directly.
37
+ 3. **Handle Cancelled/Superseded Instances/Instructions**:
38
+ - If the overall `instance.overallStatus` indicates a cancelled appointment or a superseded reschedule, or if an individual `currentInstruction.status` is `CANCELLED`:
39
+ - If the instruction had an existing `notificationId`, calls `this.notificationsAdmin.updateNotificationStatus()` to set the notification's status to `CANCELLED`.
40
+ - Updates the `currentInstruction`'s `notificationId` to `undefined` and its `status` to `CANCELLED`.
41
+ - Marks that `instructionUpdatesMade` is `true`.
42
+ 4. **Handle Reschedules/Reactivations for Existing Notifications**:
43
+ - Compares `currentInstruction` with `previousInstruction` (if available).
44
+ - Determines if `dueTimeChanged` or if the instruction `wasPreviouslyCancelledAndNowActive`.
45
+ - If either is true AND the `currentInstruction` has a `notificationId` (meaning an old notification exists):
46
+ - Cancels the old notification using `this.notificationsAdmin.updateNotificationStatus()`.
47
+ - Clears `currentInstruction.notificationId`.
48
+ - Marks `instructionUpdatesMade` as `true`.
49
+ 5. **Schedule New Notifications**:
50
+ - Checks if a notification `shouldSchedule` for the `currentInstruction`:
51
+ - Instruction status must be `PENDING_NOTIFICATION`.
52
+ - No existing `notificationId`.
53
+ - `dueTime` must be in the future.
54
+ - Patient must have Expo tokens.
55
+ - If `shouldSchedule` is true:
56
+ - Constructs a `notificationPayload` for a `RequirementInstructionDueNotification`.
57
+ - Calls `this.notificationsAdmin.createNotification()` to create the notification document.
58
+ - Updates `currentInstruction` with the new `notificationId` and ensures its status is `PENDING_NOTIFICATION`.
59
+ - Marks `instructionUpdatesMade` as `true`.
60
+ 6. **Update Firestore Document**:
61
+ - If `instructionUpdatesMade` is `true` (meaning any instruction's notification details or status changed):
62
+ - Updates the `PatientRequirementInstance` document in Firestore with the `updatedInstructions` array and sets its `updatedAt` timestamp.
63
+ - Ensures all `updatedAt` (and other Timestamp fields) within `updatedInstructions` and for the main instance are converted to `FirebaseClientTimestamp` for compatibility with shared types.
64
+ - **Usage Context**:
65
+ - Triggered by a Cloud Function on **create** of a `PatientRequirementInstance`.
66
+ - Triggered by a Cloud Function on **update** of a `PatientRequirementInstance`. The Cloud Function should provide both the new and previous data of the instance.
67
+
68
+ ### 3. `async cancelAllNotificationsForInstance(instance: PatientRequirementInstance)`
69
+
70
+ - **Purpose**: To cancel all _pending_ notifications associated with a given `PatientRequirementInstance`. This is typically used when an entire instance is hard-deleted or unequivocally cancelled in a way not covered by status changes processed by `processRequirementInstanceAndScheduleNotifications`.
71
+ - **Parameters**:
72
+ - `instance: PatientRequirementInstance`: The requirement instance whose notifications need to be cancelled.
73
+ - **Core Logic Flow**:
74
+ 1. Iterates through each instruction in `instance.instructions`.
75
+ 2. If an instruction has a `notificationId`:
76
+ - Fetches the notification using `this.notificationsAdmin.getNotification()`.
77
+ - If the notification exists and its status is `PENDING`:
78
+ - Calls `this.notificationsAdmin.updateNotificationStatus()` to set its status to `CANCELLED`.
79
+ - **Usage Context**:
80
+ - Triggered by a Cloud Function on **delete** of a `PatientRequirementInstance`.
81
+ - Can also be invoked if an instance's overall status changes to a terminal "cancelled" state that requires immediate cessation of all related pending notifications.
82
+
83
+ ### 4. `async updateMissedInstructions(patientId: string, instanceId: string)`
84
+
85
+ - **Purpose**: (Optional utility, typically for a cron job) Scans instructions within a specific `PatientRequirementInstance` that are past their `dueTime` but have not yet been actioned (i.e., status is `PENDING_NOTIFICATION` or `ACTION_DUE`). It updates their status to `MISSED`.
86
+ - **Parameters**:
87
+ - `patientId: string`: The ID of the patient.
88
+ - `instanceId: string`: The ID of the `PatientRequirementInstance` to check.
89
+ - **Core Logic Flow**:
90
+ 1. Fetches the specified `PatientRequirementInstance` document.
91
+ 2. If not found, logs a warning and exits.
92
+ 3. Iterates through each instruction in the instance.
93
+ 4. If an instruction's `dueTime` is in the past AND its status is `PENDING_NOTIFICATION` or `ACTION_DUE`:
94
+ - Updates the instruction's `status` to `MISSED`.
95
+ - Sets the instruction's `updatedAt` timestamp (converted to `FirebaseClientTimestamp`).
96
+ - Marks that `changesMade` is `true`.
97
+ 5. If `changesMade` is `true`:
98
+ - Updates the `PatientRequirementInstance` document in Firestore with the modified instructions and sets its main `updatedAt` timestamp (converted to `FirebaseClientTimestamp`).
99
+ - **Usage Context**:
100
+ - Intended to be called by a scheduled Cloud Function (e.g., a daily cron job) to perform cleanup and status updates for instructions that were not completed by their due date.
101
+
102
+ ### 5. `async updateOverallInstanceStatus(patientId: string, instanceId: string)`
103
+
104
+ - **Purpose**: Calculates and updates the `overallStatus` of a `PatientRequirementInstance` based on the collective statuses of its individual, non-cancelled instructions. This helps reflect the true completion state of the entire requirement set.
105
+ - **Parameters**:
106
+ - `patientId: string`: The ID of the patient to whom the requirement instance belongs.
107
+ - `instanceId: string`: The ID of the `PatientRequirementInstance` to update.
108
+ - **Core Logic Flow**:
109
+ 1. **Fetch Instance**: Retrieves the specified `PatientRequirementInstance`.
110
+ 2. **Check Terminal States**: If the current `instance.overallStatus` is already `CANCELLED_APPOINTMENT`, `SUPERSEDED_RESCHEDULE`, or `FAILED_TO_PROCESS`, the function logs this and exits, as these are considered final states not to be overridden by this logic.
111
+ 3. **Handle No Active Instructions**: Filters out any instructions with a status of `CANCELLED`. If no non-cancelled instructions remain:
112
+ - Sets the `overallStatus` to `ACTIVE` (if not already) and updates Firestore. This acts as a default if an instance becomes empty of actionable items.
113
+ 4. **Check for Pending/Due Instructions**: Iterates through the non-cancelled instructions. If any instruction has a status of `PENDING_NOTIFICATION` or `ACTION_DUE`:
114
+ - The `newOverallStatus` is determined to be `ACTIVE`.
115
+ 5. **All Instructions Resolved**: If no instructions are `PENDING_NOTIFICATION` or `ACTION_DUE` (meaning all non-cancelled instructions are in a "resolved" state: `ACTION_TAKEN`, `MISSED`, or `SKIPPED`):
116
+ - Counts `effectivelyCompletedCount` (non-cancelled instructions that are `ACTION_TAKEN` or `SKIPPED`).
117
+ - Calculates `completionPercentage = (effectivelyCompletedCount / totalNonCancelledInstructions) * 100`.
118
+ - If `completionPercentage === 100%`, `newOverallStatus` is `ALL_INSTRUCTIONS_MET`.
119
+ - Else if `completionPercentage >= 60%`, `newOverallStatus` is `PARTIALLY_COMPLETED`.
120
+ - Else (`completionPercentage < 60%`), `newOverallStatus` is `FAILED_TO_PROCESS`.
121
+ 6. **Update Firestore**: If the calculated `newOverallStatus` is different from the `instance.overallStatus` currently in Firestore, it updates the document with the new status and the current timestamp (converted to `FirebaseClientTimestamp`).
122
+ - **Usage Context**:
123
+ - Typically called by a Cloud Function triggered on **update** of a `PatientRequirementInstance`, ideally after `processRequirementInstanceAndScheduleNotifications` (or any other logic that might modify individual instruction statuses) has completed. This ensures the `overallStatus` accurately reflects the latest state of the instructions.
124
+ - It helps maintain data integrity and provides a clear, high-level status for the entire set of requirements.
125
+
126
+ ## Timestamp Handling
127
+
128
+ A key aspect of this service is the correct handling of Firestore Timestamps. Since the shared type definitions (e.g., for `PatientRequirementInstruction`) expect Timestamps compatible with the client-side Firebase SDK (`@firebase/firestore.Timestamp`), any Timestamps generated by the Admin SDK (e.g., `admin.firestore.Timestamp.now()`) must be converted to `new FirebaseClientTimestamp(adminTimestamp.seconds, adminTimestamp.nanoseconds)` before being written back to Firestore as part of these shared types. This ensures type consistency across the backend (admin) and frontend/shared type definitions.
@@ -0,0 +1,482 @@
1
+ import * as admin from "firebase-admin";
2
+ // Import client-side Timestamp for type compatibility with shared types
3
+ import { Timestamp as FirebaseClientTimestamp } from "@firebase/firestore";
4
+ import {
5
+ PatientRequirementInstance,
6
+ PatientInstructionStatus,
7
+ PatientRequirementOverallStatus,
8
+ PatientRequirementInstruction,
9
+ PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME,
10
+ } from "../../types/patient/patient-requirements";
11
+ import {
12
+ NotificationType,
13
+ RequirementInstructionDueNotification,
14
+ NOTIFICATIONS_COLLECTION,
15
+ NotificationStatus,
16
+ } from "../../types/notifications";
17
+ import { PatientProfile, PATIENTS_COLLECTION } from "../../types/patient";
18
+ import { UserRole } from "../../types"; // Assuming UserRole is in the main types index
19
+ import { NotificationsAdmin } from "../notifications/notifications.admin";
20
+
21
+ /**
22
+ * @class PatientRequirementsAdminService
23
+ * @description Handles administrative tasks for patient requirement instances, primarily managing associated notifications.
24
+ * This service is intended to be used by Cloud Functions triggered by changes to PatientRequirementInstance documents.
25
+ */
26
+ export class PatientRequirementsAdminService {
27
+ private db: admin.firestore.Firestore;
28
+ private notificationsAdmin: NotificationsAdmin;
29
+
30
+ constructor(firestore?: admin.firestore.Firestore) {
31
+ this.db = firestore || admin.firestore();
32
+ this.notificationsAdmin = new NotificationsAdmin(this.db);
33
+ }
34
+
35
+ /**
36
+ * Processes a newly created or updated PatientRequirementInstance to schedule notifications for its instructions.
37
+ * It will also cancel pre-existing notifications if due times have changed significantly.
38
+ *
39
+ * @param patientId - The ID of the patient.
40
+ * @param instance - The PatientRequirementInstance data (either new or updated).
41
+ * @param previousInstanceData - Optional. The previous state of the instance data if it's an update.
42
+ * Used to determine if notifications need to be cancelled/rescheduled.
43
+ * @returns {Promise<void>} A promise that resolves when processing is complete.
44
+ */
45
+ async processRequirementInstanceAndScheduleNotifications(
46
+ patientId: string,
47
+ instance: PatientRequirementInstance,
48
+ previousInstanceData?: PatientRequirementInstance
49
+ ): Promise<void> {
50
+ console.log(
51
+ `[PRA_Service] Processing requirement instance ${instance.id} for patient ${patientId}. Overall Status: ${instance.overallStatus}`
52
+ );
53
+
54
+ const patientProfileRef = this.db
55
+ .collection(PATIENTS_COLLECTION)
56
+ .doc(patientId);
57
+ let patientExpoTokens: string[] = [];
58
+
59
+ try {
60
+ const patientDoc = await patientProfileRef.get();
61
+ if (patientDoc.exists) {
62
+ const patientData = patientDoc.data() as PatientProfile;
63
+ patientExpoTokens = patientData.expoTokens || [];
64
+ }
65
+ } catch (error) {
66
+ console.error(
67
+ `[PRA_Service] Error fetching patient ${patientId} for expo tokens:`,
68
+ error
69
+ );
70
+ }
71
+
72
+ if (patientExpoTokens.length === 0) {
73
+ console.log(
74
+ `[PRA_Service] Patient ${patientId} has no expo tokens. Skipping notification creation for instance ${instance.id}.`
75
+ );
76
+ }
77
+ // Create a new array of instruction objects to avoid mutating the original
78
+ // Keep original Timestamp objects by reference
79
+ const updatedInstructions: PatientRequirementInstruction[] =
80
+ instance.instructions.map((instr) => ({ ...instr }));
81
+ let instructionUpdatesMade = false;
82
+
83
+ for (let i = 0; i < updatedInstructions.length; i++) {
84
+ let currentInstruction = updatedInstructions[i];
85
+ const previousInstruction = previousInstanceData?.instructions.find(
86
+ (pi) => pi.instructionId === currentInstruction.instructionId
87
+ );
88
+ const adminTsNow = admin.firestore.Timestamp.now();
89
+
90
+ if (
91
+ instance.overallStatus ===
92
+ PatientRequirementOverallStatus.CANCELLED_APPOINTMENT ||
93
+ instance.overallStatus ===
94
+ PatientRequirementOverallStatus.SUPERSEDED_RESCHEDULE ||
95
+ currentInstruction.status === PatientInstructionStatus.CANCELLED
96
+ ) {
97
+ if (currentInstruction.notificationId) {
98
+ console.log(
99
+ `[PRA_Service] Cancelling notification ${currentInstruction.notificationId} for instruction ${currentInstruction.instructionId} of instance ${instance.id}.`
100
+ );
101
+ await this.notificationsAdmin.updateNotificationStatus(
102
+ currentInstruction.notificationId,
103
+ NotificationStatus.CANCELLED
104
+ );
105
+ currentInstruction = {
106
+ ...currentInstruction,
107
+ notificationId: undefined,
108
+ status: PatientInstructionStatus.CANCELLED,
109
+ updatedAt: new FirebaseClientTimestamp(
110
+ adminTsNow.seconds,
111
+ adminTsNow.nanoseconds
112
+ ),
113
+ };
114
+ updatedInstructions[i] = currentInstruction;
115
+ instructionUpdatesMade = true;
116
+ }
117
+ continue;
118
+ }
119
+
120
+ const dueTimeChanged =
121
+ previousInstruction &&
122
+ currentInstruction.dueTime && // Ensure dueTime exists
123
+ previousInstruction.dueTime.toMillis() !==
124
+ currentInstruction.dueTime.toMillis();
125
+
126
+ // Simplified: if previous was CANCELLED, and we are in this part of the code,
127
+ // it means currentInstruction.status is NOT CANCELLED (i.e., it's active).
128
+ const wasPreviouslyCancelledAndNowActive =
129
+ previousInstruction &&
130
+ previousInstruction.status === PatientInstructionStatus.CANCELLED;
131
+
132
+ if (
133
+ previousInstruction &&
134
+ (dueTimeChanged || wasPreviouslyCancelledAndNowActive) && // Use the simplified variable
135
+ currentInstruction.notificationId
136
+ ) {
137
+ console.log(
138
+ `[PRA_Service] Due time changed or instruction reactivated for ${currentInstruction.instructionId}. Cancelling old notification ${currentInstruction.notificationId}.`
139
+ );
140
+ await this.notificationsAdmin.updateNotificationStatus(
141
+ currentInstruction.notificationId,
142
+ NotificationStatus.CANCELLED
143
+ );
144
+ currentInstruction = {
145
+ ...currentInstruction,
146
+ notificationId: undefined,
147
+ updatedAt: new FirebaseClientTimestamp(
148
+ adminTsNow.seconds,
149
+ adminTsNow.nanoseconds
150
+ ),
151
+ };
152
+ updatedInstructions[i] = currentInstruction;
153
+ instructionUpdatesMade = true;
154
+ }
155
+
156
+ const shouldSchedule =
157
+ currentInstruction.dueTime && // Ensure dueTime exists
158
+ currentInstruction.status ===
159
+ PatientInstructionStatus.PENDING_NOTIFICATION &&
160
+ !currentInstruction.notificationId &&
161
+ currentInstruction.dueTime.toMillis() > adminTsNow.toMillis() &&
162
+ patientExpoTokens.length > 0;
163
+
164
+ if (shouldSchedule) {
165
+ console.log(
166
+ `[PRA_Service] Scheduling notification for instruction ${
167
+ currentInstruction.instructionId
168
+ } of instance ${
169
+ instance.id
170
+ } at ${currentInstruction.dueTime.toDate()}.`
171
+ );
172
+
173
+ const notificationPayload: Omit<
174
+ RequirementInstructionDueNotification,
175
+ "id" | "createdAt" | "updatedAt" | "status" | "isRead"
176
+ > = {
177
+ userId: patientId,
178
+ userRole: UserRole.PATIENT,
179
+ notificationType: NotificationType.REQUIREMENT_INSTRUCTION_DUE,
180
+ notificationTime: currentInstruction.dueTime, // This is a Firestore Timestamp
181
+ notificationTokens: patientExpoTokens,
182
+ title: `Reminder: ${instance.requirementName}`,
183
+ body: currentInstruction.instructionText,
184
+ appointmentId: instance.appointmentId,
185
+ patientRequirementInstanceId: instance.id,
186
+ instructionId: currentInstruction.instructionId,
187
+ originalRequirementId: instance.originalRequirementId,
188
+ };
189
+
190
+ try {
191
+ const createdNotificationId =
192
+ await this.notificationsAdmin.createNotification(
193
+ notificationPayload as any
194
+ );
195
+ currentInstruction = {
196
+ ...currentInstruction,
197
+ notificationId: createdNotificationId,
198
+ status: PatientInstructionStatus.PENDING_NOTIFICATION,
199
+ updatedAt: new FirebaseClientTimestamp(
200
+ adminTsNow.seconds,
201
+ adminTsNow.nanoseconds
202
+ ),
203
+ };
204
+ updatedInstructions[i] = currentInstruction;
205
+ instructionUpdatesMade = true;
206
+ } catch (error) {
207
+ console.error(
208
+ `[PRA_Service] Failed to create notification for instruction ${currentInstruction.instructionId}:`,
209
+ error
210
+ );
211
+ }
212
+ }
213
+ }
214
+
215
+ if (instructionUpdatesMade) {
216
+ console.log(
217
+ `[PRA_Service] Updating instructions array for instance ${instance.id} on patient ${patientId}.`
218
+ );
219
+ const instanceDocRef = this.db
220
+ .collection(PATIENTS_COLLECTION)
221
+ .doc(patientId)
222
+ .collection(PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME)
223
+ .doc(instance.id);
224
+
225
+ const finalAdminTsNow = admin.firestore.Timestamp.now();
226
+ await instanceDocRef.update({
227
+ instructions: updatedInstructions, // Array of instructions with actual Timestamps
228
+ updatedAt: new FirebaseClientTimestamp(
229
+ finalAdminTsNow.seconds,
230
+ finalAdminTsNow.nanoseconds
231
+ ),
232
+ });
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Cancels all PENDING notifications associated with a specific PatientRequirementInstance.
238
+ * Typically called when the instance itself is deleted or its overall status becomes CANCELLED.
239
+ *
240
+ * @param instance - The PatientRequirementInstance.
241
+ * @returns {Promise<void>}
242
+ */
243
+ async cancelAllNotificationsForInstance(
244
+ instance: PatientRequirementInstance
245
+ ): Promise<void> {
246
+ console.log(
247
+ `[PRA_Service] Attempting to cancel all pending notifications for instance ${instance.id}.`
248
+ );
249
+ let cancelledCount = 0;
250
+ for (const instruction of instance.instructions) {
251
+ if (instruction.notificationId) {
252
+ try {
253
+ const notification = await this.notificationsAdmin.getNotification(
254
+ instruction.notificationId
255
+ );
256
+ if (
257
+ notification &&
258
+ notification.status === NotificationStatus.PENDING
259
+ ) {
260
+ await this.notificationsAdmin.updateNotificationStatus(
261
+ instruction.notificationId,
262
+ NotificationStatus.CANCELLED
263
+ );
264
+ console.log(
265
+ `[PRA_Service] Cancelled notification ${instruction.notificationId} for instruction ${instruction.instructionId}.`
266
+ );
267
+ cancelledCount++;
268
+ } else if (notification) {
269
+ console.log(
270
+ `[PRA_Service] Notification ${instruction.notificationId} for instruction ${instruction.instructionId} was not pending (status: ${notification.status}). Not cancelling.`
271
+ );
272
+ }
273
+ } catch (error) {
274
+ console.error(
275
+ `[PRA_Service] Error cancelling notification ${instruction.notificationId}:`,
276
+ error
277
+ );
278
+ }
279
+ }
280
+ }
281
+ if (cancelledCount > 0) {
282
+ console.log(
283
+ `[PRA_Service] Cancelled ${cancelledCount} notifications for instance ${instance.id}.`
284
+ );
285
+ }
286
+ }
287
+
288
+ /**
289
+ * (Optional - For a cron job)
290
+ * Scans for instructions that are past their due time but not yet actioned, and updates their status to MISSED.
291
+ * This would typically be called by a scheduled Cloud Function.
292
+ *
293
+ * @param patientId - The ID of the patient.
294
+ * @param instanceId - The ID of the PatientRequirementInstance.
295
+ * @returns {Promise<void>}
296
+ */
297
+ async updateMissedInstructions(
298
+ patientId: string,
299
+ instanceId: string
300
+ ): Promise<void> {
301
+ const instanceRef = this.db
302
+ .collection(PATIENTS_COLLECTION)
303
+ .doc(patientId)
304
+ .collection(PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME)
305
+ .doc(instanceId);
306
+
307
+ const instanceSnap = await instanceRef.get();
308
+ if (!instanceSnap.exists) {
309
+ console.warn(
310
+ `[PRA_Service] Instance ${instanceId} not found during missed check for patient ${patientId}.`
311
+ );
312
+ return;
313
+ }
314
+
315
+ const instance = instanceSnap.data() as PatientRequirementInstance;
316
+ const adminNowForMissed = admin.firestore.Timestamp.now();
317
+
318
+ // Create a new array of instruction objects to avoid mutating the original
319
+ const updatedInstructions: PatientRequirementInstruction[] =
320
+ instance.instructions.map((instr) => ({ ...instr }));
321
+ let changesMade = false;
322
+
323
+ for (let i = 0; i < updatedInstructions.length; i++) {
324
+ let currentInstruction = updatedInstructions[i];
325
+ if (
326
+ currentInstruction.dueTime && // Ensure dueTime exists
327
+ (currentInstruction.status ===
328
+ PatientInstructionStatus.PENDING_NOTIFICATION ||
329
+ currentInstruction.status === PatientInstructionStatus.ACTION_DUE) &&
330
+ currentInstruction.dueTime.toMillis() < adminNowForMissed.toMillis()
331
+ ) {
332
+ currentInstruction = {
333
+ ...currentInstruction,
334
+ status: PatientInstructionStatus.MISSED,
335
+ updatedAt: new FirebaseClientTimestamp(
336
+ adminNowForMissed.seconds,
337
+ adminNowForMissed.nanoseconds
338
+ ),
339
+ };
340
+ updatedInstructions[i] = currentInstruction;
341
+ changesMade = true;
342
+ console.log(
343
+ `[PRA_Service] Marked instruction ${currentInstruction.instructionId} in instance ${instanceId} as MISSED.`
344
+ );
345
+ }
346
+ }
347
+
348
+ if (changesMade) {
349
+ const finalAdminNowForMissedUpdate = admin.firestore.Timestamp.now();
350
+ await instanceRef.update({
351
+ instructions: updatedInstructions, // Array of instructions with actual Timestamps
352
+ updatedAt: new FirebaseClientTimestamp(
353
+ finalAdminNowForMissedUpdate.seconds,
354
+ finalAdminNowForMissedUpdate.nanoseconds
355
+ ),
356
+ });
357
+ console.log(
358
+ `[PRA_Service] Updated missed instructions for instance ${instanceId}.`
359
+ );
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Calculates and updates the overallStatus of a PatientRequirementInstance
365
+ * based on the statuses of its individual instructions.
366
+ *
367
+ * @param patientId - The ID of the patient.
368
+ * @param instanceId - The ID of the PatientRequirementInstance to update.
369
+ * @returns {Promise<void>} A promise that resolves when processing is complete.
370
+ */
371
+ async updateOverallInstanceStatus(
372
+ patientId: string,
373
+ instanceId: string
374
+ ): Promise<void> {
375
+ const instanceRef = this.db
376
+ .collection(PATIENTS_COLLECTION)
377
+ .doc(patientId)
378
+ .collection(PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME)
379
+ .doc(instanceId);
380
+
381
+ const instanceSnap = await instanceRef.get();
382
+ if (!instanceSnap.exists) {
383
+ console.warn(
384
+ `[PRA_Service] Instance ${instanceId} not found while trying to update overall status for patient ${patientId}.`
385
+ );
386
+ return;
387
+ }
388
+
389
+ const instance = instanceSnap.data() as PatientRequirementInstance;
390
+
391
+ // Do not override terminal statuses set by other processes
392
+ if (
393
+ instance.overallStatus ===
394
+ PatientRequirementOverallStatus.CANCELLED_APPOINTMENT ||
395
+ instance.overallStatus ===
396
+ PatientRequirementOverallStatus.SUPERSEDED_RESCHEDULE ||
397
+ instance.overallStatus ===
398
+ PatientRequirementOverallStatus.FAILED_TO_PROCESS // Assuming FAILED_TO_PROCESS is also a terminal state set by other means if it's a hard failure.
399
+ ) {
400
+ console.log(
401
+ `[PRA_Service] Instance ${instanceId} has overallStatus ${instance.overallStatus}, skipping overall status update based on instruction completion logic.`
402
+ );
403
+ return;
404
+ }
405
+
406
+ const nonCancelledInstructions = instance.instructions.filter(
407
+ (instr) => instr.status !== PatientInstructionStatus.CANCELLED
408
+ );
409
+
410
+ if (nonCancelledInstructions.length === 0) {
411
+ // If all instructions are cancelled or there are no instructions.
412
+ // If it was previously something like ALL_INSTRUCTIONS_MET, it should revert to ACTIVE or a default.
413
+ if (instance.overallStatus !== PatientRequirementOverallStatus.ACTIVE) {
414
+ console.log(
415
+ `[PRA_Service] Instance ${instanceId} has no active (non-cancelled) instructions. Setting to ACTIVE.`
416
+ );
417
+ await instanceRef.update({
418
+ overallStatus: PatientRequirementOverallStatus.ACTIVE,
419
+ updatedAt: new FirebaseClientTimestamp(
420
+ admin.firestore.Timestamp.now().seconds,
421
+ admin.firestore.Timestamp.now().nanoseconds
422
+ ),
423
+ });
424
+ }
425
+ return;
426
+ }
427
+
428
+ // Check if any instruction is still pending action by the patient
429
+ const hasPendingOrDueInstructions = nonCancelledInstructions.some(
430
+ (instr) =>
431
+ instr.status === PatientInstructionStatus.PENDING_NOTIFICATION ||
432
+ instr.status === PatientInstructionStatus.ACTION_DUE
433
+ );
434
+
435
+ let newOverallStatus: PatientRequirementOverallStatus;
436
+
437
+ if (hasPendingOrDueInstructions) {
438
+ newOverallStatus = PatientRequirementOverallStatus.ACTIVE;
439
+ } else {
440
+ // All non-cancelled instructions are in a "resolved" state (ACTION_TAKEN, MISSED, SKIPPED)
441
+ const effectivelyCompletedCount = nonCancelledInstructions.filter(
442
+ (instr) =>
443
+ instr.status === PatientInstructionStatus.ACTION_TAKEN ||
444
+ instr.status === PatientInstructionStatus.SKIPPED
445
+ ).length;
446
+
447
+ const totalNonCancelled = nonCancelledInstructions.length;
448
+ const completionPercentage =
449
+ (effectivelyCompletedCount / totalNonCancelled) * 100;
450
+
451
+ if (completionPercentage === 100) {
452
+ newOverallStatus = PatientRequirementOverallStatus.ALL_INSTRUCTIONS_MET;
453
+ } else if (completionPercentage >= 60) {
454
+ // Changed from >60 to >=60 as per common understanding of "more than 60%" often including 60%
455
+ newOverallStatus = PatientRequirementOverallStatus.PARTIALLY_COMPLETED;
456
+ } else {
457
+ // Less than 60% effectively completed (could include some MISSED ones not blocking this calculation directly)
458
+ // Or if all are MISSED, this would also fall here if FAILED_TO_PROCESS isn't set for other reasons.
459
+ // Your logic: "if less then 60% of instructions are action taken or skipped, then we move status to failed"
460
+ newOverallStatus = PatientRequirementOverallStatus.FAILED_TO_PROCESS;
461
+ }
462
+ }
463
+
464
+ if (newOverallStatus !== instance.overallStatus) {
465
+ console.log(
466
+ `[PRA_Service] Updating overallStatus for instance ${instanceId} from ${instance.overallStatus} to ${newOverallStatus}.`
467
+ );
468
+ const adminTsNow = admin.firestore.Timestamp.now();
469
+ await instanceRef.update({
470
+ overallStatus: newOverallStatus,
471
+ updatedAt: new FirebaseClientTimestamp(
472
+ adminTsNow.seconds,
473
+ adminTsNow.nanoseconds
474
+ ),
475
+ });
476
+ } else {
477
+ console.log(
478
+ `[PRA_Service] Calculated overallStatus ${newOverallStatus} for instance ${instanceId} is same as current. No update needed.`
479
+ );
480
+ }
481
+ }
482
+ }