@blackcode_sa/metaestetics-api 1.13.5 → 1.13.6

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 (291) hide show
  1. package/dist/admin/index.d.mts +20 -1
  2. package/dist/admin/index.d.ts +20 -1
  3. package/dist/admin/index.js +217 -1
  4. package/dist/admin/index.mjs +217 -1
  5. package/package.json +121 -121
  6. package/src/__mocks__/firstore.ts +10 -10
  7. package/src/admin/aggregation/README.md +79 -79
  8. package/src/admin/aggregation/appointment/README.md +128 -128
  9. package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +1984 -1984
  10. package/src/admin/aggregation/appointment/index.ts +1 -1
  11. package/src/admin/aggregation/clinic/README.md +52 -52
  12. package/src/admin/aggregation/clinic/clinic.aggregation.service.ts +966 -703
  13. package/src/admin/aggregation/clinic/index.ts +1 -1
  14. package/src/admin/aggregation/forms/README.md +13 -13
  15. package/src/admin/aggregation/forms/filled-forms.aggregation.service.ts +322 -322
  16. package/src/admin/aggregation/forms/index.ts +1 -1
  17. package/src/admin/aggregation/index.ts +8 -8
  18. package/src/admin/aggregation/patient/README.md +27 -27
  19. package/src/admin/aggregation/patient/index.ts +1 -1
  20. package/src/admin/aggregation/patient/patient.aggregation.service.ts +141 -141
  21. package/src/admin/aggregation/practitioner/README.md +42 -42
  22. package/src/admin/aggregation/practitioner/index.ts +1 -1
  23. package/src/admin/aggregation/practitioner/practitioner.aggregation.service.ts +433 -433
  24. package/src/admin/aggregation/practitioner-invite/index.ts +1 -1
  25. package/src/admin/aggregation/practitioner-invite/practitioner-invite.aggregation.service.ts +961 -961
  26. package/src/admin/aggregation/procedure/README.md +43 -43
  27. package/src/admin/aggregation/procedure/index.ts +1 -1
  28. package/src/admin/aggregation/procedure/procedure.aggregation.service.ts +702 -702
  29. package/src/admin/aggregation/reviews/index.ts +1 -1
  30. package/src/admin/aggregation/reviews/reviews.aggregation.service.ts +689 -689
  31. package/src/admin/analytics/analytics.admin.service.ts +278 -278
  32. package/src/admin/analytics/index.ts +2 -2
  33. package/src/admin/booking/README.md +125 -125
  34. package/src/admin/booking/booking.admin.ts +1037 -1037
  35. package/src/admin/booking/booking.calculator.ts +712 -712
  36. package/src/admin/booking/booking.types.ts +59 -59
  37. package/src/admin/booking/index.ts +3 -3
  38. package/src/admin/booking/timezones-problem.md +185 -185
  39. package/src/admin/calendar/README.md +7 -7
  40. package/src/admin/calendar/calendar.admin.service.ts +345 -345
  41. package/src/admin/calendar/index.ts +1 -1
  42. package/src/admin/documentation-templates/document-manager.admin.ts +260 -260
  43. package/src/admin/documentation-templates/index.ts +1 -1
  44. package/src/admin/free-consultation/free-consultation-utils.admin.ts +148 -148
  45. package/src/admin/free-consultation/index.ts +1 -1
  46. package/src/admin/index.ts +81 -81
  47. package/src/admin/logger/index.ts +78 -78
  48. package/src/admin/mailing/README.md +95 -95
  49. package/src/admin/mailing/appointment/appointment.mailing.service.ts +732 -732
  50. package/src/admin/mailing/appointment/index.ts +1 -1
  51. package/src/admin/mailing/appointment/templates/patient/appointment-confirmed.html +40 -40
  52. package/src/admin/mailing/base.mailing.service.ts +208 -208
  53. package/src/admin/mailing/index.ts +3 -3
  54. package/src/admin/mailing/practitionerInvite/existing-practitioner-invite.mailing.ts +611 -611
  55. package/src/admin/mailing/practitionerInvite/index.ts +2 -2
  56. package/src/admin/mailing/practitionerInvite/practitionerInvite.mailing.ts +395 -395
  57. package/src/admin/mailing/practitionerInvite/templates/existing-practitioner-invitation.template.ts +155 -155
  58. package/src/admin/mailing/practitionerInvite/templates/invitation.template.ts +101 -101
  59. package/src/admin/mailing/practitionerInvite/templates/invite-accepted-notification.template.ts +228 -228
  60. package/src/admin/mailing/practitionerInvite/templates/invite-rejected-notification.template.ts +242 -242
  61. package/src/admin/notifications/index.ts +1 -1
  62. package/src/admin/notifications/notifications.admin.ts +710 -710
  63. package/src/admin/requirements/README.md +128 -128
  64. package/src/admin/requirements/index.ts +1 -1
  65. package/src/admin/requirements/patient-requirements.admin.service.ts +475 -475
  66. package/src/admin/users/index.ts +1 -1
  67. package/src/admin/users/user-profile.admin.ts +405 -405
  68. package/src/backoffice/constants/certification.constants.ts +13 -13
  69. package/src/backoffice/constants/index.ts +1 -1
  70. package/src/backoffice/errors/backoffice.errors.ts +181 -181
  71. package/src/backoffice/errors/index.ts +1 -1
  72. package/src/backoffice/expo-safe/README.md +26 -26
  73. package/src/backoffice/expo-safe/index.ts +41 -41
  74. package/src/backoffice/index.ts +5 -5
  75. package/src/backoffice/services/FIXES_README.md +102 -102
  76. package/src/backoffice/services/README.md +57 -57
  77. package/src/backoffice/services/analytics.service.proposal.md +863 -863
  78. package/src/backoffice/services/analytics.service.summary.md +143 -143
  79. package/src/backoffice/services/brand.service.ts +256 -256
  80. package/src/backoffice/services/category.service.ts +384 -384
  81. package/src/backoffice/services/constants.service.ts +385 -385
  82. package/src/backoffice/services/documentation-template.service.ts +202 -202
  83. package/src/backoffice/services/index.ts +10 -10
  84. package/src/backoffice/services/migrate-products.ts +116 -116
  85. package/src/backoffice/services/product.service.ts +553 -553
  86. package/src/backoffice/services/requirement.service.ts +235 -235
  87. package/src/backoffice/services/subcategory.service.ts +461 -461
  88. package/src/backoffice/services/technology.service.ts +1151 -1151
  89. package/src/backoffice/types/README.md +12 -12
  90. package/src/backoffice/types/admin-constants.types.ts +69 -69
  91. package/src/backoffice/types/brand.types.ts +29 -29
  92. package/src/backoffice/types/category.types.ts +67 -67
  93. package/src/backoffice/types/documentation-templates.types.ts +28 -28
  94. package/src/backoffice/types/index.ts +10 -10
  95. package/src/backoffice/types/procedure-product.types.ts +38 -38
  96. package/src/backoffice/types/product.types.ts +240 -240
  97. package/src/backoffice/types/requirement.types.ts +63 -63
  98. package/src/backoffice/types/static/README.md +18 -18
  99. package/src/backoffice/types/static/blocking-condition.types.ts +21 -21
  100. package/src/backoffice/types/static/certification.types.ts +37 -37
  101. package/src/backoffice/types/static/contraindication.types.ts +19 -19
  102. package/src/backoffice/types/static/index.ts +6 -6
  103. package/src/backoffice/types/static/pricing.types.ts +16 -16
  104. package/src/backoffice/types/static/procedure-family.types.ts +14 -14
  105. package/src/backoffice/types/static/treatment-benefit.types.ts +22 -22
  106. package/src/backoffice/types/subcategory.types.ts +34 -34
  107. package/src/backoffice/types/technology.types.ts +168 -168
  108. package/src/backoffice/validations/index.ts +1 -1
  109. package/src/backoffice/validations/schemas.ts +164 -164
  110. package/src/config/__mocks__/firebase.ts +99 -99
  111. package/src/config/firebase.ts +78 -78
  112. package/src/config/index.ts +9 -9
  113. package/src/errors/auth.error.ts +6 -6
  114. package/src/errors/auth.errors.ts +200 -200
  115. package/src/errors/clinic.errors.ts +32 -32
  116. package/src/errors/firebase.errors.ts +47 -47
  117. package/src/errors/user.errors.ts +99 -99
  118. package/src/index.backup.ts +407 -407
  119. package/src/index.ts +6 -6
  120. package/src/locales/en.ts +31 -31
  121. package/src/recommender/admin/index.ts +1 -1
  122. package/src/recommender/admin/services/recommender.service.admin.ts +5 -5
  123. package/src/recommender/front/index.ts +1 -1
  124. package/src/recommender/front/services/onboarding.service.ts +5 -5
  125. package/src/recommender/front/services/recommender.service.ts +3 -3
  126. package/src/recommender/index.ts +1 -1
  127. package/src/services/PATIENTAUTH.MD +197 -197
  128. package/src/services/README.md +106 -106
  129. package/src/services/__tests__/auth/auth.mock.test.ts +17 -17
  130. package/src/services/__tests__/auth/auth.setup.ts +293 -293
  131. package/src/services/__tests__/auth.service.test.ts +346 -346
  132. package/src/services/__tests__/base.service.test.ts +77 -77
  133. package/src/services/__tests__/user.service.test.ts +528 -528
  134. package/src/services/analytics/ARCHITECTURE.md +199 -199
  135. package/src/services/analytics/CLOUD_FUNCTIONS.md +225 -225
  136. package/src/services/analytics/GROUPED_ANALYTICS.md +501 -501
  137. package/src/services/analytics/QUICK_START.md +393 -393
  138. package/src/services/analytics/README.md +304 -304
  139. package/src/services/analytics/SUMMARY.md +141 -141
  140. package/src/services/analytics/TRENDS.md +380 -380
  141. package/src/services/analytics/USAGE_GUIDE.md +518 -518
  142. package/src/services/analytics/analytics-cloud.service.ts +222 -222
  143. package/src/services/analytics/analytics.service.ts +2142 -2142
  144. package/src/services/analytics/index.ts +4 -4
  145. package/src/services/analytics/review-analytics.service.ts +941 -941
  146. package/src/services/analytics/utils/appointment-filtering.utils.ts +138 -138
  147. package/src/services/analytics/utils/cost-calculation.utils.ts +182 -182
  148. package/src/services/analytics/utils/grouping.utils.ts +434 -434
  149. package/src/services/analytics/utils/stored-analytics.utils.ts +347 -347
  150. package/src/services/analytics/utils/time-calculation.utils.ts +186 -186
  151. package/src/services/analytics/utils/trend-calculation.utils.ts +200 -200
  152. package/src/services/appointment/README.md +17 -17
  153. package/src/services/appointment/appointment.service.ts +2558 -2558
  154. package/src/services/appointment/index.ts +1 -1
  155. package/src/services/appointment/utils/appointment.utils.ts +552 -552
  156. package/src/services/appointment/utils/extended-procedure.utils.ts +314 -314
  157. package/src/services/appointment/utils/form-initialization.utils.ts +225 -225
  158. package/src/services/appointment/utils/recommended-procedure.utils.ts +195 -195
  159. package/src/services/appointment/utils/zone-management.utils.ts +353 -353
  160. package/src/services/appointment/utils/zone-photo.utils.ts +152 -152
  161. package/src/services/auth/auth.service.ts +989 -989
  162. package/src/services/auth/auth.v2.service.ts +961 -961
  163. package/src/services/auth/index.ts +7 -7
  164. package/src/services/auth/utils/error.utils.ts +90 -90
  165. package/src/services/auth/utils/firebase.utils.ts +49 -49
  166. package/src/services/auth/utils/index.ts +21 -21
  167. package/src/services/auth/utils/practitioner.utils.ts +125 -125
  168. package/src/services/base.service.ts +41 -41
  169. package/src/services/calendar/calendar.service.ts +1077 -1077
  170. package/src/services/calendar/calendar.v2.service.ts +1683 -1683
  171. package/src/services/calendar/calendar.v3.service.ts +313 -313
  172. package/src/services/calendar/externalCalendar.service.ts +178 -178
  173. package/src/services/calendar/index.ts +5 -5
  174. package/src/services/calendar/synced-calendars.service.ts +743 -743
  175. package/src/services/calendar/utils/appointment.utils.ts +265 -265
  176. package/src/services/calendar/utils/calendar-event.utils.ts +646 -646
  177. package/src/services/calendar/utils/clinic.utils.ts +237 -237
  178. package/src/services/calendar/utils/docs.utils.ts +157 -157
  179. package/src/services/calendar/utils/google-calendar.utils.ts +697 -697
  180. package/src/services/calendar/utils/index.ts +8 -8
  181. package/src/services/calendar/utils/patient.utils.ts +198 -198
  182. package/src/services/calendar/utils/practitioner.utils.ts +221 -221
  183. package/src/services/calendar/utils/synced-calendar.utils.ts +472 -472
  184. package/src/services/clinic/README.md +204 -204
  185. package/src/services/clinic/__tests__/clinic-admin.service.test.ts +287 -287
  186. package/src/services/clinic/__tests__/clinic-group.service.test.ts +352 -352
  187. package/src/services/clinic/__tests__/clinic.service.test.ts +354 -354
  188. package/src/services/clinic/billing-transactions.service.ts +217 -217
  189. package/src/services/clinic/clinic-admin.service.ts +202 -202
  190. package/src/services/clinic/clinic-group.service.ts +310 -310
  191. package/src/services/clinic/clinic.service.ts +708 -708
  192. package/src/services/clinic/index.ts +5 -5
  193. package/src/services/clinic/practitioner-invite.service.ts +519 -519
  194. package/src/services/clinic/utils/admin.utils.ts +551 -551
  195. package/src/services/clinic/utils/clinic-group.utils.ts +646 -646
  196. package/src/services/clinic/utils/clinic.utils.ts +949 -949
  197. package/src/services/clinic/utils/filter.utils.d.ts +23 -23
  198. package/src/services/clinic/utils/filter.utils.ts +446 -446
  199. package/src/services/clinic/utils/index.ts +11 -11
  200. package/src/services/clinic/utils/photos.utils.ts +188 -188
  201. package/src/services/clinic/utils/search.utils.ts +84 -84
  202. package/src/services/clinic/utils/tag.utils.ts +124 -124
  203. package/src/services/documentation-templates/documentation-template.service.ts +537 -537
  204. package/src/services/documentation-templates/filled-document.service.ts +587 -587
  205. package/src/services/documentation-templates/index.ts +2 -2
  206. package/src/services/index.ts +14 -14
  207. package/src/services/media/index.ts +1 -1
  208. package/src/services/media/media.service.ts +418 -418
  209. package/src/services/notifications/__tests__/notification.service.test.ts +242 -242
  210. package/src/services/notifications/index.ts +1 -1
  211. package/src/services/notifications/notification.service.ts +215 -215
  212. package/src/services/patient/README.md +48 -48
  213. package/src/services/patient/To-Do.md +43 -43
  214. package/src/services/patient/__tests__/patient.service.test.ts +294 -294
  215. package/src/services/patient/index.ts +2 -2
  216. package/src/services/patient/patient.service.ts +883 -883
  217. package/src/services/patient/patientRequirements.service.ts +285 -285
  218. package/src/services/patient/utils/aesthetic-analysis.utils.ts +176 -176
  219. package/src/services/patient/utils/clinic.utils.ts +80 -80
  220. package/src/services/patient/utils/docs.utils.ts +142 -142
  221. package/src/services/patient/utils/index.ts +9 -9
  222. package/src/services/patient/utils/location.utils.ts +126 -126
  223. package/src/services/patient/utils/medical-stuff.utils.ts +143 -143
  224. package/src/services/patient/utils/medical.utils.ts +458 -458
  225. package/src/services/patient/utils/practitioner.utils.ts +260 -260
  226. package/src/services/patient/utils/profile.utils.ts +510 -510
  227. package/src/services/patient/utils/sensitive.utils.ts +260 -260
  228. package/src/services/patient/utils/token.utils.ts +211 -211
  229. package/src/services/practitioner/README.md +145 -145
  230. package/src/services/practitioner/index.ts +1 -1
  231. package/src/services/practitioner/practitioner.service.ts +1742 -1742
  232. package/src/services/procedure/README.md +163 -163
  233. package/src/services/procedure/index.ts +1 -1
  234. package/src/services/procedure/procedure.service.ts +2200 -2200
  235. package/src/services/reviews/index.ts +1 -1
  236. package/src/services/reviews/reviews.service.ts +734 -734
  237. package/src/services/user/index.ts +1 -1
  238. package/src/services/user/user.service.ts +489 -489
  239. package/src/services/user/user.v2.service.ts +466 -466
  240. package/src/types/analytics/analytics.types.ts +597 -597
  241. package/src/types/analytics/grouped-analytics.types.ts +173 -173
  242. package/src/types/analytics/index.ts +4 -4
  243. package/src/types/analytics/stored-analytics.types.ts +137 -137
  244. package/src/types/appointment/index.ts +480 -480
  245. package/src/types/calendar/index.ts +258 -258
  246. package/src/types/calendar/synced-calendar.types.ts +66 -66
  247. package/src/types/clinic/index.ts +498 -498
  248. package/src/types/clinic/practitioner-invite.types.ts +91 -91
  249. package/src/types/clinic/preferences.types.ts +159 -159
  250. package/src/types/clinic/to-do +3 -3
  251. package/src/types/documentation-templates/index.ts +308 -308
  252. package/src/types/index.ts +47 -47
  253. package/src/types/notifications/README.md +77 -77
  254. package/src/types/notifications/index.ts +286 -286
  255. package/src/types/patient/aesthetic-analysis.types.ts +66 -66
  256. package/src/types/patient/allergies.ts +58 -58
  257. package/src/types/patient/index.ts +275 -275
  258. package/src/types/patient/medical-info.types.ts +152 -152
  259. package/src/types/patient/patient-requirements.ts +92 -92
  260. package/src/types/patient/token.types.ts +61 -61
  261. package/src/types/practitioner/index.ts +206 -206
  262. package/src/types/procedure/index.ts +181 -181
  263. package/src/types/profile/index.ts +39 -39
  264. package/src/types/reviews/index.ts +132 -132
  265. package/src/types/tz-lookup.d.ts +4 -4
  266. package/src/types/user/index.ts +38 -38
  267. package/src/utils/TIMESTAMPS.md +176 -176
  268. package/src/utils/TimestampUtils.ts +241 -241
  269. package/src/utils/index.ts +1 -1
  270. package/src/validations/appointment.schema.ts +574 -574
  271. package/src/validations/calendar.schema.ts +225 -225
  272. package/src/validations/clinic.schema.ts +494 -494
  273. package/src/validations/common.schema.ts +25 -25
  274. package/src/validations/documentation-templates/index.ts +1 -1
  275. package/src/validations/documentation-templates/template.schema.ts +220 -220
  276. package/src/validations/documentation-templates.schema.ts +10 -10
  277. package/src/validations/index.ts +20 -20
  278. package/src/validations/media.schema.ts +10 -10
  279. package/src/validations/notification.schema.ts +90 -90
  280. package/src/validations/patient/aesthetic-analysis.schema.ts +55 -55
  281. package/src/validations/patient/medical-info.schema.ts +125 -125
  282. package/src/validations/patient/patient-requirements.schema.ts +84 -84
  283. package/src/validations/patient/token.schema.ts +29 -29
  284. package/src/validations/patient.schema.ts +217 -217
  285. package/src/validations/practitioner.schema.ts +222 -222
  286. package/src/validations/procedure-product.schema.ts +41 -41
  287. package/src/validations/procedure.schema.ts +124 -124
  288. package/src/validations/profile-info.schema.ts +41 -41
  289. package/src/validations/reviews.schema.ts +195 -195
  290. package/src/validations/schemas.ts +104 -104
  291. package/src/validations/shared.schema.ts +78 -78
