@blackcode_sa/metaestetics-api 1.6.3 → 1.6.5

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 (40) hide show
  1. package/dist/admin/index.d.mts +439 -25
  2. package/dist/admin/index.d.ts +439 -25
  3. package/dist/admin/index.js +36107 -2493
  4. package/dist/admin/index.mjs +36093 -2461
  5. package/dist/backoffice/index.d.mts +254 -1
  6. package/dist/backoffice/index.d.ts +254 -1
  7. package/dist/backoffice/index.js +86 -12
  8. package/dist/backoffice/index.mjs +86 -13
  9. package/dist/index.d.mts +1434 -621
  10. package/dist/index.d.ts +1434 -621
  11. package/dist/index.js +1381 -970
  12. package/dist/index.mjs +1433 -1016
  13. package/package.json +1 -1
  14. package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +321 -0
  15. package/src/admin/booking/booking.admin.ts +376 -3
  16. package/src/admin/index.ts +15 -1
  17. package/src/admin/notifications/notifications.admin.ts +1 -1
  18. package/src/admin/requirements/README.md +128 -0
  19. package/src/admin/requirements/patient-requirements.admin.service.ts +482 -0
  20. package/src/backoffice/types/product.types.ts +2 -0
  21. package/src/index.ts +16 -1
  22. package/src/services/appointment/appointment.service.ts +386 -250
  23. package/src/services/clinic/clinic-admin.service.ts +3 -0
  24. package/src/services/clinic/clinic-group.service.ts +8 -0
  25. package/src/services/documentation-templates/documentation-template.service.ts +24 -16
  26. package/src/services/documentation-templates/filled-document.service.ts +253 -136
  27. package/src/services/patient/patientRequirements.service.ts +285 -0
  28. package/src/services/procedure/procedure.service.ts +1 -0
  29. package/src/types/appointment/index.ts +136 -11
  30. package/src/types/documentation-templates/index.ts +34 -2
  31. package/src/types/notifications/README.md +77 -0
  32. package/src/types/notifications/index.ts +154 -27
  33. package/src/types/patient/patient-requirements.ts +81 -0
  34. package/src/types/procedure/index.ts +7 -0
  35. package/src/validations/appointment.schema.ts +298 -62
  36. package/src/validations/documentation-templates/template.schema.ts +55 -0
  37. package/src/validations/documentation-templates.schema.ts +9 -14
  38. package/src/validations/notification.schema.ts +3 -3
  39. package/src/validations/patient/patient-requirements.schema.ts +75 -0
  40. package/src/validations/procedure.schema.ts +3 -0
@@ -1,4 +1,5 @@
1
1
  import * as admin from "firebase-admin";