@@ -1,475 +1,475 @@
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
- import { TimestampUtils } from "../../utils/TimestampUtils";
21
-
22
- /**
23
- * @class PatientRequirementsAdminService
24
- * @description Handles administrative tasks for patient requirement instances, primarily managing associated notifications.
25
- * This service is intended to be used by Cloud Functions triggered by changes to PatientRequirementInstance documents.
26
- */
27
- export class PatientRequirementsAdminService {
28
- private db: admin.firestore.Firestore;
29
- private notificationsAdmin: NotificationsAdmin;
30
-
31
- constructor(firestore?: admin.firestore.Firestore) {
32
- this.db = firestore || admin.firestore();
33
- this.notificationsAdmin = new NotificationsAdmin(this.db);
34
- }
35
-
36
- /**
37
- * Processes a newly created or updated PatientRequirementInstance to schedule notifications for its instructions.
38
- * It will also cancel pre-existing notifications if due times have changed significantly.
39
- *
40
- * @param patientId - The ID of the patient.
41
- * @param instance - The PatientRequirementInstance data (either new or updated).
42
- * @param previousInstanceData - Optional. The previous state of the instance data if it's an update.
43
- * Used to determine if notifications need to be cancelled/rescheduled.
44
- * @returns {Promise<void>} A promise that resolves when processing is complete.
45
- */
46
- async processRequirementInstanceAndScheduleNotifications(
47
- patientId: string,
48
- instance: PatientRequirementInstance,
49
- previousInstanceData?: PatientRequirementInstance
50
- ): Promise<void> {
51
- console.log(
52
- `[PRA_Service] Processing requirement instance ${instance.id} for patient ${patientId}. Overall Status: ${instance.overallStatus}`
53
- );
54
-
55
- const patientProfileRef = this.db
56
- .collection(PATIENTS_COLLECTION)
57
- .doc(patientId);
58
- let patientExpoTokens: string[] = [];
59
-
60
- try {
61
- const patientDoc = await patientProfileRef.get();
62
- if (patientDoc.exists) {
63
- const patientData = patientDoc.data() as PatientProfile;
64
- patientExpoTokens = patientData.expoTokens || [];
65
- }
66
- } catch (error) {
67
- console.error(
68
- `[PRA_Service] Error fetching patient ${patientId} for expo tokens:`,
69
- error
70
- );
71
- }
72
-
73
- if (patientExpoTokens.length === 0) {
74
- console.log(
75
- `[PRA_Service] Patient ${patientId} has no expo tokens. Skipping notification creation for instance ${instance.id}.`
76
- );
77
- }
78
- // Create a new array of instruction objects to avoid mutating the original
79
- // Keep original Timestamp objects by reference
80
- const updatedInstructions: PatientRequirementInstruction[] =
81
- instance.instructions.map((instr) => ({ ...instr }));
82
- let instructionUpdatesMade = false;
83
-
84
- for (let i = 0; i < updatedInstructions.length; i++) {
85
- let currentInstruction = updatedInstructions[i];
86
- const previousInstruction = previousInstanceData?.instructions.find(
87
- (pi) => pi.instructionId === currentInstruction.instructionId
88
- );
89
- const adminTsNow = admin.firestore.Timestamp.now();
90
-
91
- if (
92
- instance.overallStatus ===
93
- PatientRequirementOverallStatus.CANCELLED_APPOINTMENT ||
94
- instance.overallStatus ===
95
- PatientRequirementOverallStatus.SUPERSEDED_RESCHEDULE ||
96
- currentInstruction.status === PatientInstructionStatus.CANCELLED
97
- ) {
98
- if (currentInstruction.notificationId) {
99
- console.log(
100
- `[PRA_Service] Cancelling notification ${currentInstruction.notificationId} for instruction ${currentInstruction.instructionId} of instance ${instance.id}.`
101
- );
102
- await this.notificationsAdmin.updateNotificationStatus(
103
- currentInstruction.notificationId,
104
- NotificationStatus.CANCELLED
105
- );
106
- currentInstruction = {
107
- ...currentInstruction,
108
- notificationId: undefined,
109
- status: PatientInstructionStatus.CANCELLED,
110
- updatedAt: TimestampUtils.adminToClient(
111
- adminTsNow
112
- ) as FirebaseClientTimestamp,
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: TimestampUtils.adminToClient(
148
- adminTsNow
149
- ) as FirebaseClientTimestamp,
150
- };
151
- updatedInstructions[i] = currentInstruction;
152
- instructionUpdatesMade = true;
153
- }
154
-
155
- const shouldSchedule =
156
- currentInstruction.dueTime && // Ensure dueTime exists
157
- currentInstruction.status ===
158
- PatientInstructionStatus.PENDING_NOTIFICATION &&
159
- !currentInstruction.notificationId &&
160
- currentInstruction.dueTime.toMillis() > adminTsNow.toMillis() &&
161
- patientExpoTokens.length > 0;
162
-
163
- if (shouldSchedule) {
164
- console.log(
165
- `[PRA_Service] Scheduling notification for instruction ${
166
- currentInstruction.instructionId
167
- } of instance ${
168
- instance.id
169
- } at ${currentInstruction.dueTime.toDate()}.`
170
- );
171
-
172
- const notificationPayload: Omit<
173
- RequirementInstructionDueNotification,
174
- "id" | "createdAt" | "updatedAt" | "status" | "isRead"
175
- > = {
176
- userId: patientId,
177
- userRole: UserRole.PATIENT,
178
- notificationType: NotificationType.REQUIREMENT_INSTRUCTION_DUE,
179
- notificationTime: currentInstruction.dueTime as any, // dueTime should be an admin.firestore.Timestamp already
180
- notificationTokens: patientExpoTokens,
181
- title: `Reminder: ${instance.requirementName}`,
182
- body: currentInstruction.instructionText,
183
- appointmentId: instance.appointmentId,
184
- patientRequirementInstanceId: instance.id,
185
- instructionId: currentInstruction.instructionId,
186
- originalRequirementId: instance.originalRequirementId,
187
- };
188
-
189
- try {
190
- const createdNotificationId =
191
- await this.notificationsAdmin.createNotification(
192
- notificationPayload as any
193
- );
194
- currentInstruction = {
195
- ...currentInstruction,
196
- notificationId: createdNotificationId,
197
- status: PatientInstructionStatus.PENDING_NOTIFICATION,
198
- updatedAt: TimestampUtils.adminToClient(
199
- adminTsNow
200
- ) as FirebaseClientTimestamp,
201
- };
202
- updatedInstructions[i] = currentInstruction;
203
- instructionUpdatesMade = true;
204
- } catch (error) {
205
- console.error(
206
- `[PRA_Service] Failed to create notification for instruction ${currentInstruction.instructionId}:`,
207
- error
208
- );
209
- }
210
- }
211
- }
212
-
213
- if (instructionUpdatesMade) {
214
- console.log(
215
- `[PRA_Service] Updating instructions array for instance ${instance.id} on patient ${patientId}.`
216
- );
217
- const instanceDocRef = this.db
218
- .collection(PATIENTS_COLLECTION)
219
- .doc(patientId)
220
- .collection(PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME)
221
- .doc(instance.id);
222
-
223
- const finalAdminTsNow = admin.firestore.Timestamp.now();
224
- await instanceDocRef.update({
225
- instructions: updatedInstructions, // Array of instructions with actual Timestamps
226
- updatedAt: TimestampUtils.adminToClient(
227
- finalAdminTsNow
228
- ) as FirebaseClientTimestamp,
229
- });
230
- }
231
- }
232
-
233
- /**
234
- * Cancels all PENDING notifications associated with a specific PatientRequirementInstance.
235
- * Typically called when the instance itself is deleted or its overall status becomes CANCELLED.
236
- *
237
- * @param instance - The PatientRequirementInstance.
238
- * @returns {Promise<void>}
239
- */
240
- async cancelAllNotificationsForInstance(
241
- instance: PatientRequirementInstance
242
- ): Promise<void> {
243
- console.log(
244
- `[PRA_Service] Attempting to cancel all pending notifications for instance ${instance.id}.`
245
- );
246
- let cancelledCount = 0;
247
- for (const instruction of instance.instructions) {
248
- if (instruction.notificationId) {
249
- try {
250
- const notification = await this.notificationsAdmin.getNotification(
251
- instruction.notificationId
252
- );
253
- if (
254
- notification &&
255
- notification.status === NotificationStatus.PENDING
256
- ) {
257
- await this.notificationsAdmin.updateNotificationStatus(
258
- instruction.notificationId,
259
- NotificationStatus.CANCELLED
260
- );
261
- console.log(
262
- `[PRA_Service] Cancelled notification ${instruction.notificationId} for instruction ${instruction.instructionId}.`
263
- );
264
- cancelledCount++;
265
- } else if (notification) {
266
- console.log(
267
- `[PRA_Service] Notification ${instruction.notificationId} for instruction ${instruction.instructionId} was not pending (status: ${notification.status}). Not cancelling.`
268
- );
269
- }
270
- } catch (error) {
271
- console.error(
272
- `[PRA_Service] Error cancelling notification ${instruction.notificationId}:`,
273
- error
274
- );
275
- }
276
- }
277
- }
278
- if (cancelledCount > 0) {
279
- console.log(
280
- `[PRA_Service] Cancelled ${cancelledCount} notifications for instance ${instance.id}.`
281
- );
282
- }
283
- }
284
-
285
- /**
286
- * (Optional - For a cron job)
287
- * Scans for instructions that are past their due time but not yet actioned, and updates their status to MISSED.
288
- * This would typically be called by a scheduled Cloud Function.
289
- *
290
- * @param patientId - The ID of the patient.
291
- * @param instanceId - The ID of the PatientRequirementInstance.
292
- * @returns {Promise<void>}
293
- */
294
- async updateMissedInstructions(
295
- patientId: string,
296
- instanceId: string
297
- ): Promise<void> {
298
- const instanceRef = this.db
299
- .collection(PATIENTS_COLLECTION)
300
- .doc(patientId)
301
- .collection(PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME)
302
- .doc(instanceId);
303
-
304
- const instanceSnap = await instanceRef.get();
305
- if (!instanceSnap.exists) {
306
- console.warn(
307
- `[PRA_Service] Instance ${instanceId} not found during missed check for patient ${patientId}.`
308
- );
309
- return;
310
- }
311
-
312
- const instance = instanceSnap.data() as PatientRequirementInstance;
313
- const adminNowForMissed = admin.firestore.Timestamp.now();
314
-
315
- // Create a new array of instruction objects to avoid mutating the original
316
- const updatedInstructions: PatientRequirementInstruction[] =
317
- instance.instructions.map((instr) => ({ ...instr }));
318
- let changesMade = false;
319
-
320
- for (let i = 0; i < updatedInstructions.length; i++) {
321
- let currentInstruction = updatedInstructions[i];
322
- if (
323
- currentInstruction.dueTime && // Ensure dueTime exists
324
- (currentInstruction.status ===
325
- PatientInstructionStatus.PENDING_NOTIFICATION ||
326
- currentInstruction.status === PatientInstructionStatus.ACTION_DUE) &&
327
- currentInstruction.dueTime.toMillis() < adminNowForMissed.toMillis()
328
- ) {
329
- currentInstruction = {
330
- ...currentInstruction,
331
- status: PatientInstructionStatus.MISSED,
332
- updatedAt: TimestampUtils.adminToClient(
333
- adminNowForMissed
334
- ) as FirebaseClientTimestamp,
335
- };
336
- updatedInstructions[i] = currentInstruction;
337
- changesMade = true;
338
- console.log(
339
- `[PRA_Service] Marked instruction ${currentInstruction.instructionId} in instance ${instanceId} as MISSED.`
340
- );
341
- }
342
- }
343
-
344
- if (changesMade) {
345
- const finalAdminNowForMissedUpdate = admin.firestore.Timestamp.now();
346
- await instanceRef.update({
347
- instructions: updatedInstructions, // Array of instructions with actual Timestamps
348
- updatedAt: TimestampUtils.adminToClient(
349
- finalAdminNowForMissedUpdate
350
- ) as FirebaseClientTimestamp,
351
- });
352
- console.log(
353
- `[PRA_Service] Updated missed instructions for instance ${instanceId}.`
354
- );
355
- }
356
- }
357
-
358
- /**
359
- * Calculates and updates the overallStatus of a PatientRequirementInstance
360
- * based on the statuses of its individual instructions.
361
- *
362
- * @param patientId - The ID of the patient.
363
- * @param instanceId - The ID of the PatientRequirementInstance to update.
364
- * @returns {Promise<void>} A promise that resolves when processing is complete.
365
- */
366
- async updateOverallInstanceStatus(
367
- patientId: string,
368
- instanceId: string
369
- ): Promise<void> {
370
- const instanceRef = this.db
371
- .collection(PATIENTS_COLLECTION)
372
- .doc(patientId)
373
- .collection(PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME)
374
- .doc(instanceId);
375
-
376
- const instanceSnap = await instanceRef.get();
377
- if (!instanceSnap.exists) {
378
- console.warn(
379
- `[PRA_Service] Instance ${instanceId} not found while trying to update overall status for patient ${patientId}.`
380
- );
381
- return;
382
- }
383
-
384
- const instance = instanceSnap.data() as PatientRequirementInstance;
385
-
386
- // Do not override terminal statuses set by other processes
387
- if (
388
- instance.overallStatus ===
389
- PatientRequirementOverallStatus.CANCELLED_APPOINTMENT ||
390
- instance.overallStatus ===
391
- PatientRequirementOverallStatus.SUPERSEDED_RESCHEDULE ||
392
- instance.overallStatus ===
393
- PatientRequirementOverallStatus.FAILED_TO_PROCESS // Assuming FAILED_TO_PROCESS is also a terminal state set by other means if it's a hard failure.
394
- ) {
395
- console.log(
396
- `[PRA_Service] Instance ${instanceId} has overallStatus ${instance.overallStatus}, skipping overall status update based on instruction completion logic.`
397
- );
398
- return;
399
- }
400
-
401
- const nonCancelledInstructions = instance.instructions.filter(
402
- (instr) => instr.status !== PatientInstructionStatus.CANCELLED
403
- );
404
-
405
- if (nonCancelledInstructions.length === 0) {
406
- // If all instructions are cancelled or there are no instructions.
407
- // If it was previously something like ALL_INSTRUCTIONS_MET, it should revert to ACTIVE or a default.
408
- if (instance.overallStatus !== PatientRequirementOverallStatus.ACTIVE) {
409
- console.log(
410
- `[PRA_Service] Instance ${instanceId} has no active (non-cancelled) instructions. Setting to ACTIVE.`
411
- );
412
- await instanceRef.update({
413
- overallStatus: PatientRequirementOverallStatus.ACTIVE,
414
- updatedAt: TimestampUtils.adminToClient(
415
- admin.firestore.Timestamp.now()
416
- ) as FirebaseClientTimestamp,
417
- });
418
- }
419
- return;
420
- }
421
-
422
- // Check if any instruction is still pending action by the patient
423
- const hasPendingOrDueInstructions = nonCancelledInstructions.some(
424
- (instr) =>
425
- instr.status === PatientInstructionStatus.PENDING_NOTIFICATION ||
426
- instr.status === PatientInstructionStatus.ACTION_DUE
427
- );
428
-
429
- let newOverallStatus: PatientRequirementOverallStatus;
430
-
431
- if (hasPendingOrDueInstructions) {
432
- newOverallStatus = PatientRequirementOverallStatus.ACTIVE;
433
- } else {
434
- // All non-cancelled instructions are in a "resolved" state (ACTION_TAKEN, MISSED, SKIPPED)
435
- const effectivelyCompletedCount = nonCancelledInstructions.filter(
436
- (instr) =>
437
- instr.status === PatientInstructionStatus.ACTION_TAKEN ||
438
- instr.status === PatientInstructionStatus.SKIPPED
439
- ).length;
440
-
441
- const totalNonCancelled = nonCancelledInstructions.length;
442
- const completionPercentage =
443
- (effectivelyCompletedCount / totalNonCancelled) * 100;
444
-
445
- if (completionPercentage === 100) {
446
- newOverallStatus = PatientRequirementOverallStatus.ALL_INSTRUCTIONS_MET;
447
- } else if (completionPercentage >= 60) {
448
- // Changed from >60 to >=60 as per common understanding of "more than 60%" often including 60%
449
- newOverallStatus = PatientRequirementOverallStatus.PARTIALLY_COMPLETED;
450
- } else {
451
- // Less than 60% effectively completed (could include some MISSED ones not blocking this calculation directly)
452
- // Or if all are MISSED, this would also fall here if FAILED_TO_PROCESS isn't set for other reasons.
453
- // Your logic: "if less then 60% of instructions are action taken or skipped, then we move status to failed"
454
- newOverallStatus = PatientRequirementOverallStatus.FAILED_TO_PROCESS;
455
- }
456
- }
457
-
458
- if (newOverallStatus !== instance.overallStatus) {
459
- console.log(
460
- `[PRA_Service] Updating overallStatus for instance ${instanceId} from ${instance.overallStatus} to ${newOverallStatus}.`
461
- );
462
- const adminTsNow = admin.firestore.Timestamp.now();
463
- await instanceRef.update({
464
- overallStatus: newOverallStatus,
465
- updatedAt: TimestampUtils.adminToClient(
466
- adminTsNow
467
- ) as FirebaseClientTimestamp,
468
- });
469
- } else {
470
- console.log(
471
- `[PRA_Service] Calculated overallStatus ${newOverallStatus} for instance ${instanceId} is same as current. No update needed.`
472
- );
473
- }
474
- }
475
- }
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
+ import { TimestampUtils } from "../../utils/TimestampUtils";
21
+
22
+ /**
23
+ * @class PatientRequirementsAdminService
24
+ * @description Handles administrative tasks for patient requirement instances, primarily managing associated notifications.
25
+ * This service is intended to be used by Cloud Functions triggered by changes to PatientRequirementInstance documents.
26
+ */
27
+ export class PatientRequirementsAdminService {
28
+ private db: admin.firestore.Firestore;
29
+ private notificationsAdmin: NotificationsAdmin;
30
+
31
+ constructor(firestore?: admin.firestore.Firestore) {
32
+ this.db = firestore || admin.firestore();
33
+ this.notificationsAdmin = new NotificationsAdmin(this.db);
34
+ }
35
+
36
+ /**
37
+ * Processes a newly created or updated PatientRequirementInstance to schedule notifications for its instructions.
38
+ * It will also cancel pre-existing notifications if due times have changed significantly.
39
+ *
40
+ * @param patientId - The ID of the patient.
41
+ * @param instance - The PatientRequirementInstance data (either new or updated).
42
+ * @param previousInstanceData - Optional. The previous state of the instance data if it's an update.
43
+ * Used to determine if notifications need to be cancelled/rescheduled.
44
+ * @returns {Promise<void>} A promise that resolves when processing is complete.
45
+ */
46
+ async processRequirementInstanceAndScheduleNotifications(
47
+ patientId: string,
48
+ instance: PatientRequirementInstance,
49
+ previousInstanceData?: PatientRequirementInstance
50
+ ): Promise<void> {
51
+ console.log(
52
+ `[PRA_Service] Processing requirement instance ${instance.id} for patient ${patientId}. Overall Status: ${instance.overallStatus}`
53
+ );
54
+
55
+ const patientProfileRef = this.db
56
+ .collection(PATIENTS_COLLECTION)
57
+ .doc(patientId);
58
+ let patientExpoTokens: string[] = [];
59
+
60
+ try {
61
+ const patientDoc = await patientProfileRef.get();
62
+ if (patientDoc.exists) {
63
+ const patientData = patientDoc.data() as PatientProfile;
64
+ patientExpoTokens = patientData.expoTokens || [];
65
+ }
66
+ } catch (error) {
67
+ console.error(
68
+ `[PRA_Service] Error fetching patient ${patientId} for expo tokens:`,
69
+ error
70
+ );
71
+ }
72
+
73
+ if (patientExpoTokens.length === 0) {
74
+ console.log(
75
+ `[PRA_Service] Patient ${patientId} has no expo tokens. Skipping notification creation for instance ${instance.id}.`
76
+ );
77
+ }
78
+ // Create a new array of instruction objects to avoid mutating the original
79
+ // Keep original Timestamp objects by reference
80
+ const updatedInstructions: PatientRequirementInstruction[] =
81
+ instance.instructions.map((instr) => ({ ...instr }));
82
+ let instructionUpdatesMade = false;
83
+
84
+ for (let i = 0; i < updatedInstructions.length; i++) {
85
+ let currentInstruction = updatedInstructions[i];
86
+ const previousInstruction = previousInstanceData?.instructions.find(
87
+ (pi) => pi.instructionId === currentInstruction.instructionId
88
+ );
89
+ const adminTsNow = admin.firestore.Timestamp.now();
90
+
91
+ if (
92
+ instance.overallStatus ===
93
+ PatientRequirementOverallStatus.CANCELLED_APPOINTMENT ||
94
+ instance.overallStatus ===
95
+ PatientRequirementOverallStatus.SUPERSEDED_RESCHEDULE ||
96
+ currentInstruction.status === PatientInstructionStatus.CANCELLED
97
+ ) {
98
+ if (currentInstruction.notificationId) {
99
+ console.log(
100
+ `[PRA_Service] Cancelling notification ${currentInstruction.notificationId} for instruction ${currentInstruction.instructionId} of instance ${instance.id}.`
101
+ );
102
+ await this.notificationsAdmin.updateNotificationStatus(
103
+ currentInstruction.notificationId,
104
+ NotificationStatus.CANCELLED
105
+ );
106
+ currentInstruction = {
107
+ ...currentInstruction,
108
+ notificationId: undefined,
109
+ status: PatientInstructionStatus.CANCELLED,
110
+ updatedAt: TimestampUtils.adminToClient(
111
+ adminTsNow
112
+ ) as FirebaseClientTimestamp,
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: TimestampUtils.adminToClient(
148
+ adminTsNow
149
+ ) as FirebaseClientTimestamp,
150
+ };
151
+ updatedInstructions[i] = currentInstruction;
152
+ instructionUpdatesMade = true;
153
+ }
154
+
155
+ const shouldSchedule =
156
+ currentInstruction.dueTime && // Ensure dueTime exists
157
+ currentInstruction.status ===
158
+ PatientInstructionStatus.PENDING_NOTIFICATION &&
159
+ !currentInstruction.notificationId &&
160
+ currentInstruction.dueTime.toMillis() > adminTsNow.toMillis() &&
161
+ patientExpoTokens.length > 0;
162
+
163
+ if (shouldSchedule) {
164
+ console.log(
165
+ `[PRA_Service] Scheduling notification for instruction ${
166
+ currentInstruction.instructionId
167
+ } of instance ${
168
+ instance.id
169
+ } at ${currentInstruction.dueTime.toDate()}.`
170
+ );
171
+
172
+ const notificationPayload: Omit<
173
+ RequirementInstructionDueNotification,
174
+ "id" | "createdAt" | "updatedAt" | "status" | "isRead"
175
+ > = {
176
+ userId: patientId,
177
+ userRole: UserRole.PATIENT,
178
+ notificationType: NotificationType.REQUIREMENT_INSTRUCTION_DUE,
179
+ notificationTime: currentInstruction.dueTime as any, // dueTime should be an admin.firestore.Timestamp already
180
+ notificationTokens: patientExpoTokens,
181
+ title: `Reminder: ${instance.requirementName}`,
182
+ body: currentInstruction.instructionText,
183
+ appointmentId: instance.appointmentId,
184
+ patientRequirementInstanceId: instance.id,
185
+ instructionId: currentInstruction.instructionId,
186
+ originalRequirementId: instance.originalRequirementId,
187
+ };
188
+
189
+ try {
190
+ const createdNotificationId =
191
+ await this.notificationsAdmin.createNotification(
192
+ notificationPayload as any
193
+ );
194
+ currentInstruction = {
195
+ ...currentInstruction,
196
+ notificationId: createdNotificationId,
197
+ status: PatientInstructionStatus.PENDING_NOTIFICATION,
198
+ updatedAt: TimestampUtils.adminToClient(
199
+ adminTsNow
200
+ ) as FirebaseClientTimestamp,
201
+ };
202
+ updatedInstructions[i] = currentInstruction;
203
+ instructionUpdatesMade = true;
204
+ } catch (error) {
205
+ console.error(
206
+ `[PRA_Service] Failed to create notification for instruction ${currentInstruction.instructionId}:`,
207
+ error
208
+ );
209
+ }
210
+ }
211
+ }
212
+
213
+ if (instructionUpdatesMade) {
214
+ console.log(
215
+ `[PRA_Service] Updating instructions array for instance ${instance.id} on patient ${patientId}.`
216
+ );
217
+ const instanceDocRef = this.db
218
+ .collection(PATIENTS_COLLECTION)
219
+ .doc(patientId)
220
+ .collection(PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME)
221
+ .doc(instance.id);
222
+
223
+ const finalAdminTsNow = admin.firestore.Timestamp.now();
224
+ await instanceDocRef.update({
225
+ instructions: updatedInstructions, // Array of instructions with actual Timestamps
226
+ updatedAt: TimestampUtils.adminToClient(
227
+ finalAdminTsNow
228
+ ) as FirebaseClientTimestamp,
229
+ });
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Cancels all PENDING notifications associated with a specific PatientRequirementInstance.
235
+ * Typically called when the instance itself is deleted or its overall status becomes CANCELLED.
236
+ *
237
+ * @param instance - The PatientRequirementInstance.
238
+ * @returns {Promise<void>}
239
+ */
240
+ async cancelAllNotificationsForInstance(
241
+ instance: PatientRequirementInstance
242
+ ): Promise<void> {
243
+ console.log(
244
+ `[PRA_Service] Attempting to cancel all pending notifications for instance ${instance.id}.`
245
+ );
246
+ let cancelledCount = 0;
247
+ for (const instruction of instance.instructions) {
248
+ if (instruction.notificationId) {
249
+ try {
250
+ const notification = await this.notificationsAdmin.getNotification(
251
+ instruction.notificationId
252
+ );
253
+ if (
254
+ notification &&
255
+ notification.status === NotificationStatus.PENDING
256
+ ) {
257
+ await this.notificationsAdmin.updateNotificationStatus(
258
+ instruction.notificationId,
259
+ NotificationStatus.CANCELLED
260
+ );
261
+ console.log(
262
+ `[PRA_Service] Cancelled notification ${instruction.notificationId} for instruction ${instruction.instructionId}.`
263
+ );
264
+ cancelledCount++;
265
+ } else if (notification) {
266
+ console.log(
267
+ `[PRA_Service] Notification ${instruction.notificationId} for instruction ${instruction.instructionId} was not pending (status: ${notification.status}). Not cancelling.`
268
+ );
269
+ }
270
+ } catch (error) {
271
+ console.error(
272
+ `[PRA_Service] Error cancelling notification ${instruction.notificationId}:`,
273
+ error
274
+ );
275
+ }
276
+ }
277
+ }
278
+ if (cancelledCount > 0) {
279
+ console.log(
280
+ `[PRA_Service] Cancelled ${cancelledCount} notifications for instance ${instance.id}.`
281
+ );
282
+ }
283
+ }
284
+
285
+ /**
286
+ * (Optional - For a cron job)
287
+ * Scans for instructions that are past their due time but not yet actioned, and updates their status to MISSED.
288
+ * This would typically be called by a scheduled Cloud Function.
289
+ *
290
+ * @param patientId - The ID of the patient.
291
+ * @param instanceId - The ID of the PatientRequirementInstance.
292
+ * @returns {Promise<void>}
293
+ */
294
+ async updateMissedInstructions(
295
+ patientId: string,
296
+ instanceId: string
297
+ ): Promise<void> {
298
+ const instanceRef = this.db
299
+ .collection(PATIENTS_COLLECTION)
300
+ .doc(patientId)
301
+ .collection(PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME)
302
+ .doc(instanceId);
303
+
304
+ const instanceSnap = await instanceRef.get();
305
+ if (!instanceSnap.exists) {
306
+ console.warn(
307
+ `[PRA_Service] Instance ${instanceId} not found during missed check for patient ${patientId}.`
308
+ );
309
+ return;
310
+ }
311
+
312
+ const instance = instanceSnap.data() as PatientRequirementInstance;
313
+ const adminNowForMissed = admin.firestore.Timestamp.now();
314
+
315
+ // Create a new array of instruction objects to avoid mutating the original
316
+ const updatedInstructions: PatientRequirementInstruction[] =
317
+ instance.instructions.map((instr) => ({ ...instr }));
318
+ let changesMade = false;
319
+
320
+ for (let i = 0; i < updatedInstructions.length; i++) {
321
+ let currentInstruction = updatedInstructions[i];
322
+ if (
323
+ currentInstruction.dueTime && // Ensure dueTime exists
324
+ (currentInstruction.status ===
325
+ PatientInstructionStatus.PENDING_NOTIFICATION ||
326
+ currentInstruction.status === PatientInstructionStatus.ACTION_DUE) &&
327
+ currentInstruction.dueTime.toMillis() < adminNowForMissed.toMillis()
328
+ ) {
329
+ currentInstruction = {
330
+ ...currentInstruction,
331
+ status: PatientInstructionStatus.MISSED,
332
+ updatedAt: TimestampUtils.adminToClient(
333
+ adminNowForMissed
334
+ ) as FirebaseClientTimestamp,
335
+ };
336
+ updatedInstructions[i] = currentInstruction;
337
+ changesMade = true;
338
+ console.log(
339
+ `[PRA_Service] Marked instruction ${currentInstruction.instructionId} in instance ${instanceId} as MISSED.`
340
+ );
341
+ }
342
+ }
343
+
344
+ if (changesMade) {
345
+ const finalAdminNowForMissedUpdate = admin.firestore.Timestamp.now();
346
+ await instanceRef.update({
347
+ instructions: updatedInstructions, // Array of instructions with actual Timestamps
348
+ updatedAt: TimestampUtils.adminToClient(
349
+ finalAdminNowForMissedUpdate
350
+ ) as FirebaseClientTimestamp,
351
+ });
352
+ console.log(
353
+ `[PRA_Service] Updated missed instructions for instance ${instanceId}.`
354
+ );
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Calculates and updates the overallStatus of a PatientRequirementInstance
360
+ * based on the statuses of its individual instructions.
361
+ *
362
+ * @param patientId - The ID of the patient.
363
+ * @param instanceId - The ID of the PatientRequirementInstance to update.
364
+ * @returns {Promise<void>} A promise that resolves when processing is complete.
365
+ */
366
+ async updateOverallInstanceStatus(
367
+ patientId: string,
368
+ instanceId: string
369
+ ): Promise<void> {
370
+ const instanceRef = this.db
371
+ .collection(PATIENTS_COLLECTION)
372
+ .doc(patientId)
373
+ .collection(PATIENT_REQUIREMENTS_SUBCOLLECTION_NAME)
374
+ .doc(instanceId);
375
+
376
+ const instanceSnap = await instanceRef.get();
377
+ if (!instanceSnap.exists) {
378
+ console.warn(
379
+ `[PRA_Service] Instance ${instanceId} not found while trying to update overall status for patient ${patientId}.`
380
+ );
381
+ return;
382
+ }
383
+
384
+ const instance = instanceSnap.data() as PatientRequirementInstance;
385
+
386
+ // Do not override terminal statuses set by other processes
387
+ if (
388
+ instance.overallStatus ===
389
+ PatientRequirementOverallStatus.CANCELLED_APPOINTMENT ||
390
+ instance.overallStatus ===
391
+ PatientRequirementOverallStatus.SUPERSEDED_RESCHEDULE ||
392
+ instance.overallStatus ===
393
+ PatientRequirementOverallStatus.FAILED_TO_PROCESS // Assuming FAILED_TO_PROCESS is also a terminal state set by other means if it's a hard failure.
394
+ ) {
395
+ console.log(
396
+ `[PRA_Service] Instance ${instanceId} has overallStatus ${instance.overallStatus}, skipping overall status update based on instruction completion logic.`
397
+ );
398
+ return;
399
+ }
400
+
401
+ const nonCancelledInstructions = instance.instructions.filter(
402
+ (instr) => instr.status !== PatientInstructionStatus.CANCELLED
403
+ );
404
+
405
+ if (nonCancelledInstructions.length === 0) {
406
+ // If all instructions are cancelled or there are no instructions.
407
+ // If it was previously something like ALL_INSTRUCTIONS_MET, it should revert to ACTIVE or a default.
408
+ if (instance.overallStatus !== PatientRequirementOverallStatus.ACTIVE) {
409
+ console.log(
410
+ `[PRA_Service] Instance ${instanceId} has no active (non-cancelled) instructions. Setting to ACTIVE.`
411
+ );
412
+ await instanceRef.update({
413
+ overallStatus: PatientRequirementOverallStatus.ACTIVE,
414
+ updatedAt: TimestampUtils.adminToClient(
415
+ admin.firestore.Timestamp.now()
416
+ ) as FirebaseClientTimestamp,
417
+ });
418
+ }
419
+ return;
420
+ }
421
+
422
+ // Check if any instruction is still pending action by the patient
423
+ const hasPendingOrDueInstructions = nonCancelledInstructions.some(
424
+ (instr) =>
425
+ instr.status === PatientInstructionStatus.PENDING_NOTIFICATION ||
426
+ instr.status === PatientInstructionStatus.ACTION_DUE
427
+ );
428
+
429
+ let newOverallStatus: PatientRequirementOverallStatus;
430
+
431
+ if (hasPendingOrDueInstructions) {
432
+ newOverallStatus = PatientRequirementOverallStatus.ACTIVE;
433
+ } else {
434
+ // All non-cancelled instructions are in a "resolved" state (ACTION_TAKEN, MISSED, SKIPPED)
435
+ const effectivelyCompletedCount = nonCancelledInstructions.filter(
436
+ (instr) =>
437
+ instr.status === PatientInstructionStatus.ACTION_TAKEN ||
438
+ instr.status === PatientInstructionStatus.SKIPPED
439
+ ).length;
440
+
441
+ const totalNonCancelled = nonCancelledInstructions.length;
442
+ const completionPercentage =
443
+ (effectivelyCompletedCount / totalNonCancelled) * 100;
444
+
445
+ if (completionPercentage === 100) {
446
+ newOverallStatus = PatientRequirementOverallStatus.ALL_INSTRUCTIONS_MET;
447
+ } else if (completionPercentage >= 60) {
448
+ // Changed from >60 to >=60 as per common understanding of "more than 60%" often including 60%
449
+ newOverallStatus = PatientRequirementOverallStatus.PARTIALLY_COMPLETED;
450
+ } else {
451
+ // Less than 60% effectively completed (could include some MISSED ones not blocking this calculation directly)
452
+ // Or if all are MISSED, this would also fall here if FAILED_TO_PROCESS isn't set for other reasons.
453
+ // Your logic: "if less then 60% of instructions are action taken or skipped, then we move status to failed"
454
+ newOverallStatus = PatientRequirementOverallStatus.FAILED_TO_PROCESS;
455
+ }
456
+ }
457
+
458
+ if (newOverallStatus !== instance.overallStatus) {
459
+ console.log(
460
+ `[PRA_Service] Updating overallStatus for instance ${instanceId} from ${instance.overallStatus} to ${newOverallStatus}.`
461
+ );
462
+ const adminTsNow = admin.firestore.Timestamp.now();
463
+ await instanceRef.update({
464
+ overallStatus: newOverallStatus,
465
+ updatedAt: TimestampUtils.adminToClient(
466
+ adminTsNow
467
+ ) as FirebaseClientTimestamp,
468
+ });
469
+ } else {
470
+ console.log(
471
+ `[PRA_Service] Calculated overallStatus ${newOverallStatus} for instance ${instanceId} is same as current. No update needed.`
472
+ );
473
+ }
474
+ }
475
+ }