2
+ import { Timestamp as FirebaseClientTimestamp } from "@firebase/firestore";
2
3
  import {
3
4
  BookingAvailabilityCalculator,
4
5
  BookingAvailabilityRequest,
@@ -6,9 +7,57 @@ import {
6
7
  AvailableSlot,
7
8
  } from "./";
8
9
  import { CalendarEventStatus, CalendarEventType } from "../../types/calendar";
9
- import { Clinic } from "../../types/clinic";
10
- import { Practitioner } from "../../types/practitioner";
11
- import { Procedure } from "../../types/procedure";
10
+ import {
11
+ Clinic,
12
+ CLINICS_COLLECTION,
13
+ ClinicGroup,
14
+ CLINIC_GROUPS_COLLECTION,
15
+ } from "../../types/clinic";
16
+ import {
17
+ Practitioner,
18
+ PRACTITIONERS_COLLECTION,
19
+ } from "../../types/practitioner";
20
+ import {
21
+ Procedure,
22
+ PROCEDURES_COLLECTION,
23
+ ProcedureSummaryInfo,
24
+ } from "../../types/procedure";
25
+ import {
26
+ PatientProfile,
27
+ PATIENTS_COLLECTION,
28
+ PatientSensitiveInfo,
29
+ PATIENT_SENSITIVE_INFO_COLLECTION,
30
+ Gender,
31
+ } from "../../types/patient";
32
+ import {
33
+ Appointment,
34
+ AppointmentStatus,
35
+ PaymentStatus,
36
+ APPOINTMENTS_COLLECTION,
37
+ ProcedureExtendedInfo,
38
+ } from "../../types/appointment";
39
+ import { Currency } from "../../backoffice/types/static/pricing.types";
40
+ import { DocumentTemplate } from "../../types/documentation-templates";
41
+ import {
42
+ ClinicInfo,
43
+ PractitionerProfileInfo,
44
+ PatientProfileInfo,
45
+ } from "../../types/profile";
46
+ import { Category } from "../../backoffice/types/category.types";
47
+ import { Subcategory } from "../../backoffice/types/subcategory.types";
48
+ import { Technology } from "../../backoffice/types/technology.types";
49
+ import { Product } from "../../backoffice/types/product.types";
50
+
51
+ /**
52
+ * Interface for the data required by orchestrateAppointmentCreation
53
+ */
54
+ export interface OrchestrateAppointmentCreationData {
55
+ patientId: string;
56
+ procedureId: string;
57
+ appointmentStartTime: admin.firestore.Timestamp;
58
+ appointmentEndTime: admin.firestore.Timestamp;
59
+ patientNotes?: string | null;
60
+ }
12
61
 
13
62
  /**
14
63
  * Admin service for handling booking-related operations.
@@ -231,4 +280,328 @@ export class BookingAdmin {
231
280
  return [];
232
281
  }
233
282
  }
283
+
284
+ /**
285
+ * Orchestrates the creation of a new appointment, including data aggregation.
286
+ * This method is intended to be called from a trusted backend environment (e.g., an Express route handler in a Cloud Function).
287
+ *
288
+ * @param data - Data required to create the appointment.
289
+ * @param authenticatedUserId - The ID of the user making the request (for auditing, and usually is the patientId).
290
+ * @returns Promise resolving to an object indicating success, and appointmentId or an error message.
291
+ */
292
+ async orchestrateAppointmentCreation(
293
+ data: OrchestrateAppointmentCreationData,
294
+ authenticatedUserId: string
295
+ ): Promise<{
296
+ success: boolean;
297
+ appointmentId?: string;
298
+ appointmentData?: Appointment;
299
+ error?: string;
300
+ }> {
301
+ console.log(
302
+ `[BookingAdmin] Orchestrating appointment creation for patient ${data.patientId} by user ${authenticatedUserId}`
303
+ );
304
+
305
+ try {
306
+ // --- 1. Input Validation ---
307
+ if (
308
+ !data.patientId ||
309
+ !data.procedureId ||
310
+ !data.appointmentStartTime ||
311
+ !data.appointmentEndTime
312
+ ) {
313
+ return {
314
+ success: false,
315
+ error:
316
+ "Missing required fields: patientId, procedureId, appointmentStartTime, or appointmentEndTime.",
317
+ };
318
+ }
319
+ if (
320
+ data.appointmentEndTime.toMillis() <=
321
+ data.appointmentStartTime.toMillis()
322
+ ) {
323
+ return {
324
+ success: false,
325
+ error: "Appointment end time must be after start time.",
326
+ };
327
+ }
328
+ if (authenticatedUserId !== data.patientId) {
329
+ console.warn(
330
+ `[BookingAdmin] Authenticated user ${authenticatedUserId} is booking for a different patient ${data.patientId}. Review authorization if this is not intended.`
331
+ );
332
+ }
333
+
334
+ // --- 2. Fetch Core Procedure Data ---
335
+ const procedureRef = this.db
336
+ .collection(PROCEDURES_COLLECTION)
337
+ .doc(data.procedureId);
338
+ const procedureDoc = await procedureRef.get();
339
+ if (!procedureDoc.exists) {
340
+ return {
341
+ success: false,
342
+ error: `Procedure ${data.procedureId} not found.`,
343
+ };
344
+ }
345
+ const procedure = procedureDoc.data() as Procedure;
346
+
347
+ // --- 3. Fetch Clinic and then other Primary Documents ---
348
+ // Fetch clinic first to get its clinicGroupId
349
+ const clinicRef = this.db
350
+ .collection(CLINICS_COLLECTION)
351
+ .doc(procedure.clinicBranchId);
352
+ const clinicSnap = await clinicRef.get(); // Await here directly
353
+ if (!clinicSnap.exists) {
354
+ return {
355
+ success: false,
356
+ error: `Clinic ${procedure.clinicBranchId} not found.`,
357
+ };
358
+ }
359
+ const clinicData = clinicSnap.data() as Clinic; // Now clinicData is available
360
+
361
+ // Define other refs using clinicData for clinicGroupRef
362
+ const practitionerRef = this.db
363
+ .collection(PRACTITIONERS_COLLECTION)
364
+ .doc(procedure.practitionerId);
365
+ const patientProfileRef = this.db
366
+ .collection(PATIENTS_COLLECTION)
367
+ .doc(data.patientId);
368
+ const patientSensitiveRef = this.db
369
+ .collection(PATIENTS_COLLECTION)
370
+ .doc(data.patientId)
371
+ .collection(PATIENT_SENSITIVE_INFO_COLLECTION)
372
+ .doc(data.patientId);
373
+ const clinicGroupRef = this.db
374
+ .collection(CLINIC_GROUPS_COLLECTION)
375
+ .doc(clinicData.clinicGroupId); // Use clinicData here
376
+
377
+ const [
378
+ practitionerSnap,
379
+ patientProfileSnap,
380
+ patientSensitiveSnap,
381
+ clinicGroupSnap,
382
+ ] = await Promise.all([
383
+ // clinicRef.get() is already done via clinicSnap
384
+ practitionerRef.get(),
385
+ patientProfileRef.get(),
386
+ patientSensitiveRef.get(),
387
+ clinicGroupRef.get(), // Fetch the defined clinicGroupRef
388
+ ]);
389
+
390
+ if (!practitionerSnap.exists)
391
+ return {
392
+ success: false,
393
+ error: `Practitioner ${procedure.practitionerId} not found.`,
394
+ };
395
+ if (!patientProfileSnap.exists)
396
+ return {
397
+ success: false,
398
+ error: `PatientProfile ${data.patientId} not found.`,
399
+ };
400
+ if (!clinicGroupSnap.exists)
401
+ return {
402
+ success: false,
403
+ error: `ClinicGroup for clinic ${procedure.clinicBranchId} not found.`,
404
+ };
405
+
406
+ const practitionerData = practitionerSnap.data() as Practitioner;
407
+ const patientProfileData = patientProfileSnap.data() as PatientProfile;
408
+ const patientSensitiveData = patientSensitiveSnap.exists
409
+ ? (patientSensitiveSnap.data() as PatientSensitiveInfo)
410
+ : undefined;
411
+ const clinicGroupData = clinicGroupSnap.data() as ClinicGroup;
412
+
413
+ // --- 4. Determine initialStatus (based on clinic settings) ---
414
+ const autoConfirm = clinicGroupData.autoConfirmAppointments || false;
415
+ const initialStatus = autoConfirm
416
+ ? AppointmentStatus.CONFIRMED
417
+ : AppointmentStatus.PENDING;
418
+
419
+ // --- 5. Aggregate Information (Snapshots) ---
420
+ const clinicInfo: ClinicInfo = {
421
+ id: clinicSnap.id,
422
+ name: clinicData.name,
423
+ featuredPhoto: clinicData.coverPhoto || clinicData.logo || "",
424
+ description: clinicData.description,
425
+ location: clinicData.location,
426
+ contactInfo: clinicData.contactInfo,
427
+ };
428
+ const practitionerInfo: PractitionerProfileInfo = {
429
+ id: practitionerSnap.id,
430
+ practitionerPhoto: practitionerData.basicInfo.profileImageUrl || null,
431
+ name: `${practitionerData.basicInfo.firstName} ${practitionerData.basicInfo.lastName}`,
432
+ email: practitionerData.basicInfo.email,
433
+ phone: practitionerData.basicInfo.phoneNumber || null,
434
+ certification: practitionerData.certification,
435
+ };
436
+ const patientInfo: PatientProfileInfo = {
437
+ id: patientProfileSnap.id,
438
+ fullName:
439
+ `${patientSensitiveData?.firstName || ""} ${
440
+ patientSensitiveData?.lastName || ""
441
+ }`.trim() || patientProfileData.displayName,
442
+ email: patientSensitiveData?.email || "",
443
+ phone:
444
+ patientSensitiveData?.phoneNumber ||
445
+ patientProfileData.phoneNumber ||
446
+ null,
447
+ dateOfBirth:
448
+ patientSensitiveData?.dateOfBirth ||
449
+ patientProfileData.dateOfBirth ||
450
+ admin.firestore.Timestamp.now(),
451
+ gender: patientSensitiveData?.gender || Gender.OTHER,
452
+ };
453
+ const procedureCategory = procedure.category as Category;
454
+ const procedureSubCategory = procedure.subcategory as Subcategory;
455
+ const procedureTechnology = procedure.technology as Technology;
456
+ const procedureProduct = procedure.product as Product;
457
+
458
+ const procedureInfo: ProcedureSummaryInfo = {
459
+ id: procedure.id,
460
+ name: procedure.name,
461
+ description: procedure.description,
462
+ family: procedure.family,
463
+ categoryName: procedureCategory?.name || "",
464
+ subcategoryName: procedureSubCategory?.name || "",
465
+ technologyName: procedureTechnology?.name || "",
466
+ price: procedure.price,
467
+ pricingMeasure: procedure.pricingMeasure,
468
+ currency: procedure.currency,
469
+ duration: procedure.duration,
470
+ clinicId: procedure.clinicBranchId,
471
+ clinicName: clinicData.name,
472
+ practitionerId: procedure.practitionerId,
473
+ practitionerName: `${practitionerData.basicInfo.firstName} ${practitionerData.basicInfo.lastName}`,
474
+ photo: procedure.photos?.[0] || "",
475
+ brandName: procedureProduct?.brandName || "",
476
+ productName: procedureProduct?.name || "",
477
+ };
478
+ const procedureExtendedInfo: ProcedureExtendedInfo = {
479
+ id: procedure.id,
480
+ name: procedure.name,
481
+ description: procedure.description,
482
+ cost: procedure.price,
483
+ duration: procedure.duration,
484
+ procedureFamily: procedure.family,
485
+ procedureCategoryId: procedureCategory?.id || "",
486
+ procedureCategoryName: procedureCategory?.name || "",
487
+ procedureSubCategoryId: procedureSubCategory?.id || "",
488
+ procedureSubCategoryName: procedureSubCategory?.name || "",
489
+ procedureTechnologyId: procedureTechnology?.id || "",
490
+ procedureTechnologyName: procedureTechnology?.name || "",
491
+ procedureProductBrandId: procedureProduct.brandId || "",
492
+ procedureProductBrandName: procedureProduct.brandName || "",
493
+ procedureProductId: procedureProduct.id || "",
494
+ procedureProductName: procedureProduct.name || "",
495
+ };
496
+
497
+ // --- 6. Determine pendingUserFormsIds and linkedFormIds ---
498
+ let pendingUserFormsIds: string[] = [];
499
+ let linkedFormIds: string[] = [];
500
+ if (
501
+ procedure.documentationTemplates &&
502
+ Array.isArray(procedure.documentationTemplates)
503
+ ) {
504
+ pendingUserFormsIds = procedure.documentationTemplates
505
+ .filter(
506
+ (template: DocumentTemplate) =>
507
+ template.isUserForm && template.isRequired
508
+ )
509
+ .map((template: DocumentTemplate) => template.id);
510
+ linkedFormIds = procedure.documentationTemplates.map(
511
+ (template: DocumentTemplate) => template.id
512
+ );
513
+ }
514
+
515
+ // --- 7. Construct New Appointment Object ---
516
+ const newAppointmentId = this.db
517
+ .collection(APPOINTMENTS_COLLECTION)
518
+ .doc().id;
519
+ const serverTimestampValue = admin.firestore.FieldValue.serverTimestamp();
520
+ const adminTsNow = admin.firestore.Timestamp.now();
521
+
522
+ const newAppointmentData: Appointment = {
523
+ id: newAppointmentId,
524
+ calendarEventId: "",
525
+ clinicBranchId: procedure.clinicBranchId,
526
+ clinicInfo,
527
+ practitionerId: procedure.practitionerId,
528
+ practitionerInfo,
529
+ patientId: data.patientId,
530
+ patientInfo,
531
+ procedureId: data.procedureId,
532
+ procedureInfo,
533
+ procedureExtendedInfo,
534
+ status: initialStatus,
535
+ bookingTime: serverTimestampValue as any,
536
+ confirmationTime:
537
+ initialStatus === AppointmentStatus.CONFIRMED
538
+ ? (serverTimestampValue as any)
539
+ : null,
540
+ appointmentStartTime: new FirebaseClientTimestamp(
541
+ data.appointmentStartTime.seconds,
542
+ data.appointmentStartTime.nanoseconds
543
+ ),
544
+ appointmentEndTime: new FirebaseClientTimestamp(
545
+ data.appointmentEndTime.seconds,
546
+ data.appointmentEndTime.nanoseconds
547
+ ),
548
+ cost: procedure.price,
549
+ currency: procedure.currency,
550
+ paymentStatus:
551
+ procedure.price > 0
552
+ ? PaymentStatus.UNPAID
553
+ : PaymentStatus.NOT_APPLICABLE,
554
+ patientNotes: data.patientNotes || null,
555
+ blockingConditions: procedure.blockingConditions || [],
556
+ contraindications: procedure.contraindications || [],
557
+ preProcedureRequirements: procedure.preRequirements || [],
558
+ postProcedureRequirements: procedure.postRequirements || [],
559
+ pendingUserFormsIds: pendingUserFormsIds,
560
+ completedPreRequirements: [],
561
+ completedPostRequirements: [],
562
+ linkedFormIds: linkedFormIds,
563
+ linkedForms: [],
564
+ media: [],
565
+ reviewInfo: null,
566
+ finalizedDetails: undefined,
567
+ internalNotes: null,
568
+ cancellationReason: null,
569
+ cancellationTime: null,
570
+ canceledBy: undefined,
571
+ rescheduleTime: null,
572
+ procedureActualStartTime: null,
573
+ actualDurationMinutes: undefined,
574
+ isRecurring: false,
575
+ recurringAppointmentId: null,
576
+ isArchived: false,
577
+ createdAt: serverTimestampValue as any,
578
+ updatedAt: serverTimestampValue as any,
579
+ };
580
+
581
+ // --- 8. Save New Appointment ---
582
+ await this.db
583
+ .collection(APPOINTMENTS_COLLECTION)
584
+ .doc(newAppointmentId)
585
+ .set(newAppointmentData);
586
+
587
+ console.log(
588
+ `[BookingAdmin] Appointment ${newAppointmentId} created successfully with status ${initialStatus}.`
589
+ );
590
+ return {
591
+ success: true,
592
+ appointmentId: newAppointmentId,
593
+ appointmentData: newAppointmentData,
594
+ };
595
+ } catch (error) {
596
+ console.error(
597
+ "[BookingAdmin] Critical error in orchestrateAppointmentCreation:",
598
+ error
599
+ );
600
+ const errorMessage =
601
+ error instanceof Error
602
+ ? error.message
603
+ : "Unknown server error during appointment creation.";
604
+ return { success: false, error: errorMessage };
605
+ }
606
+ }
234
607
  }
@@ -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.