@blackcode_sa/metaestetics-api 1.15.16 → 1.15.17-staging.1

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 (326) hide show
  1. package/dist/admin/index.d.mts +377 -222
  2. package/dist/admin/index.d.ts +377 -222
  3. package/dist/admin/index.js +625 -206
  4. package/dist/admin/index.mjs +624 -206
  5. package/dist/backoffice/index.d.mts +24 -0
  6. package/dist/backoffice/index.d.ts +24 -0
  7. package/dist/index.d.mts +292 -4
  8. package/dist/index.d.ts +292 -4
  9. package/dist/index.js +1142 -630
  10. package/dist/index.mjs +1137 -617
  11. package/package.json +2 -1
  12. package/src/__mocks__/firstore.ts +10 -10
  13. package/src/admin/aggregation/README.md +79 -79
  14. package/src/admin/aggregation/appointment/README.md +151 -129
  15. package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +2137 -2091
  16. package/src/admin/aggregation/appointment/index.ts +1 -1
  17. package/src/admin/aggregation/clinic/README.md +52 -52
  18. package/src/admin/aggregation/clinic/clinic.aggregation.service.ts +966 -966
  19. package/src/admin/aggregation/clinic/index.ts +1 -1
  20. package/src/admin/aggregation/forms/README.md +13 -13
  21. package/src/admin/aggregation/forms/filled-forms.aggregation.service.ts +322 -322
  22. package/src/admin/aggregation/forms/index.ts +1 -1
  23. package/src/admin/aggregation/index.ts +8 -8
  24. package/src/admin/aggregation/patient/README.md +27 -27
  25. package/src/admin/aggregation/patient/index.ts +1 -1
  26. package/src/admin/aggregation/patient/patient.aggregation.service.ts +141 -141
  27. package/src/admin/aggregation/practitioner/README.md +42 -42
  28. package/src/admin/aggregation/practitioner/index.ts +1 -1
  29. package/src/admin/aggregation/practitioner/practitioner.aggregation.service.ts +433 -433
  30. package/src/admin/aggregation/practitioner-invite/index.ts +1 -1
  31. package/src/admin/aggregation/practitioner-invite/practitioner-invite.aggregation.service.ts +961 -961
  32. package/src/admin/aggregation/procedure/README.md +43 -43
  33. package/src/admin/aggregation/procedure/index.ts +1 -1
  34. package/src/admin/aggregation/procedure/procedure.aggregation.service.ts +702 -702
  35. package/src/admin/aggregation/reviews/index.ts +1 -1
  36. package/src/admin/aggregation/reviews/reviews.aggregation.service.ts +689 -689
  37. package/src/admin/analytics/analytics.admin.service.ts +278 -278
  38. package/src/admin/analytics/index.ts +2 -2
  39. package/src/admin/booking/README.md +184 -125
  40. package/src/admin/booking/booking.admin.ts +1330 -1073
  41. package/src/admin/booking/booking.calculator.ts +850 -712
  42. package/src/admin/booking/booking.types.ts +76 -59
  43. package/src/admin/booking/index.ts +3 -3
  44. package/src/admin/booking/timezones-problem.md +185 -185
  45. package/src/admin/calendar/README.md +62 -7
  46. package/src/admin/calendar/calendar.admin.service.ts +345 -345
  47. package/src/admin/calendar/index.ts +2 -1
  48. package/src/admin/calendar/resource-calendar.admin.ts +198 -0
  49. package/src/admin/documentation-templates/document-manager.admin.ts +260 -260
  50. package/src/admin/documentation-templates/index.ts +1 -1
  51. package/src/admin/free-consultation/free-consultation-utils.admin.ts +148 -148
  52. package/src/admin/free-consultation/index.ts +1 -1
  53. package/src/admin/index.ts +83 -83
  54. package/src/admin/logger/index.ts +78 -78
  55. package/src/admin/mailing/README.md +139 -139
  56. package/src/admin/mailing/appointment/appointment.mailing.service.ts +1253 -1253
  57. package/src/admin/mailing/appointment/index.ts +1 -1
  58. package/src/admin/mailing/appointment/templates/patient/appointment-confirmed.html +40 -40
  59. package/src/admin/mailing/base.mailing.service.ts +208 -208
  60. package/src/admin/mailing/clinicWelcome/clinicWelcome.mailing.ts +292 -292
  61. package/src/admin/mailing/clinicWelcome/index.ts +1 -1
  62. package/src/admin/mailing/clinicWelcome/templates/welcome.template.ts +225 -225
  63. package/src/admin/mailing/index.ts +5 -5
  64. package/src/admin/mailing/patientInvite/index.ts +2 -2
  65. package/src/admin/mailing/patientInvite/patientInvite.mailing.ts +415 -415
  66. package/src/admin/mailing/patientInvite/templates/invitation.template.ts +105 -105
  67. package/src/admin/mailing/practitionerInvite/existing-practitioner-invite.mailing.ts +611 -611
  68. package/src/admin/mailing/practitionerInvite/index.ts +2 -2
  69. package/src/admin/mailing/practitionerInvite/practitionerInvite.mailing.ts +395 -395
  70. package/src/admin/mailing/practitionerInvite/templates/existing-practitioner-invitation.template.ts +155 -155
  71. package/src/admin/mailing/practitionerInvite/templates/invitation.template.ts +101 -101
  72. package/src/admin/mailing/practitionerInvite/templates/invite-accepted-notification.template.ts +228 -228
  73. package/src/admin/mailing/practitionerInvite/templates/invite-rejected-notification.template.ts +242 -242
  74. package/src/admin/notifications/index.ts +1 -1
  75. package/src/admin/notifications/notifications.admin.ts +818 -818
  76. package/src/admin/requirements/README.md +128 -128
  77. package/src/admin/requirements/index.ts +1 -1
  78. package/src/admin/requirements/patient-requirements.admin.service.ts +475 -475
  79. package/src/admin/users/index.ts +1 -1
  80. package/src/admin/users/user-profile.admin.ts +405 -405
  81. package/src/backoffice/constants/certification.constants.ts +13 -13
  82. package/src/backoffice/constants/index.ts +1 -1
  83. package/src/backoffice/errors/backoffice.errors.ts +181 -181
  84. package/src/backoffice/errors/index.ts +1 -1
  85. package/src/backoffice/expo-safe/README.md +26 -26
  86. package/src/backoffice/expo-safe/index.ts +41 -41
  87. package/src/backoffice/index.ts +5 -5
  88. package/src/backoffice/services/FIXES_README.md +102 -102
  89. package/src/backoffice/services/README.md +57 -57
  90. package/src/backoffice/services/analytics.service.proposal.md +863 -863
  91. package/src/backoffice/services/analytics.service.summary.md +143 -143
  92. package/src/backoffice/services/brand.service.ts +260 -260
  93. package/src/backoffice/services/category.service.ts +384 -384
  94. package/src/backoffice/services/constants.service.ts +385 -385
  95. package/src/backoffice/services/documentation-template.service.ts +202 -202
  96. package/src/backoffice/services/index.ts +10 -10
  97. package/src/backoffice/services/migrate-products.ts +116 -116
  98. package/src/backoffice/services/product.service.ts +557 -557
  99. package/src/backoffice/services/requirement.service.ts +235 -235
  100. package/src/backoffice/services/subcategory.service.ts +461 -461
  101. package/src/backoffice/services/technology.service.ts +1153 -1153
  102. package/src/backoffice/types/README.md +12 -12
  103. package/src/backoffice/types/admin-constants.types.ts +69 -69
  104. package/src/backoffice/types/brand.types.ts +29 -29
  105. package/src/backoffice/types/category.types.ts +67 -67
  106. package/src/backoffice/types/documentation-templates.types.ts +28 -28
  107. package/src/backoffice/types/index.ts +10 -10
  108. package/src/backoffice/types/procedure-product.types.ts +38 -38
  109. package/src/backoffice/types/product.types.ts +239 -239
  110. package/src/backoffice/types/requirement.types.ts +63 -63
  111. package/src/backoffice/types/static/README.md +18 -18
  112. package/src/backoffice/types/static/blocking-condition.types.ts +21 -21
  113. package/src/backoffice/types/static/certification.types.ts +37 -37
  114. package/src/backoffice/types/static/contraindication.types.ts +19 -19
  115. package/src/backoffice/types/static/index.ts +6 -6
  116. package/src/backoffice/types/static/pricing.types.ts +16 -16
  117. package/src/backoffice/types/static/procedure-family.types.ts +14 -14
  118. package/src/backoffice/types/static/treatment-benefit.types.ts +22 -22
  119. package/src/backoffice/types/subcategory.types.ts +34 -34
  120. package/src/backoffice/types/technology.types.ts +168 -168
  121. package/src/backoffice/validations/index.ts +1 -1
  122. package/src/backoffice/validations/schemas.ts +164 -164
  123. package/src/config/__mocks__/firebase.ts +99 -99
  124. package/src/config/firebase.ts +78 -78
  125. package/src/config/index.ts +17 -17
  126. package/src/config/tiers.config.ts +255 -229
  127. package/src/errors/auth.error.ts +6 -6
  128. package/src/errors/auth.errors.ts +211 -211
  129. package/src/errors/clinic.errors.ts +32 -32
  130. package/src/errors/firebase.errors.ts +47 -47
  131. package/src/errors/user.errors.ts +99 -99
  132. package/src/index.backup.ts +407 -407
  133. package/src/index.ts +6 -6
  134. package/src/locales/en.ts +31 -31
  135. package/src/recommender/admin/index.ts +1 -1
  136. package/src/recommender/admin/services/recommender.service.admin.ts +5 -5
  137. package/src/recommender/front/index.ts +1 -1
  138. package/src/recommender/front/services/onboarding.service.ts +5 -5
  139. package/src/recommender/front/services/recommender.service.ts +3 -3
  140. package/src/recommender/index.ts +1 -1
  141. package/src/services/PATIENTAUTH.MD +197 -197
  142. package/src/services/README.md +106 -106
  143. package/src/services/__tests__/auth/auth.mock.test.ts +17 -17
  144. package/src/services/__tests__/auth/auth.setup.ts +298 -298
  145. package/src/services/__tests__/auth.service.test.ts +310 -310
  146. package/src/services/__tests__/base.service.test.ts +36 -36
  147. package/src/services/__tests__/user.service.test.ts +530 -530
  148. package/src/services/analytics/ARCHITECTURE.md +199 -199
  149. package/src/services/analytics/CLOUD_FUNCTIONS.md +225 -225
  150. package/src/services/analytics/GROUPED_ANALYTICS.md +501 -501
  151. package/src/services/analytics/QUICK_START.md +393 -393
  152. package/src/services/analytics/README.md +304 -304
  153. package/src/services/analytics/SUMMARY.md +141 -141
  154. package/src/services/analytics/TRENDS.md +380 -380
  155. package/src/services/analytics/USAGE_GUIDE.md +518 -518
  156. package/src/services/analytics/analytics-cloud.service.ts +222 -222
  157. package/src/services/analytics/analytics.service.ts +2148 -2148
  158. package/src/services/analytics/index.ts +4 -4
  159. package/src/services/analytics/review-analytics.service.ts +941 -941
  160. package/src/services/analytics/utils/appointment-filtering.utils.ts +138 -138
  161. package/src/services/analytics/utils/cost-calculation.utils.ts +182 -182
  162. package/src/services/analytics/utils/grouping.utils.ts +434 -434
  163. package/src/services/analytics/utils/stored-analytics.utils.ts +347 -347
  164. package/src/services/analytics/utils/time-calculation.utils.ts +186 -186
  165. package/src/services/analytics/utils/trend-calculation.utils.ts +200 -200
  166. package/src/services/appointment/README.md +17 -17
  167. package/src/services/appointment/appointment.service.ts +2943 -2941
  168. package/src/services/appointment/index.ts +1 -1
  169. package/src/services/appointment/utils/appointment.utils.ts +620 -620
  170. package/src/services/appointment/utils/extended-procedure.utils.ts +354 -354
  171. package/src/services/appointment/utils/form-initialization.utils.ts +516 -516
  172. package/src/services/appointment/utils/recommended-procedure.utils.ts +195 -195
  173. package/src/services/appointment/utils/zone-management.utils.ts +468 -468
  174. package/src/services/appointment/utils/zone-photo.utils.ts +302 -302
  175. package/src/services/auth/auth.service.ts +1435 -1435
  176. package/src/services/auth/auth.v2.service.ts +961 -961
  177. package/src/services/auth/index.ts +7 -7
  178. package/src/services/auth/utils/error.utils.ts +90 -90
  179. package/src/services/auth/utils/firebase.utils.ts +49 -49
  180. package/src/services/auth/utils/index.ts +21 -21
  181. package/src/services/auth/utils/practitioner.utils.ts +125 -125
  182. package/src/services/base.service.ts +41 -41
  183. package/src/services/calendar/calendar.service.ts +1077 -1077
  184. package/src/services/calendar/calendar.v2.service.ts +1693 -1693
  185. package/src/services/calendar/calendar.v3.service.ts +313 -313
  186. package/src/services/calendar/externalCalendar.service.ts +178 -178
  187. package/src/services/calendar/index.ts +5 -5
  188. package/src/services/calendar/synced-calendars.service.ts +743 -743
  189. package/src/services/calendar/utils/appointment.utils.ts +265 -265
  190. package/src/services/calendar/utils/calendar-event.utils.ts +676 -676
  191. package/src/services/calendar/utils/clinic.utils.ts +237 -237
  192. package/src/services/calendar/utils/docs.utils.ts +157 -157
  193. package/src/services/calendar/utils/google-calendar.utils.ts +697 -697
  194. package/src/services/calendar/utils/index.ts +8 -8
  195. package/src/services/calendar/utils/patient.utils.ts +198 -198
  196. package/src/services/calendar/utils/practitioner.utils.ts +221 -221
  197. package/src/services/calendar/utils/synced-calendar.utils.ts +472 -472
  198. package/src/services/clinic/README.md +204 -204
  199. package/src/services/clinic/__tests__/clinic-admin.service.test.ts +265 -265
  200. package/src/services/clinic/__tests__/clinic-group.service.test.ts +222 -222
  201. package/src/services/clinic/__tests__/clinic.service.test.ts +302 -302
  202. package/src/services/clinic/billing-transactions.service.ts +217 -217
  203. package/src/services/clinic/clinic-admin.service.ts +202 -202
  204. package/src/services/clinic/clinic-group.service.ts +310 -310
  205. package/src/services/clinic/clinic.service.ts +720 -720
  206. package/src/services/clinic/index.ts +5 -5
  207. package/src/services/clinic/practitioner-invite.service.ts +519 -519
  208. package/src/services/clinic/utils/admin.utils.ts +551 -551
  209. package/src/services/clinic/utils/clinic-group.utils.ts +646 -646
  210. package/src/services/clinic/utils/clinic.utils.ts +1023 -1023
  211. package/src/services/clinic/utils/filter.utils.d.ts +23 -23
  212. package/src/services/clinic/utils/filter.utils.ts +462 -462
  213. package/src/services/clinic/utils/index.ts +10 -10
  214. package/src/services/clinic/utils/photos.utils.ts +188 -188
  215. package/src/services/clinic/utils/search.utils.ts +83 -83
  216. package/src/services/clinic/utils/tag.utils.ts +124 -124
  217. package/src/services/documentation-templates/documentation-template.service.ts +537 -537
  218. package/src/services/documentation-templates/filled-document.service.ts +597 -597
  219. package/src/services/documentation-templates/index.ts +2 -2
  220. package/src/services/index.ts +16 -15
  221. package/src/services/media/index.ts +1 -1
  222. package/src/services/media/media.service.ts +418 -418
  223. package/src/services/notifications/__tests__/notification.service.test.ts +242 -242
  224. package/src/services/notifications/index.ts +1 -1
  225. package/src/services/notifications/notification.service.ts +215 -215
  226. package/src/services/patient/README.md +48 -48
  227. package/src/services/patient/To-Do.md +43 -43
  228. package/src/services/patient/__tests__/patient.service.test.ts +286 -286
  229. package/src/services/patient/index.ts +2 -2
  230. package/src/services/patient/patient.service.ts +1021 -1021
  231. package/src/services/patient/patientRequirements.service.ts +309 -309
  232. package/src/services/patient/utils/aesthetic-analysis.utils.ts +176 -176
  233. package/src/services/patient/utils/body-assessment.utils.ts +159 -159
  234. package/src/services/patient/utils/clinic.utils.ts +159 -159
  235. package/src/services/patient/utils/docs.utils.ts +142 -142
  236. package/src/services/patient/utils/hair-scalp-assessment.utils.ts +158 -158
  237. package/src/services/patient/utils/index.ts +9 -9
  238. package/src/services/patient/utils/location.utils.ts +126 -126
  239. package/src/services/patient/utils/medical-stuff.utils.ts +143 -143
  240. package/src/services/patient/utils/medical.utils.ts +458 -458
  241. package/src/services/patient/utils/practitioner.utils.ts +260 -260
  242. package/src/services/patient/utils/pre-surgical-assessment.utils.ts +161 -161
  243. package/src/services/patient/utils/profile.utils.ts +510 -510
  244. package/src/services/patient/utils/sensitive.utils.ts +260 -260
  245. package/src/services/patient/utils/skin-quality-assessment.utils.ts +160 -160
  246. package/src/services/patient/utils/token.utils.ts +211 -211
  247. package/src/services/practitioner/README.md +145 -145
  248. package/src/services/practitioner/index.ts +1 -1
  249. package/src/services/practitioner/practitioner.service.ts +2355 -2354
  250. package/src/services/procedure/README.md +163 -163
  251. package/src/services/procedure/index.ts +1 -1
  252. package/src/services/procedure/procedure.service.ts +2521 -2521
  253. package/src/services/resource/README.md +119 -0
  254. package/src/services/resource/index.ts +1 -0
  255. package/src/services/resource/resource.service.ts +555 -0
  256. package/src/services/reviews/index.ts +1 -1
  257. package/src/services/reviews/reviews.service.ts +745 -745
  258. package/src/services/tier-enforcement.ts +240 -240
  259. package/src/services/user/index.ts +1 -1
  260. package/src/services/user/user.service.ts +533 -533
  261. package/src/services/user/user.v2.service.ts +467 -467
  262. package/src/types/analytics/analytics.types.ts +597 -597
  263. package/src/types/analytics/grouped-analytics.types.ts +173 -173
  264. package/src/types/analytics/index.ts +4 -4
  265. package/src/types/analytics/stored-analytics.types.ts +137 -137
  266. package/src/types/appointment/index.ts +524 -517
  267. package/src/types/calendar/index.ts +261 -260
  268. package/src/types/calendar/synced-calendar.types.ts +66 -66
  269. package/src/types/clinic/index.ts +530 -529
  270. package/src/types/clinic/practitioner-invite.types.ts +91 -91
  271. package/src/types/clinic/preferences.types.ts +159 -159
  272. package/src/types/clinic/rbac.types.ts +64 -63
  273. package/src/types/clinic/to-do +3 -3
  274. package/src/types/documentation-templates/index.ts +308 -308
  275. package/src/types/index.ts +50 -47
  276. package/src/types/notifications/README.md +77 -77
  277. package/src/types/notifications/index.ts +300 -300
  278. package/src/types/patient/aesthetic-analysis.types.ts +66 -66
  279. package/src/types/patient/allergies.ts +58 -58
  280. package/src/types/patient/body-assessment.types.ts +93 -93
  281. package/src/types/patient/hair-scalp-assessment.types.ts +98 -98
  282. package/src/types/patient/index.ts +279 -279
  283. package/src/types/patient/medical-info.types.ts +152 -152
  284. package/src/types/patient/patient-requirements.ts +92 -92
  285. package/src/types/patient/pre-surgical-assessment.types.ts +95 -95
  286. package/src/types/patient/skin-quality-assessment.types.ts +105 -105
  287. package/src/types/patient/token.types.ts +61 -61
  288. package/src/types/practitioner/index.ts +208 -208
  289. package/src/types/procedure/index.ts +189 -183
  290. package/src/types/profile/index.ts +39 -39
  291. package/src/types/resource/README.md +153 -0
  292. package/src/types/resource/index.ts +199 -0
  293. package/src/types/reviews/index.ts +132 -132
  294. package/src/types/tz-lookup.d.ts +4 -4
  295. package/src/types/user/index.ts +60 -60
  296. package/src/utils/TIMESTAMPS.md +176 -176
  297. package/src/utils/TimestampUtils.ts +241 -241
  298. package/src/utils/index.ts +1 -1
  299. package/src/validations/README.md +94 -0
  300. package/src/validations/appointment.schema.ts +589 -589
  301. package/src/validations/calendar.schema.ts +225 -225
  302. package/src/validations/clinic.schema.ts +494 -494
  303. package/src/validations/common.schema.ts +25 -25
  304. package/src/validations/documentation-templates/index.ts +1 -1
  305. package/src/validations/documentation-templates/template.schema.ts +220 -220
  306. package/src/validations/documentation-templates.schema.ts +10 -10
  307. package/src/validations/index.ts +21 -20
  308. package/src/validations/media.schema.ts +10 -10
  309. package/src/validations/notification.schema.ts +90 -90
  310. package/src/validations/patient/aesthetic-analysis.schema.ts +55 -55
  311. package/src/validations/patient/body-assessment.schema.ts +82 -82
  312. package/src/validations/patient/hair-scalp-assessment.schema.ts +70 -70
  313. package/src/validations/patient/medical-info.schema.ts +177 -177
  314. package/src/validations/patient/patient-requirements.schema.ts +84 -84
  315. package/src/validations/patient/pre-surgical-assessment.schema.ts +78 -78
  316. package/src/validations/patient/skin-quality-assessment.schema.ts +70 -70
  317. package/src/validations/patient/token.schema.ts +29 -29
  318. package/src/validations/patient.schema.ts +217 -217
  319. package/src/validations/practitioner.schema.ts +224 -224
  320. package/src/validations/procedure-product.schema.ts +41 -41
  321. package/src/validations/procedure.schema.ts +136 -124
  322. package/src/validations/profile-info.schema.ts +41 -41
  323. package/src/validations/resource.schema.ts +57 -0
  324. package/src/validations/reviews.schema.ts +195 -195
  325. package/src/validations/schemas.ts +109 -109
  326. package/src/validations/shared.schema.ts +78 -78
@@ -1,1073 +1,1330 @@
1
- import * as admin from "firebase-admin";
2
- import { Timestamp as FirebaseClientTimestamp } from "@firebase/firestore";
3
- import {
4
- BookingAvailabilityCalculator,
5
- BookingAvailabilityRequest,
6
- BookingAvailabilityResponse,
7
- AvailableSlot,
8
- } from "./";
9
- import { CalendarEventStatus, CalendarEventType } from "../../types/calendar";
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 {
41
- DocumentTemplate as AppDocumentTemplate,
42
- FilledDocument,
43
- FilledDocumentStatus,
44
- USER_FORMS_SUBCOLLECTION,
45
- DOCTOR_FORMS_SUBCOLLECTION,
46
- } from "../../types/documentation-templates";
47
- import { TechnologyDocumentationTemplate } from "../../backoffice/types/technology.types";
48
- import {
49
- ClinicInfo,
50
- PractitionerProfileInfo,
51
- PatientProfileInfo,
52
- } from "../../types/profile";
53
- import { Category } from "../../backoffice/types/category.types";
54
- import { Subcategory } from "../../backoffice/types/subcategory.types";
55
- import { Technology } from "../../backoffice/types/technology.types";
56
- import { Product } from "../../backoffice/types/product.types";
57
- import {
58
- CalendarEvent,
59
- CalendarEventTime,
60
- CalendarSyncStatus,
61
- ProcedureInfo as CalendarProcedureInfo,
62
- CALENDAR_COLLECTION,
63
- } from "../../types/calendar";
64
- import { DocumentManagerAdminService } from "../documentation-templates/document-manager.admin";
65
- import { LinkedFormInfo } from "../../types/appointment";
66
- import { TimestampUtils } from "../../utils/TimestampUtils";
67
- import { Logger } from "../logger";
68
-
69
- /**
70
- * Interface for the data required by orchestrateAppointmentCreation
71
- */
72
- export interface OrchestrateAppointmentCreationData {
73
- patientId: string;
74
- procedureId: string;
75
- appointmentStartTime: admin.firestore.Timestamp;
76
- appointmentEndTime: admin.firestore.Timestamp;
77
- patientNotes?: string | null;
78
- }
79
-
80
- /**
81
- * Admin service for handling booking-related operations.
82
- * This is the cloud-based implementation that will be used in Cloud Functions.
83
- */
84
- export class BookingAdmin {
85
- private db: admin.firestore.Firestore;
86
- private documentManagerAdmin: DocumentManagerAdminService;
87
-
88
- /**
89
- * Creates a new BookingAdmin instance
90
- * @param firestore - Firestore instance provided by the caller
91
- */
92
- constructor(firestore?: admin.firestore.Firestore) {
93
- this.db = firestore || admin.firestore();
94
- this.documentManagerAdmin = new DocumentManagerAdminService(this.db);
95
- }
96
-
97
- /**
98
- * Gets available booking time slots for a specific clinic, practitioner, and procedure
99
- *
100
- * @param clinicId - ID of the clinic
101
- * @param practitionerId - ID of the practitioner
102
- * @param procedureId - ID of the procedure
103
- * @param timeframe - Time range to check for availability
104
- * @returns Promise resolving to an array of available booking slots
105
- */
106
- async getAvailableBookingSlots(
107
- clinicId: string,
108
- practitionerId: string,
109
- procedureId: string,
110
- timeframe: {
111
- start: Date | admin.firestore.Timestamp;
112
- end: Date | admin.firestore.Timestamp;
113
- }
114
- ): Promise<{ availableSlots: { start: admin.firestore.Timestamp }[] }> {
115
- try {
116
- Logger.info("[BookingAdmin] Starting availability calculation", {
117
- clinicId,
118
- practitionerId,
119
- procedureId,
120
- timeframeStart:
121
- timeframe.start instanceof Date
122
- ? timeframe.start.toISOString()
123
- : timeframe.start.toDate().toISOString(),
124
- timeframeEnd:
125
- timeframe.end instanceof Date
126
- ? timeframe.end.toISOString()
127
- : timeframe.end.toDate().toISOString(),
128
- });
129
-
130
- // Convert timeframe dates to Firestore Timestamps if needed
131
- const start =
132
- timeframe.start instanceof Date
133
- ? admin.firestore.Timestamp.fromDate(timeframe.start)
134
- : timeframe.start;
135
-
136
- const end =
137
- timeframe.end instanceof Date
138
- ? admin.firestore.Timestamp.fromDate(timeframe.end)
139
- : timeframe.end;
140
-
141
- // 1. Fetch clinic data
142
- Logger.debug("[BookingAdmin] Fetching clinic data", { clinicId });
143
- const clinicDoc = await this.db.collection("clinics").doc(clinicId).get();
144
- if (!clinicDoc.exists) {
145
- Logger.error("[BookingAdmin] Clinic not found", { clinicId });
146
- throw new Error(`Clinic ${clinicId} not found`);
147
- }
148
- const clinic = clinicDoc.data() as unknown as Clinic;
149
- Logger.debug("[BookingAdmin] Retrieved clinic data", {
150
- clinicName: clinic.name,
151
- clinicHasWorkingHours: !!clinic.workingHours,
152
- });
153
-
154
- // 2. Fetch practitioner data
155
- Logger.debug("[BookingAdmin] Fetching practitioner data", {
156
- practitionerId,
157
- });
158
- const practitionerDoc = await this.db
159
- .collection("practitioners")
160
- .doc(practitionerId)
161
- .get();
162
- if (!practitionerDoc.exists) {
163
- Logger.error("[BookingAdmin] Practitioner not found", {
164
- practitionerId,
165
- });
166
- throw new Error(`Practitioner ${practitionerId} not found`);
167
- }
168
- const practitioner = practitionerDoc.data() as unknown as Practitioner;
169
- Logger.debug("[BookingAdmin] Retrieved practitioner data", {
170
- practitionerName: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
171
- pracWorkingHoursCount: practitioner.clinicWorkingHours?.length || 0,
172
- });
173
-
174
- // 3. Fetch procedure data
175
- Logger.debug("[BookingAdmin] Fetching procedure data", { procedureId });
176
- const procedureDoc = await this.db
177
- .collection("procedures")
178
- .doc(procedureId)
179
- .get();
180
- if (!procedureDoc.exists) {
181
- Logger.error("[BookingAdmin] Procedure not found", { procedureId });
182
- throw new Error(`Procedure ${procedureId} not found`);
183
- }
184
- const procedure = procedureDoc.data() as unknown as Procedure;
185
- Logger.debug("[BookingAdmin] Retrieved procedure data", {
186
- procedureName: procedure.name,
187
- procedureDuration: procedure.duration,
188
- });
189
-
190
- // 4. Fetch clinic calendar events
191
- Logger.debug("[BookingAdmin] Fetching clinic calendar events", {
192
- clinicId,
193
- startTime: start.toDate().toISOString(),
194
- endTime: end.toDate().toISOString(),
195
- });
196
- const clinicCalendarEvents = await this.getClinicCalendarEvents(
197
- clinicId,
198
- start,
199
- end
200
- );
201
- Logger.debug("[BookingAdmin] Retrieved clinic calendar events", {
202
- count: clinicCalendarEvents.length,
203
- });
204
-
205
- // 5. Fetch practitioner calendar events
206
- Logger.debug("[BookingAdmin] Fetching practitioner calendar events", {
207
- practitionerId,
208
- startTime: start.toDate().toISOString(),
209
- endTime: end.toDate().toISOString(),
210
- });
211
- const practitionerCalendarEvents =
212
- await this.getPractitionerCalendarEvents(practitionerId, start, end);
213
- Logger.debug("[BookingAdmin] Retrieved practitioner calendar events", {
214
- count: practitionerCalendarEvents.length,
215
- });
216
-
217
- // Since we're working with two different Timestamp implementations (admin vs client),
218
- // we need to convert our timestamps to the client-side format expected by the calculator
219
- // Create client Timestamp objects from admin Timestamp objects
220
- const convertedTimeframe = {
221
- start: this.adminTimestampToClientTimestamp(start),
222
- end: this.adminTimestampToClientTimestamp(end),
223
- };
224
-
225
- // Create the request object for the calculator
226
- const request: BookingAvailabilityRequest = {
227
- clinic,
228
- practitioner,
229
- procedure,
230
- timeframe: convertedTimeframe,
231
- clinicCalendarEvents:
232
- this.convertEventsTimestamps(clinicCalendarEvents),
233
- practitionerCalendarEvents: this.convertEventsTimestamps(
234
- practitionerCalendarEvents
235
- ),
236
- tz: clinic.location.tz || "UTC",
237
- };
238
-
239
- Logger.info("[BookingAdmin] Calling availability calculator", {
240
- calculatorInputReady: true,
241
- timeframeDurationHours: Math.round(
242
- (end.toMillis() - start.toMillis()) / (1000 * 60 * 60)
243
- ),
244
- clinicEventsCount: clinicCalendarEvents.length,
245
- practitionerEventsCount: practitionerCalendarEvents.length,
246
- });
247
-
248
- // Use the calculator to compute available slots
249
- const result = BookingAvailabilityCalculator.calculateSlots(request);
250
-
251
- // Convert the client Timestamps to admin Timestamps before returning
252
- const availableSlotsResult = {
253
- availableSlots: result.availableSlots.map((slot) => ({
254
- start: admin.firestore.Timestamp.fromMillis(slot.start.toMillis()),
255
- })),
256
- };
257
-
258
- Logger.info(
259
- "[BookingAdmin] Availability calculation completed successfully",
260
- {
261
- availableSlotsCount: availableSlotsResult.availableSlots.length,
262
- firstSlotTime:
263
- availableSlotsResult.availableSlots.length > 0
264
- ? availableSlotsResult.availableSlots[0].start
265
- .toDate()
266
- .toISOString()
267
- : "none",
268
- lastSlotTime:
269
- availableSlotsResult.availableSlots.length > 0
270
- ? availableSlotsResult.availableSlots[
271
- availableSlotsResult.availableSlots.length - 1
272
- ].start
273
- .toDate()
274
- .toISOString()
275
- : "none",
276
- }
277
- );
278
-
279
- return availableSlotsResult;
280
- } catch (error) {
281
- const errorMessage =
282
- error instanceof Error ? error.message : String(error);
283
- Logger.error("[BookingAdmin] Error getting available slots", {
284
- errorMessage,
285
- clinicId,
286
- practitionerId,
287
- procedureId,
288
- stack: error instanceof Error ? error.stack : undefined,
289
- });
290
- throw error;
291
- }
292
- }
293
-
294
- /**
295
- * Converts an admin Firestore Timestamp to a client Firestore Timestamp
296
- */
297
- private adminTimestampToClientTimestamp(
298
- timestamp: admin.firestore.Timestamp
299
- ): FirebaseClientTimestamp {
300
- // Use TimestampUtils instead of custom implementation
301
- return TimestampUtils.adminToClient(timestamp) as FirebaseClientTimestamp;
302
- }
303
-
304
- /**
305
- * Converts timestamps in calendar events from admin Firestore Timestamps to client Firestore Timestamps
306
- */
307
- private convertEventsTimestamps(events: any[]): any[] {
308
- return events.map((event) => ({
309
- ...event,
310
- eventTime: {
311
- start: TimestampUtils.adminToClient(
312
- event.eventTime.start
313
- ) as FirebaseClientTimestamp,
314
- end: TimestampUtils.adminToClient(
315
- event.eventTime.end
316
- ) as FirebaseClientTimestamp,
317
- },
318
- // Convert any other timestamps in the event if needed
319
- }));
320
- }
321
-
322
- /**
323
- * Fetches clinic calendar events for a specific time range
324
- *
325
- * @param clinicId - ID of the clinic
326
- * @param start - Start time of the range
327
- * @param end - End time of the range
328
- * @returns Promise resolving to an array of calendar events
329
- */
330
- private async getClinicCalendarEvents(
331
- clinicId: string,
332
- start: admin.firestore.Timestamp,
333
- end: admin.firestore.Timestamp
334
- ): Promise<any[]> {
335
- try {
336
- Logger.debug("[BookingAdmin] Querying clinic calendar events", {
337
- clinicId,
338
- startTime: start.toDate().toISOString(),
339
- endTime: end.toDate().toISOString(),
340
- });
341
-
342
- // Increased to 30 days to handle long blocking events (e.g., holidays, extended time off)
343
- // This ensures we catch blocking events that start before our query range but overlap with it
344
- const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
345
- const queryStart = admin.firestore.Timestamp.fromMillis(
346
- start.toMillis() - MAX_EVENT_DURATION_MS
347
- );
348
-
349
- // Query for events that:
350
- // 1. Start before or during our query range (eventTime.start < end)
351
- // 2. We'll post-filter to ensure they overlap (eventTime.end > start)
352
- const eventsRef = this.db
353
- .collection(`clinics/${clinicId}/calendar`)
354
- .where("eventTime.start", ">=", queryStart)
355
- .where("eventTime.start", "<=", end)
356
- .orderBy("eventTime.start");
357
-
358
- const snapshot = await eventsRef.get();
359
-
360
- // Post-filter to ensure events actually overlap with our query range
361
- // An event overlaps if: eventTime.start < queryEnd AND eventTime.end > queryStart
362
- const events = snapshot.docs
363
- .map((doc) => ({
364
- ...doc.data(),
365
- id: doc.id,
366
- }))
367
- .filter((event: any) => {
368
- // Event overlaps if it ends after our start time
369
- const overlaps = event.eventTime.end.toMillis() > start.toMillis();
370
- if (!overlaps) {
371
- Logger.debug("[BookingAdmin] Filtered out non-overlapping event", {
372
- eventId: event.id,
373
- eventStart: event.eventTime.start.toDate().toISOString(),
374
- eventEnd: event.eventTime.end.toDate().toISOString(),
375
- queryStart: start.toDate().toISOString(),
376
- queryEnd: end.toDate().toISOString(),
377
- });
378
- }
379
- return overlaps;
380
- });
381
-
382
- Logger.debug("[BookingAdmin] Retrieved clinic calendar events", {
383
- clinicId,
384
- eventsCount: events.length,
385
- eventsTypes: this.summarizeEventTypes(events),
386
- queryStartTime: queryStart.toDate().toISOString(),
387
- });
388
-
389
- return events;
390
- } catch (error) {
391
- const errorMessage =
392
- error instanceof Error ? error.message : String(error);
393
- Logger.error("[BookingAdmin] Error fetching clinic calendar events", {
394
- errorMessage,
395
- clinicId,
396
- startTime: start.toDate().toISOString(),
397
- endTime: end.toDate().toISOString(),
398
- stack: error instanceof Error ? error.stack : undefined,
399
- });
400
- return [];
401
- }
402
- }
403
-
404
- /**
405
- * Fetches practitioner calendar events for a specific time range
406
- *
407
- * @param practitionerId - ID of the practitioner
408
- * @param start - Start time of the range
409
- * @param end - End time of the range
410
- * @returns Promise resolving to an array of calendar events
411
- */
412
- private async getPractitionerCalendarEvents(
413
- practitionerId: string,
414
- start: admin.firestore.Timestamp,
415
- end: admin.firestore.Timestamp
416
- ): Promise<any[]> {
417
- try {
418
- Logger.debug("[BookingAdmin] Querying practitioner calendar events", {
419
- practitionerId,
420
- startTime: start.toDate().toISOString(),
421
- endTime: end.toDate().toISOString(),
422
- });
423
-
424
- // Increased to 30 days to handle long blocking events (e.g., holidays, extended time off)
425
- // This ensures we catch blocking events that start before our query range but overlap with it
426
- const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
427
- const queryStart = admin.firestore.Timestamp.fromMillis(
428
- start.toMillis() - MAX_EVENT_DURATION_MS
429
- );
430
-
431
- // Query for events that:
432
- // 1. Start before or during our query range (eventTime.start <= end)
433
- // 2. We'll post-filter to ensure they overlap (eventTime.end > start)
434
- const eventsRef = this.db
435
- .collection(`practitioners/${practitionerId}/calendar`)
436
- .where("eventTime.start", ">=", queryStart)
437
- .where("eventTime.start", "<=", end)
438
- .orderBy("eventTime.start");
439
-
440
- const snapshot = await eventsRef.get();
441
-
442
- // Post-filter to ensure events actually overlap with our query range
443
- // An event overlaps if: eventTime.start < queryEnd AND eventTime.end > queryStart
444
- const events = snapshot.docs
445
- .map((doc) => ({
446
- ...doc.data(),
447
- id: doc.id,
448
- }))
449
- .filter((event: any) => {
450
- // Event overlaps if it ends after our start time
451
- const overlaps = event.eventTime.end.toMillis() > start.toMillis();
452
- if (!overlaps) {
453
- Logger.debug("[BookingAdmin] Filtered out non-overlapping practitioner event", {
454
- eventId: event.id,
455
- eventStart: event.eventTime.start.toDate().toISOString(),
456
- eventEnd: event.eventTime.end.toDate().toISOString(),
457
- queryStart: start.toDate().toISOString(),
458
- queryEnd: end.toDate().toISOString(),
459
- });
460
- }
461
- return overlaps;
462
- });
463
-
464
- Logger.debug("[BookingAdmin] Retrieved practitioner calendar events", {
465
- practitionerId,
466
- eventsCount: events.length,
467
- eventsTypes: this.summarizeEventTypes(events),
468
- queryStartTime: queryStart.toDate().toISOString(),
469
- });
470
-
471
- return events;
472
- } catch (error) {
473
- const errorMessage =
474
- error instanceof Error ? error.message : String(error);
475
- Logger.error(
476
- "[BookingAdmin] Error fetching practitioner calendar events",
477
- {
478
- errorMessage,
479
- practitionerId,
480
- startTime: start.toDate().toISOString(),
481
- endTime: end.toDate().toISOString(),
482
- stack: error instanceof Error ? error.stack : undefined,
483
- }
484
- );
485
- return [];
486
- }
487
- }
488
-
489
- /**
490
- * Summarizes event types for logging purposes
491
- * @param events Array of calendar events
492
- * @returns Object with counts of each event type
493
- */
494
- private summarizeEventTypes(events: any[]): Record<string, number> {
495
- const typeCounts: Record<string, number> = {};
496
-
497
- events.forEach((event) => {
498
- const eventType = event.eventType || "unknown";
499
- typeCounts[eventType] = (typeCounts[eventType] || 0) + 1;
500
- });
501
-
502
- return typeCounts;
503
- }
504
-
505
- private _generateCalendarProcedureInfo(
506
- procedure: Procedure
507
- ): CalendarProcedureInfo {
508
- return {
509
- name: procedure.name,
510
- description: procedure.description,
511
- duration: procedure.duration, // in minutes
512
- price: procedure.price,
513
- currency: procedure.currency,
514
- };
515
- }
516
-
517
- /**
518
- * Orchestrates the creation of a new appointment, including data aggregation.
519
- * This method is intended to be called from a trusted backend environment (e.g., an Express route handler in a Cloud Function).
520
- *
521
- * @param data - Data required to create the appointment.
522
- * @param authenticatedUserId - The ID of the user making the request (for auditing, and usually is the patientId).
523
- * @returns Promise resolving to an object indicating success, and appointmentId or an error message.
524
- */
525
- async orchestrateAppointmentCreation(
526
- data: OrchestrateAppointmentCreationData,
527
- authenticatedUserId: string
528
- ): Promise<{
529
- success: boolean;
530
- appointmentId?: string;
531
- appointmentData?: Appointment;
532
- calendarEventId?: string;
533
- error?: string;
534
- }> {
535
- console.log(
536
- `[BookingAdmin] Orchestrating appointment creation for patient ${data.patientId} by user ${authenticatedUserId}`
537
- );
538
- const batch = this.db.batch();
539
- const adminTsNow = admin.firestore.Timestamp.now();
540
- const serverTimestampValue = admin.firestore.FieldValue.serverTimestamp();
541
-
542
- try {
543
- // --- 1. Input Validation ---
544
- if (
545
- !data.patientId ||
546
- !data.procedureId ||
547
- !data.appointmentStartTime ||
548
- !data.appointmentEndTime
549
- ) {
550
- return {
551
- success: false,
552
- error:
553
- "Missing required fields: patientId, procedureId, appointmentStartTime, or appointmentEndTime.",
554
- };
555
- }
556
- if (
557
- data.appointmentEndTime.toMillis() <=
558
- data.appointmentStartTime.toMillis()
559
- ) {
560
- return {
561
- success: false,
562
- error: "Appointment end time must be after start time.",
563
- };
564
- }
565
- if (authenticatedUserId !== data.patientId) {
566
- console.warn(
567
- `[BookingAdmin] Authenticated user ${authenticatedUserId} is booking for a different patient ${data.patientId}. Review authorization if this is not intended.`
568
- );
569
- }
570
-
571
- // --- 2. Fetch Core Procedure Data ---
572
- const procedureRef = this.db
573
- .collection(PROCEDURES_COLLECTION)
574
- .doc(data.procedureId);
575
- const procedureDoc = await procedureRef.get();
576
- if (!procedureDoc.exists) {
577
- return {
578
- success: false,
579
- error: `Procedure ${data.procedureId} not found.`,
580
- };
581
- }
582
- const procedure = procedureDoc.data() as Procedure;
583
-
584
- // --- 3. Fetch Clinic and then other Primary Documents ---
585
- // Fetch clinic first to get its clinicGroupId
586
- const clinicRef = this.db
587
- .collection(CLINICS_COLLECTION)
588
- .doc(procedure.clinicBranchId);
589
- const clinicSnap = await clinicRef.get(); // Await here directly
590
- if (!clinicSnap.exists) {
591
- return {
592
- success: false,
593
- error: `Clinic ${procedure.clinicBranchId} not found.`,
594
- };
595
- }
596
- const clinicData = clinicSnap.data() as Clinic; // Now clinicData is available
597
-
598
- // Define other refs using clinicData for clinicGroupRef
599
- const practitionerRef = this.db
600
- .collection(PRACTITIONERS_COLLECTION)
601
- .doc(procedure.practitionerId);
602
- const patientProfileRef = this.db
603
- .collection(PATIENTS_COLLECTION)
604
- .doc(data.patientId);
605
- const patientSensitiveRef = this.db
606
- .collection(PATIENTS_COLLECTION)
607
- .doc(data.patientId)
608
- .collection(PATIENT_SENSITIVE_INFO_COLLECTION)
609
- .doc(data.patientId);
610
- const clinicGroupRef = this.db
611
- .collection(CLINIC_GROUPS_COLLECTION)
612
- .doc(clinicData.clinicGroupId); // Use clinicData here
613
-
614
- const [
615
- practitionerSnap,
616
- patientProfileSnap,
617
- patientSensitiveSnap,
618
- clinicGroupSnap,
619
- ] = await Promise.all([
620
- // clinicRef.get() is already done via clinicSnap
621
- practitionerRef.get(),
622
- patientProfileRef.get(),
623
- patientSensitiveRef.get(),
624
- clinicGroupRef.get(), // Fetch the defined clinicGroupRef
625
- ]);
626
-
627
- if (!practitionerSnap.exists)
628
- return {
629
- success: false,
630
- error: `Practitioner ${procedure.practitionerId} not found.`,
631
- };
632
- if (!patientProfileSnap.exists)
633
- return {
634
- success: false,
635
- error: `PatientProfile ${data.patientId} not found.`,
636
- };
637
- if (!clinicGroupSnap.exists)
638
- return {
639
- success: false,
640
- error: `ClinicGroup for clinic ${procedure.clinicBranchId} not found.`,
641
- };
642
-
643
- const practitionerData = practitionerSnap.data() as Practitioner;
644
- const patientProfileData = patientProfileSnap.data() as PatientProfile;
645
- const patientSensitiveData = patientSensitiveSnap.exists
646
- ? (patientSensitiveSnap.data() as PatientSensitiveInfo)
647
- : undefined;
648
- const clinicGroupData = clinicGroupSnap.data() as ClinicGroup;
649
-
650
- // --- 4. Determine initialStatus (based on clinic settings) ---
651
- const autoConfirm = clinicGroupData.autoConfirmAppointments || false;
652
- const initialAppointmentStatus = autoConfirm
653
- ? AppointmentStatus.CONFIRMED
654
- : AppointmentStatus.PENDING;
655
- const initialCalendarEventStatus = autoConfirm
656
- ? CalendarEventStatus.CONFIRMED
657
- : CalendarEventStatus.PENDING;
658
-
659
- // --- 5. Aggregate Information (Snapshots) ---
660
- const clinicInfo: ClinicInfo = {
661
- id: clinicSnap.id,
662
- name: clinicData.name,
663
- featuredPhoto:
664
- (typeof clinicData.coverPhoto === "string"
665
- ? clinicData.coverPhoto
666
- : "") ||
667
- (typeof clinicData.logo === "string" ? clinicData.logo : "") ||
668
- "",
669
- description: clinicData.description,
670
- location: clinicData.location,
671
- contactInfo: clinicData.contactInfo,
672
- };
673
- const practitionerInfo: PractitionerProfileInfo = {
674
- id: practitionerSnap.id,
675
- practitionerPhoto:
676
- typeof practitionerData.basicInfo.profileImageUrl === "string"
677
- ? practitionerData.basicInfo.profileImageUrl
678
- : null,
679
- name: `${practitionerData.basicInfo.firstName} ${practitionerData.basicInfo.lastName}`,
680
- email: practitionerData.basicInfo.email,
681
- phone: practitionerData.basicInfo.phoneNumber || null,
682
- certification: practitionerData.certification,
683
- };
684
- const patientInfo: PatientProfileInfo = {
685
- id: patientProfileSnap.id,
686
- fullName:
687
- `${patientSensitiveData?.firstName || ""} ${
688
- patientSensitiveData?.lastName || ""
689
- }`.trim() || patientProfileData.displayName,
690
- email: patientSensitiveData?.email || "",
691
- phone:
692
- patientSensitiveData?.phoneNumber ||
693
- patientProfileData.phoneNumber ||
694
- null,
695
- dateOfBirth:
696
- patientSensitiveData?.dateOfBirth ||
697
- patientProfileData.dateOfBirth ||
698
- admin.firestore.Timestamp.now(),
699
- gender: patientSensitiveData?.gender || Gender.OTHER,
700
- };
701
- // const procedureCategory = procedure.category as Category;
702
- // const procedureSubCategory = procedure.subcategory as Subcategory;
703
- // const procedureTechnology = procedure.technology as Technology;
704
- // const procedureProduct = procedure.product as Product;
705
-
706
- // const procedureExtendedInfo: ProcedureExtendedInfo = {
707
- // id: procedure.id,
708
- // name: procedure.name,
709
- // description: procedure.description,
710
- // cost: procedure.price,
711
- // duration: procedure.duration,
712
- // procedureFamily: procedure.family,
713
- // procedureCategoryId: procedureCategory?.id || "",
714
- // procedureCategoryName: procedureCategory?.name || "",
715
- // procedureSubCategoryId: procedureSubCategory?.id || "",
716
- // procedureSubCategoryName: procedureSubCategory?.name || "",
717
- // procedureTechnologyId: procedureTechnology?.id || "",
718
- // procedureTechnologyName: procedureTechnology?.name || "",
719
- // procedureProductBrandId: procedureProduct.brandId || "",
720
- // procedureProductBrandName: procedureProduct.brandName || "",
721
- // procedureProductId: procedureProduct.id || "",
722
- // procedureProductName: procedureProduct.name || "",
723
- // };
724
-
725
- // // --- 6. Determine pendingUserFormsIds and linkedFormIds ---
726
- // let pendingUserFormsIds: string[] = [];
727
- // let linkedFormIds: string[] = [];
728
- // if (
729
- // procedure.documentationTemplates &&
730
- // Array.isArray(procedure.documentationTemplates)
731
- // ) {
732
- // pendingUserFormsIds = procedure.documentationTemplates
733
- // .filter(
734
- // (template: TechnologyDocumentationTemplate) =>
735
- // template.isUserForm && template.isRequired
736
- // )
737
- // .map(
738
- // (template: TechnologyDocumentationTemplate) => template.templateId
739
- // );
740
- // linkedFormIds = procedure.documentationTemplates.map(
741
- // (template: TechnologyDocumentationTemplate) => template.templateId
742
- // );
743
- // }
744
-
745
- // --- 7. Construct New Appointment Object ---
746
- const newAppointmentId = this.db
747
- .collection(APPOINTMENTS_COLLECTION)
748
- .doc().id;
749
-
750
- const eventTimeForCalendarEvents: CalendarEventTime = {
751
- start: data.appointmentStartTime as any,
752
- end: data.appointmentEndTime as any,
753
- };
754
-
755
- // Practitioner Calendar Event
756
- const practitionerCalendarEventId = this.db
757
- .collection(PRACTITIONERS_COLLECTION)
758
- .doc(practitionerData.id)
759
- .collection(CALENDAR_COLLECTION)
760
- .doc().id;
761
- const practitionerCalendarEventData: CalendarEvent = {
762
- id: practitionerCalendarEventId,
763
- appointmentId: newAppointmentId,
764
- clinicBranchId: clinicData.id,
765
- clinicBranchInfo: clinicInfo,
766
- practitionerProfileId: practitionerData.id,
767
- practitionerProfileInfo: practitionerInfo,
768
- patientProfileId: patientProfileData.id,
769
- patientProfileInfo: patientInfo,
770
- procedureId: procedure.id,
771
- procedureInfo: this._generateCalendarProcedureInfo(procedure),
772
- eventName: `Appointment: ${procedure.name} with ${patientInfo.fullName}`,
773
- eventLocation: clinicData.location,
774
- eventTime: eventTimeForCalendarEvents,
775
- description: procedure.description || "",
776
- status: initialCalendarEventStatus,
777
- syncStatus: CalendarSyncStatus.INTERNAL,
778
- eventType: CalendarEventType.APPOINTMENT,
779
- createdAt: serverTimestampValue as any,
780
- updatedAt: serverTimestampValue as any,
781
- };
782
- batch.set(
783
- this.db
784
- .collection(PRACTITIONERS_COLLECTION)
785
- .doc(practitionerData.id)
786
- .collection(CALENDAR_COLLECTION)
787
- .doc(practitionerCalendarEventId),
788
- practitionerCalendarEventData
789
- );
790
-
791
- // Patient Calendar Event
792
- // Use same ID as practitionerCalendarEventId
793
- const patientCalendarEventData: CalendarEvent = {
794
- id: practitionerCalendarEventId,
795
- appointmentId: newAppointmentId,
796
- clinicBranchId: clinicData.id,
797
- clinicBranchInfo: clinicInfo,
798
- practitionerProfileId: practitionerData.id,
799
- practitionerProfileInfo: practitionerInfo,
800
- procedureId: procedure.id,
801
- procedureInfo: this._generateCalendarProcedureInfo(procedure),
802
- eventName: `Appointment: ${procedure.name} at ${clinicData.name}`,
803
- eventLocation: clinicData.location,
804
- eventTime: eventTimeForCalendarEvents,
805
- description: data.patientNotes || "",
806
- status: initialCalendarEventStatus,
807
- syncStatus: CalendarSyncStatus.INTERNAL,
808
- eventType: CalendarEventType.APPOINTMENT,
809
- createdAt: serverTimestampValue as any,
810
- updatedAt: serverTimestampValue as any,
811
- };
812
- batch.set(
813
- this.db
814
- .collection(PATIENTS_COLLECTION)
815
- .doc(patientProfileData.id)
816
- .collection(CALENDAR_COLLECTION)
817
- .doc(practitionerCalendarEventId),
818
- patientCalendarEventData
819
- );
820
-
821
- // Clinic Calendar Event
822
- // Use same ID as practitionerCalendarEventId
823
- const clinicCalendarEventData: CalendarEvent = {
824
- id: practitionerCalendarEventId,
825
- appointmentId: newAppointmentId,
826
- clinicBranchId: clinicData.id,
827
- clinicBranchInfo: clinicInfo,
828
- practitionerProfileId: practitionerData.id,
829
- practitionerProfileInfo: practitionerInfo,
830
- patientProfileId: patientProfileData.id,
831
- patientProfileInfo: patientInfo,
832
- procedureId: procedure.id,
833
- procedureInfo: this._generateCalendarProcedureInfo(procedure),
834
- eventName: `Appointment: ${procedure.name} for ${patientInfo.fullName} with ${practitionerInfo.name}`,
835
- eventLocation: clinicData.location,
836
- eventTime: eventTimeForCalendarEvents,
837
- description: data.patientNotes || "",
838
- status: initialCalendarEventStatus,
839
- syncStatus: CalendarSyncStatus.INTERNAL,
840
- eventType: CalendarEventType.APPOINTMENT,
841
- createdAt: serverTimestampValue as any,
842
- updatedAt: serverTimestampValue as any,
843
- };
844
- batch.set(
845
- this.db
846
- .collection(CLINICS_COLLECTION)
847
- .doc(clinicData.id)
848
- .collection(CALENDAR_COLLECTION)
849
- .doc(practitionerCalendarEventId),
850
- clinicCalendarEventData
851
- );
852
-
853
- // --- Initialize Pending/Draft Filled Documents and get form IDs ---
854
- let initializedFormsInfo: LinkedFormInfo[] = [];
855
- let pendingUserFormTemplateIds: string[] = [];
856
- let allLinkedFormTemplateIds: string[] = [];
857
-
858
- if (
859
- procedure.documentationTemplates &&
860
- Array.isArray(procedure.documentationTemplates) &&
861
- procedure.documentationTemplates.length > 0
862
- ) {
863
- const formInitResult =
864
- await this.documentManagerAdmin.batchInitializeAppointmentFormsFromTechnologyTemplates(
865
- batch,
866
- newAppointmentId,
867
- procedure.id, // Pass the actual procedureId for the forms
868
- procedure.documentationTemplates,
869
- data.patientId,
870
- procedure.practitionerId,
871
- procedure.clinicBranchId,
872
- adminTsNow.toMillis()
873
- );
874
- initializedFormsInfo = formInitResult.initializedFormsInfo;
875
- pendingUserFormTemplateIds = formInitResult.pendingUserFormsIds;
876
- allLinkedFormTemplateIds = formInitResult.allLinkedTemplateIds;
877
- }
878
-
879
- // --- Generate appointment products from procedure ---
880
- const appointmentProducts = this._generateAppointmentProductsFromProcedure(procedure);
881
-
882
- // --- Construct Appointment Object ---
883
- const newAppointmentData: Appointment = {
884
- id: newAppointmentId,
885
- calendarEventId: practitionerCalendarEventId,
886
- clinicBranchId: procedure.clinicBranchId,
887
- clinicInfo,
888
- clinic_tz: clinicData.location.tz || "UTC",
889
- practitionerId: procedure.practitionerId,
890
- practitionerInfo,
891
- patientId: data.patientId,
892
- patientInfo,
893
- procedureId: data.procedureId,
894
- procedureInfo: this._generateProcedureSummaryInfo(
895
- procedure,
896
- clinicData,
897
- practitionerData
898
- ),
899
- procedureExtendedInfo: this._generateProcedureExtendedInfo(procedure),
900
- status: initialAppointmentStatus,
901
- bookingTime: adminTsNow as any,
902
- confirmationTime:
903
- initialAppointmentStatus === AppointmentStatus.CONFIRMED
904
- ? (adminTsNow as any)
905
- : null,
906
- appointmentStartTime: data.appointmentStartTime as any,
907
- appointmentEndTime: data.appointmentEndTime as any,
908
- cost: procedure.price,
909
- currency: procedure.currency,
910
- paymentStatus:
911
- procedure.price > 0
912
- ? PaymentStatus.UNPAID
913
- : PaymentStatus.NOT_APPLICABLE,
914
- patientNotes: data.patientNotes || null,
915
- blockingConditions: procedure.blockingConditions || [],
916
- contraindications: (procedure as any).contraindications || [],
917
- preProcedureRequirements: procedure.preRequirements || [],
918
- postProcedureRequirements: procedure.postRequirements || [],
919
- pendingUserFormsIds: pendingUserFormTemplateIds,
920
- linkedFormIds: allLinkedFormTemplateIds,
921
- completedPreRequirements: [],
922
- completedPostRequirements: [],
923
- linkedForms: initializedFormsInfo,
924
- media: [],
925
- reviewInfo: null,
926
- metadata: {
927
- selectedZones: null,
928
- zonePhotos: null,
929
- zonesData: null,
930
- appointmentProducts: appointmentProducts,
931
- extendedProcedures: [],
932
- recommendedProcedures: [],
933
- finalbilling: null,
934
- finalizationNotes: null,
935
- },
936
- finalizedDetails: {
937
- by: "",
938
- at: adminTsNow as any,
939
- notes: "",
940
- },
941
- internalNotes: null,
942
- cancellationReason: null,
943
- cancellationTime: null,
944
- canceledBy: undefined,
945
- rescheduleTime: null,
946
- procedureActualStartTime: null,
947
- actualDurationMinutes: undefined,
948
- isRecurring: false,
949
- recurringAppointmentId: null,
950
- isArchived: false,
951
- createdAt: adminTsNow as any,
952
- updatedAt: adminTsNow as any,
953
- };
954
-
955
- batch.set(
956
- this.db.collection(APPOINTMENTS_COLLECTION).doc(newAppointmentId),
957
- newAppointmentData
958
- );
959
-
960
- // Commit Batch
961
- await batch.commit();
962
-
963
- console.log(
964
- `[BookingAdmin] Appointment ${newAppointmentId} and associated calendar events created successfully.`
965
- );
966
- return {
967
- success: true,
968
- appointmentId: newAppointmentId,
969
- appointmentData: newAppointmentData,
970
- calendarEventId: practitionerCalendarEventId,
971
- };
972
- } catch (error) {
973
- console.error(
974
- "[BookingAdmin] Critical error in orchestrateAppointmentCreation:",
975
- error
976
- );
977
- const errorMessage =
978
- error instanceof Error
979
- ? error.message
980
- : "Unknown server error during appointment creation.";
981
- return { success: false, error: errorMessage };
982
- }
983
- }
984
-
985
- private _generateProcedureSummaryInfo(
986
- procedure: Procedure,
987
- clinicData: Clinic,
988
- practitionerData: Practitioner
989
- ): ProcedureSummaryInfo {
990
- const procedureCategory = procedure.category as Category;
991
- const procedureSubCategory = procedure.subcategory as Subcategory;
992
- const procedureTechnology = procedure.technology as Technology;
993
- const procedureProduct = procedure.product as Product;
994
- return {
995
- id: procedure.id,
996
- name: procedure.name,
997
- description: procedure.description,
998
- family: procedure.family,
999
- categoryName: procedureCategory?.name || "",
1000
- subcategoryName: procedureSubCategory?.name || "",
1001
- technologyName: procedureTechnology?.name || "",
1002
- price: procedure.price,
1003
- pricingMeasure: procedure.pricingMeasure,
1004
- currency: procedure.currency,
1005
- duration: procedure.duration,
1006
- clinicId: procedure.clinicBranchId,
1007
- clinicName: clinicData.name,
1008
- practitionerId: procedure.practitionerId,
1009
- practitionerName: `${practitionerData.basicInfo.firstName} ${practitionerData.basicInfo.lastName}`,
1010
- photo:
1011
- (procedureTechnology as any)?.photos?.[0]?.url ||
1012
- (procedureProduct as any)?.photos?.[0]?.url ||
1013
- "",
1014
- brandName: (procedureProduct as any)?.brand?.name || "",
1015
- productName: procedureProduct?.name || "",
1016
- };
1017
- }
1018
-
1019
- private _generateProcedureExtendedInfo(
1020
- procedure: Procedure
1021
- ): ProcedureExtendedInfo {
1022
- const procedureCategory = procedure.category as Category;
1023
- const procedureSubCategory = procedure.subcategory as Subcategory;
1024
- const procedureTechnology = procedure.technology as Technology;
1025
- const procedureProduct = procedure.product as Product;
1026
- const productsMetadata = procedure.productsMetadata || [];
1027
-
1028
- return {
1029
- id: procedure.id,
1030
- name: procedure.name,
1031
- description: procedure.description,
1032
- cost: procedure.price,
1033
- duration: procedure.duration,
1034
- procedureFamily: procedure.family,
1035
- procedureCategoryId: procedureCategory?.id || "",
1036
- procedureCategoryName: procedureCategory?.name || "",
1037
- procedureSubCategoryId: procedureSubCategory?.id || "",
1038
- procedureSubCategoryName: procedureSubCategory?.name || "",
1039
- procedureTechnologyId: procedureTechnology?.id || "",
1040
- procedureTechnologyName: procedureTechnology?.name || "",
1041
- procedureProductBrandId: procedureProduct?.brandId || "",
1042
- procedureProductBrandName: procedureProduct?.brandName || "",
1043
- procedureProducts: productsMetadata
1044
- .filter((pp: any) => pp && pp.product) // Safety check for product-free procedures
1045
- .map((pp: any) => ({
1046
- productId: pp.product.id,
1047
- productName: pp.product.name,
1048
- brandId: pp.product.brandId,
1049
- brandName: pp.product.brandName,
1050
- })),
1051
- };
1052
- }
1053
-
1054
- private _generateAppointmentProductsFromProcedure(procedure: Procedure): any[] {
1055
- const productsMetadata = procedure.productsMetadata || [];
1056
-
1057
- return productsMetadata
1058
- .filter((pp: any) => pp && pp.product) // Safety check for product-free procedures
1059
- .map((pp: any) => {
1060
- const product = pp.product;
1061
- return {
1062
- productId: product.id,
1063
- productName: product.name,
1064
- brandId: product.brandId,
1065
- brandName: product.brandName,
1066
- procedureId: procedure.id,
1067
- price: pp.price,
1068
- currency: pp.currency,
1069
- unitOfMeasurement: pp.pricingMeasure,
1070
- };
1071
- });
1072
- }
1073
- }
1
+ import * as admin from "firebase-admin";
2
+ import { Timestamp as FirebaseClientTimestamp } from "@firebase/firestore";
3
+ import {
4
+ BookingAvailabilityCalculator,
5
+ BookingAvailabilityRequest,
6
+ BookingAvailabilityResponse,
7
+ AvailableSlot,
8
+ } from "./";
9
+ import { CalendarEventStatus, CalendarEventType } from "../../types/calendar";
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 {
41
+ DocumentTemplate as AppDocumentTemplate,
42
+ FilledDocument,
43
+ FilledDocumentStatus,
44
+ USER_FORMS_SUBCOLLECTION,
45
+ DOCTOR_FORMS_SUBCOLLECTION,
46
+ } from "../../types/documentation-templates";
47
+ import { TechnologyDocumentationTemplate } from "../../backoffice/types/technology.types";
48
+ import {
49
+ ClinicInfo,
50
+ PractitionerProfileInfo,
51
+ PatientProfileInfo,
52
+ } from "../../types/profile";
53
+ import { Category } from "../../backoffice/types/category.types";
54
+ import { Subcategory } from "../../backoffice/types/subcategory.types";
55
+ import { Technology } from "../../backoffice/types/technology.types";
56
+ import { Product } from "../../backoffice/types/product.types";
57
+ import {
58
+ CalendarEvent,
59
+ CalendarEventTime,
60
+ CalendarSyncStatus,
61
+ ProcedureInfo as CalendarProcedureInfo,
62
+ CALENDAR_COLLECTION,
63
+ } from "../../types/calendar";
64
+ import { DocumentManagerAdminService } from "../documentation-templates/document-manager.admin";
65
+ import { LinkedFormInfo } from "../../types/appointment";
66
+ import { TimestampUtils } from "../../utils/TimestampUtils";
67
+ import { Logger } from "../logger";
68
+ import {
69
+ Resource,
70
+ ResourceInstance,
71
+ ResourceCalendarEvent,
72
+ ResourceBookingInfo,
73
+ ResourceStatus,
74
+ RESOURCES_COLLECTION,
75
+ RESOURCE_INSTANCES_SUBCOLLECTION,
76
+ RESOURCE_CALENDAR_SUBCOLLECTION,
77
+ } from "../../types/resource";
78
+
79
+ /**
80
+ * Interface for the data required by orchestrateAppointmentCreation
81
+ */
82
+ export interface OrchestrateAppointmentCreationData {
83
+ patientId: string;
84
+ procedureId: string;
85
+ appointmentStartTime: admin.firestore.Timestamp;
86
+ appointmentEndTime: admin.firestore.Timestamp;
87
+ patientNotes?: string | null;
88
+ }
89
+
90
+ /**
91
+ * Admin service for handling booking-related operations.
92
+ * This is the cloud-based implementation that will be used in Cloud Functions.
93
+ */
94
+ export class BookingAdmin {
95
+ private db: admin.firestore.Firestore;
96
+ private documentManagerAdmin: DocumentManagerAdminService;
97
+
98
+ /**
99
+ * Creates a new BookingAdmin instance
100
+ * @param firestore - Firestore instance provided by the caller
101
+ */
102
+ constructor(firestore?: admin.firestore.Firestore) {
103
+ this.db = firestore || admin.firestore();
104
+ this.documentManagerAdmin = new DocumentManagerAdminService(this.db);
105
+ }
106
+
107
+ /**
108
+ * Gets available booking time slots for a specific clinic, practitioner, and procedure
109
+ *
110
+ * @param clinicId - ID of the clinic
111
+ * @param practitionerId - ID of the practitioner
112
+ * @param procedureId - ID of the procedure
113
+ * @param timeframe - Time range to check for availability
114
+ * @returns Promise resolving to an array of available booking slots
115
+ */
116
+ async getAvailableBookingSlots(
117
+ clinicId: string,
118
+ practitionerId: string,
119
+ procedureId: string,
120
+ timeframe: {
121
+ start: Date | admin.firestore.Timestamp;
122
+ end: Date | admin.firestore.Timestamp;
123
+ }
124
+ ): Promise<{ availableSlots: { start: admin.firestore.Timestamp }[] }> {
125
+ try {
126
+ Logger.info("[BookingAdmin] Starting availability calculation", {
127
+ clinicId,
128
+ practitionerId,
129
+ procedureId,
130
+ timeframeStart:
131
+ timeframe.start instanceof Date
132
+ ? timeframe.start.toISOString()
133
+ : timeframe.start.toDate().toISOString(),
134
+ timeframeEnd:
135
+ timeframe.end instanceof Date
136
+ ? timeframe.end.toISOString()
137
+ : timeframe.end.toDate().toISOString(),
138
+ });
139
+
140
+ // Convert timeframe dates to Firestore Timestamps if needed
141
+ const start =
142
+ timeframe.start instanceof Date
143
+ ? admin.firestore.Timestamp.fromDate(timeframe.start)
144
+ : timeframe.start;
145
+
146
+ const end =
147
+ timeframe.end instanceof Date
148
+ ? admin.firestore.Timestamp.fromDate(timeframe.end)
149
+ : timeframe.end;
150
+
151
+ // 1. Fetch clinic data
152
+ Logger.debug("[BookingAdmin] Fetching clinic data", { clinicId });
153
+ const clinicDoc = await this.db.collection("clinics").doc(clinicId).get();
154
+ if (!clinicDoc.exists) {
155
+ Logger.error("[BookingAdmin] Clinic not found", { clinicId });
156
+ throw new Error(`Clinic ${clinicId} not found`);
157
+ }
158
+ const clinic = clinicDoc.data() as unknown as Clinic;
159
+ Logger.debug("[BookingAdmin] Retrieved clinic data", {
160
+ clinicName: clinic.name,
161
+ clinicHasWorkingHours: !!clinic.workingHours,
162
+ });
163
+
164
+ // 2. Fetch practitioner data
165
+ Logger.debug("[BookingAdmin] Fetching practitioner data", {
166
+ practitionerId,
167
+ });
168
+ const practitionerDoc = await this.db
169
+ .collection("practitioners")
170
+ .doc(practitionerId)
171
+ .get();
172
+ if (!practitionerDoc.exists) {
173
+ Logger.error("[BookingAdmin] Practitioner not found", {
174
+ practitionerId,
175
+ });
176
+ throw new Error(`Practitioner ${practitionerId} not found`);
177
+ }
178
+ const practitioner = practitionerDoc.data() as unknown as Practitioner;
179
+ Logger.debug("[BookingAdmin] Retrieved practitioner data", {
180
+ practitionerName: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
181
+ pracWorkingHoursCount: practitioner.clinicWorkingHours?.length || 0,
182
+ });
183
+
184
+ // 3. Fetch procedure data
185
+ Logger.debug("[BookingAdmin] Fetching procedure data", { procedureId });
186
+ const procedureDoc = await this.db
187
+ .collection("procedures")
188
+ .doc(procedureId)
189
+ .get();
190
+ if (!procedureDoc.exists) {
191
+ Logger.error("[BookingAdmin] Procedure not found", { procedureId });
192
+ throw new Error(`Procedure ${procedureId} not found`);
193
+ }
194
+ const procedure = procedureDoc.data() as unknown as Procedure;
195
+ Logger.debug("[BookingAdmin] Retrieved procedure data", {
196
+ procedureName: procedure.name,
197
+ procedureDuration: procedure.duration,
198
+ });
199
+
200
+ // 4. Fetch clinic calendar events
201
+ Logger.debug("[BookingAdmin] Fetching clinic calendar events", {
202
+ clinicId,
203
+ startTime: start.toDate().toISOString(),
204
+ endTime: end.toDate().toISOString(),
205
+ });
206
+ const clinicCalendarEvents = await this.getClinicCalendarEvents(
207
+ clinicId,
208
+ start,
209
+ end
210
+ );
211
+ Logger.debug("[BookingAdmin] Retrieved clinic calendar events", {
212
+ count: clinicCalendarEvents.length,
213
+ });
214
+
215
+ // 5. Fetch practitioner calendar events
216
+ Logger.debug("[BookingAdmin] Fetching practitioner calendar events", {
217
+ practitionerId,
218
+ startTime: start.toDate().toISOString(),
219
+ endTime: end.toDate().toISOString(),
220
+ });
221
+ const practitionerCalendarEvents =
222
+ await this.getPractitionerCalendarEvents(practitionerId, start, end);
223
+ Logger.debug("[BookingAdmin] Retrieved practitioner calendar events", {
224
+ count: practitionerCalendarEvents.length,
225
+ });
226
+
227
+ // 6. Fetch resource calendar events (if procedure requires resources)
228
+ let resourceCalendarEventsMap:
229
+ | BookingAvailabilityRequest["resourceCalendarEventsMap"]
230
+ | undefined;
231
+ if (
232
+ procedure.resourceRequirements &&
233
+ procedure.resourceRequirements.length > 0
234
+ ) {
235
+ Logger.debug(
236
+ "[BookingAdmin] Procedure has resource requirements, fetching resource data",
237
+ {
238
+ resourceRequirementCount: procedure.resourceRequirements.length,
239
+ resourceIds: procedure.resourceRequirements.map(
240
+ (r) => r.resourceId
241
+ ),
242
+ }
243
+ );
244
+
245
+ resourceCalendarEventsMap = {};
246
+
247
+ for (const requirement of procedure.resourceRequirements) {
248
+ // Fetch resource document
249
+ const resourceDoc = await this.db
250
+ .collection(CLINICS_COLLECTION)
251
+ .doc(clinicId)
252
+ .collection(RESOURCES_COLLECTION)
253
+ .doc(requirement.resourceId)
254
+ .get();
255
+
256
+ if (!resourceDoc.exists) {
257
+ Logger.warn(
258
+ "[BookingAdmin] Required resource not found, skipping",
259
+ {
260
+ resourceId: requirement.resourceId,
261
+ resourceName: requirement.resourceName,
262
+ }
263
+ );
264
+ continue;
265
+ }
266
+
267
+ const resource = resourceDoc.data() as Resource;
268
+ if (resource.status !== ResourceStatus.ACTIVE) {
269
+ Logger.warn(
270
+ "[BookingAdmin] Required resource is not active, skipping",
271
+ {
272
+ resourceId: requirement.resourceId,
273
+ resourceStatus: resource.status,
274
+ }
275
+ );
276
+ continue;
277
+ }
278
+
279
+ // Fetch all active instances
280
+ const instancesSnapshot = await this.db
281
+ .collection(CLINICS_COLLECTION)
282
+ .doc(clinicId)
283
+ .collection(RESOURCES_COLLECTION)
284
+ .doc(requirement.resourceId)
285
+ .collection(RESOURCE_INSTANCES_SUBCOLLECTION)
286
+ .where("status", "==", ResourceStatus.ACTIVE)
287
+ .get();
288
+
289
+ const instanceEvents: Record<string, ResourceCalendarEvent[]> = {};
290
+
291
+ for (const instanceDoc of instancesSnapshot.docs) {
292
+ const instanceId = instanceDoc.id;
293
+
294
+ // Fetch calendar events for this instance in the timeframe
295
+ const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
296
+ const queryStart = admin.firestore.Timestamp.fromMillis(
297
+ start.toMillis() - MAX_EVENT_DURATION_MS
298
+ );
299
+
300
+ const eventsSnapshot = await this.db
301
+ .collection(CLINICS_COLLECTION)
302
+ .doc(clinicId)
303
+ .collection(RESOURCES_COLLECTION)
304
+ .doc(requirement.resourceId)
305
+ .collection(RESOURCE_INSTANCES_SUBCOLLECTION)
306
+ .doc(instanceId)
307
+ .collection(RESOURCE_CALENDAR_SUBCOLLECTION)
308
+ .where("eventTime.start", ">=", queryStart)
309
+ .where("eventTime.start", "<=", end)
310
+ .orderBy("eventTime.start")
311
+ .get();
312
+
313
+ // Post-filter for overlapping events and convert timestamps
314
+ const events = eventsSnapshot.docs
315
+ .map((doc) => ({ ...doc.data(), id: doc.id } as any))
316
+ .filter(
317
+ (event: any) =>
318
+ event.eventTime.end.toMillis() > start.toMillis()
319
+ );
320
+
321
+ // Convert admin timestamps to client timestamps
322
+ instanceEvents[instanceId] = this.convertEventsTimestamps(
323
+ events
324
+ ) as unknown as ResourceCalendarEvent[];
325
+ }
326
+
327
+ resourceCalendarEventsMap[requirement.resourceId] = {
328
+ resourceId: requirement.resourceId,
329
+ resourceName: requirement.resourceName,
330
+ quantity: resource.quantity,
331
+ instanceEvents,
332
+ };
333
+
334
+ Logger.debug("[BookingAdmin] Fetched resource calendar data", {
335
+ resourceId: requirement.resourceId,
336
+ resourceName: requirement.resourceName,
337
+ instanceCount: instancesSnapshot.size,
338
+ totalEvents: Object.values(instanceEvents).reduce(
339
+ (sum, events) => sum + events.length,
340
+ 0
341
+ ),
342
+ });
343
+ }
344
+ }
345
+
346
+ // Since we're working with two different Timestamp implementations (admin vs client),
347
+ // we need to convert our timestamps to the client-side format expected by the calculator
348
+ // Create client Timestamp objects from admin Timestamp objects
349
+ const convertedTimeframe = {
350
+ start: this.adminTimestampToClientTimestamp(start),
351
+ end: this.adminTimestampToClientTimestamp(end),
352
+ };
353
+
354
+ // Create the request object for the calculator
355
+ const request: BookingAvailabilityRequest = {
356
+ clinic,
357
+ practitioner,
358
+ procedure,
359
+ timeframe: convertedTimeframe,
360
+ clinicCalendarEvents:
361
+ this.convertEventsTimestamps(clinicCalendarEvents),
362
+ practitionerCalendarEvents: this.convertEventsTimestamps(
363
+ practitionerCalendarEvents
364
+ ),
365
+ tz: clinic.location.tz || "UTC",
366
+ ...(resourceCalendarEventsMap && { resourceCalendarEventsMap }),
367
+ };
368
+
369
+ Logger.info("[BookingAdmin] Calling availability calculator", {
370
+ calculatorInputReady: true,
371
+ timeframeDurationHours: Math.round(
372
+ (end.toMillis() - start.toMillis()) / (1000 * 60 * 60)
373
+ ),
374
+ clinicEventsCount: clinicCalendarEvents.length,
375
+ practitionerEventsCount: practitionerCalendarEvents.length,
376
+ resourceRequirementCount:
377
+ procedure.resourceRequirements?.length || 0,
378
+ hasResourceData: !!resourceCalendarEventsMap,
379
+ });
380
+
381
+ // Use the calculator to compute available slots
382
+ const result = BookingAvailabilityCalculator.calculateSlots(request);
383
+
384
+ // Convert the client Timestamps to admin Timestamps before returning
385
+ const availableSlotsResult = {
386
+ availableSlots: result.availableSlots.map((slot) => ({
387
+ start: admin.firestore.Timestamp.fromMillis(slot.start.toMillis()),
388
+ })),
389
+ };
390
+
391
+ Logger.info(
392
+ "[BookingAdmin] Availability calculation completed successfully",
393
+ {
394
+ availableSlotsCount: availableSlotsResult.availableSlots.length,
395
+ firstSlotTime:
396
+ availableSlotsResult.availableSlots.length > 0
397
+ ? availableSlotsResult.availableSlots[0].start
398
+ .toDate()
399
+ .toISOString()
400
+ : "none",
401
+ lastSlotTime:
402
+ availableSlotsResult.availableSlots.length > 0
403
+ ? availableSlotsResult.availableSlots[
404
+ availableSlotsResult.availableSlots.length - 1
405
+ ].start
406
+ .toDate()
407
+ .toISOString()
408
+ : "none",
409
+ }
410
+ );
411
+
412
+ return availableSlotsResult;
413
+ } catch (error) {
414
+ const errorMessage =
415
+ error instanceof Error ? error.message : String(error);
416
+ Logger.error("[BookingAdmin] Error getting available slots", {
417
+ errorMessage,
418
+ clinicId,
419
+ practitionerId,
420
+ procedureId,
421
+ stack: error instanceof Error ? error.stack : undefined,
422
+ });
423
+ throw error;
424
+ }
425
+ }
426
+
427
+ /**
428
+ * Converts an admin Firestore Timestamp to a client Firestore Timestamp
429
+ */
430
+ private adminTimestampToClientTimestamp(
431
+ timestamp: admin.firestore.Timestamp
432
+ ): FirebaseClientTimestamp {
433
+ // Use TimestampUtils instead of custom implementation
434
+ return TimestampUtils.adminToClient(timestamp) as FirebaseClientTimestamp;
435
+ }
436
+
437
+ /**
438
+ * Converts timestamps in calendar events from admin Firestore Timestamps to client Firestore Timestamps
439
+ */
440
+ private convertEventsTimestamps(events: any[]): any[] {
441
+ return events.map((event) => ({
442
+ ...event,
443
+ eventTime: {
444
+ start: TimestampUtils.adminToClient(
445
+ event.eventTime.start
446
+ ) as FirebaseClientTimestamp,
447
+ end: TimestampUtils.adminToClient(
448
+ event.eventTime.end
449
+ ) as FirebaseClientTimestamp,
450
+ },
451
+ // Convert any other timestamps in the event if needed
452
+ }));
453
+ }
454
+
455
+ /**
456
+ * Fetches clinic calendar events for a specific time range
457
+ *
458
+ * @param clinicId - ID of the clinic
459
+ * @param start - Start time of the range
460
+ * @param end - End time of the range
461
+ * @returns Promise resolving to an array of calendar events
462
+ */
463
+ private async getClinicCalendarEvents(
464
+ clinicId: string,
465
+ start: admin.firestore.Timestamp,
466
+ end: admin.firestore.Timestamp
467
+ ): Promise<any[]> {
468
+ try {
469
+ Logger.debug("[BookingAdmin] Querying clinic calendar events", {
470
+ clinicId,
471
+ startTime: start.toDate().toISOString(),
472
+ endTime: end.toDate().toISOString(),
473
+ });
474
+
475
+ // Increased to 30 days to handle long blocking events (e.g., holidays, extended time off)
476
+ // This ensures we catch blocking events that start before our query range but overlap with it
477
+ const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
478
+ const queryStart = admin.firestore.Timestamp.fromMillis(
479
+ start.toMillis() - MAX_EVENT_DURATION_MS
480
+ );
481
+
482
+ // Query for events that:
483
+ // 1. Start before or during our query range (eventTime.start < end)
484
+ // 2. We'll post-filter to ensure they overlap (eventTime.end > start)
485
+ const eventsRef = this.db
486
+ .collection(`clinics/${clinicId}/calendar`)
487
+ .where("eventTime.start", ">=", queryStart)
488
+ .where("eventTime.start", "<=", end)
489
+ .orderBy("eventTime.start");
490
+
491
+ const snapshot = await eventsRef.get();
492
+
493
+ // Post-filter to ensure events actually overlap with our query range
494
+ // An event overlaps if: eventTime.start < queryEnd AND eventTime.end > queryStart
495
+ const events = snapshot.docs
496
+ .map((doc) => ({
497
+ ...doc.data(),
498
+ id: doc.id,
499
+ }))
500
+ .filter((event: any) => {
501
+ // Event overlaps if it ends after our start time
502
+ const overlaps = event.eventTime.end.toMillis() > start.toMillis();
503
+ if (!overlaps) {
504
+ Logger.debug("[BookingAdmin] Filtered out non-overlapping event", {
505
+ eventId: event.id,
506
+ eventStart: event.eventTime.start.toDate().toISOString(),
507
+ eventEnd: event.eventTime.end.toDate().toISOString(),
508
+ queryStart: start.toDate().toISOString(),
509
+ queryEnd: end.toDate().toISOString(),
510
+ });
511
+ }
512
+ return overlaps;
513
+ });
514
+
515
+ Logger.debug("[BookingAdmin] Retrieved clinic calendar events", {
516
+ clinicId,
517
+ eventsCount: events.length,
518
+ eventsTypes: this.summarizeEventTypes(events),
519
+ queryStartTime: queryStart.toDate().toISOString(),
520
+ });
521
+
522
+ return events;
523
+ } catch (error) {
524
+ const errorMessage =
525
+ error instanceof Error ? error.message : String(error);
526
+ Logger.error("[BookingAdmin] Error fetching clinic calendar events", {
527
+ errorMessage,
528
+ clinicId,
529
+ startTime: start.toDate().toISOString(),
530
+ endTime: end.toDate().toISOString(),
531
+ stack: error instanceof Error ? error.stack : undefined,
532
+ });
533
+ return [];
534
+ }
535
+ }
536
+
537
+ /**
538
+ * Fetches practitioner calendar events for a specific time range
539
+ *
540
+ * @param practitionerId - ID of the practitioner
541
+ * @param start - Start time of the range
542
+ * @param end - End time of the range
543
+ * @returns Promise resolving to an array of calendar events
544
+ */
545
+ private async getPractitionerCalendarEvents(
546
+ practitionerId: string,
547
+ start: admin.firestore.Timestamp,
548
+ end: admin.firestore.Timestamp
549
+ ): Promise<any[]> {
550
+ try {
551
+ Logger.debug("[BookingAdmin] Querying practitioner calendar events", {
552
+ practitionerId,
553
+ startTime: start.toDate().toISOString(),
554
+ endTime: end.toDate().toISOString(),
555
+ });
556
+
557
+ // Increased to 30 days to handle long blocking events (e.g., holidays, extended time off)
558
+ // This ensures we catch blocking events that start before our query range but overlap with it
559
+ const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
560
+ const queryStart = admin.firestore.Timestamp.fromMillis(
561
+ start.toMillis() - MAX_EVENT_DURATION_MS
562
+ );
563
+
564
+ // Query for events that:
565
+ // 1. Start before or during our query range (eventTime.start <= end)
566
+ // 2. We'll post-filter to ensure they overlap (eventTime.end > start)
567
+ const eventsRef = this.db
568
+ .collection(`practitioners/${practitionerId}/calendar`)
569
+ .where("eventTime.start", ">=", queryStart)
570
+ .where("eventTime.start", "<=", end)
571
+ .orderBy("eventTime.start");
572
+
573
+ const snapshot = await eventsRef.get();
574
+
575
+ // Post-filter to ensure events actually overlap with our query range
576
+ // An event overlaps if: eventTime.start < queryEnd AND eventTime.end > queryStart
577
+ const events = snapshot.docs
578
+ .map((doc) => ({
579
+ ...doc.data(),
580
+ id: doc.id,
581
+ }))
582
+ .filter((event: any) => {
583
+ // Event overlaps if it ends after our start time
584
+ const overlaps = event.eventTime.end.toMillis() > start.toMillis();
585
+ if (!overlaps) {
586
+ Logger.debug("[BookingAdmin] Filtered out non-overlapping practitioner event", {
587
+ eventId: event.id,
588
+ eventStart: event.eventTime.start.toDate().toISOString(),
589
+ eventEnd: event.eventTime.end.toDate().toISOString(),
590
+ queryStart: start.toDate().toISOString(),
591
+ queryEnd: end.toDate().toISOString(),
592
+ });
593
+ }
594
+ return overlaps;
595
+ });
596
+
597
+ Logger.debug("[BookingAdmin] Retrieved practitioner calendar events", {
598
+ practitionerId,
599
+ eventsCount: events.length,
600
+ eventsTypes: this.summarizeEventTypes(events),
601
+ queryStartTime: queryStart.toDate().toISOString(),
602
+ });
603
+
604
+ return events;
605
+ } catch (error) {
606
+ const errorMessage =
607
+ error instanceof Error ? error.message : String(error);
608
+ Logger.error(
609
+ "[BookingAdmin] Error fetching practitioner calendar events",
610
+ {
611
+ errorMessage,
612
+ practitionerId,
613
+ startTime: start.toDate().toISOString(),
614
+ endTime: end.toDate().toISOString(),
615
+ stack: error instanceof Error ? error.stack : undefined,
616
+ }
617
+ );
618
+ return [];
619
+ }
620
+ }
621
+
622
+ /**
623
+ * Summarizes event types for logging purposes
624
+ * @param events Array of calendar events
625
+ * @returns Object with counts of each event type
626
+ */
627
+ private summarizeEventTypes(events: any[]): Record<string, number> {
628
+ const typeCounts: Record<string, number> = {};
629
+
630
+ events.forEach((event) => {
631
+ const eventType = event.eventType || "unknown";
632
+ typeCounts[eventType] = (typeCounts[eventType] || 0) + 1;
633
+ });
634
+
635
+ return typeCounts;
636
+ }
637
+
638
+ private _generateCalendarProcedureInfo(
639
+ procedure: Procedure
640
+ ): CalendarProcedureInfo {
641
+ return {
642
+ name: procedure.name,
643
+ description: procedure.description,
644
+ duration: procedure.duration, // in minutes
645
+ price: procedure.price,
646
+ currency: procedure.currency,
647
+ };
648
+ }
649
+
650
+ /**
651
+ * Orchestrates the creation of a new appointment, including data aggregation.
652
+ * This method is intended to be called from a trusted backend environment (e.g., an Express route handler in a Cloud Function).
653
+ *
654
+ * @param data - Data required to create the appointment.
655
+ * @param authenticatedUserId - The ID of the user making the request (for auditing, and usually is the patientId).
656
+ * @returns Promise resolving to an object indicating success, and appointmentId or an error message.
657
+ */
658
+ async orchestrateAppointmentCreation(
659
+ data: OrchestrateAppointmentCreationData,
660
+ authenticatedUserId: string
661
+ ): Promise<{
662
+ success: boolean;
663
+ appointmentId?: string;
664
+ appointmentData?: Appointment;
665
+ calendarEventId?: string;
666
+ error?: string;
667
+ }> {
668
+ console.log(
669
+ `[BookingAdmin] Orchestrating appointment creation for patient ${data.patientId} by user ${authenticatedUserId}`
670
+ );
671
+ const batch = this.db.batch();
672
+ const adminTsNow = admin.firestore.Timestamp.now();
673
+ const serverTimestampValue = admin.firestore.FieldValue.serverTimestamp();
674
+
675
+ try {
676
+ // --- 1. Input Validation ---
677
+ if (
678
+ !data.patientId ||
679
+ !data.procedureId ||
680
+ !data.appointmentStartTime ||
681
+ !data.appointmentEndTime
682
+ ) {
683
+ return {
684
+ success: false,
685
+ error:
686
+ "Missing required fields: patientId, procedureId, appointmentStartTime, or appointmentEndTime.",
687
+ };
688
+ }
689
+ if (
690
+ data.appointmentEndTime.toMillis() <=
691
+ data.appointmentStartTime.toMillis()
692
+ ) {
693
+ return {
694
+ success: false,
695
+ error: "Appointment end time must be after start time.",
696
+ };
697
+ }
698
+ if (authenticatedUserId !== data.patientId) {
699
+ console.warn(
700
+ `[BookingAdmin] Authenticated user ${authenticatedUserId} is booking for a different patient ${data.patientId}. Review authorization if this is not intended.`
701
+ );
702
+ }
703
+
704
+ // --- 2. Fetch Core Procedure Data ---
705
+ const procedureRef = this.db
706
+ .collection(PROCEDURES_COLLECTION)
707
+ .doc(data.procedureId);
708
+ const procedureDoc = await procedureRef.get();
709
+ if (!procedureDoc.exists) {
710
+ return {
711
+ success: false,
712
+ error: `Procedure ${data.procedureId} not found.`,
713
+ };
714
+ }
715
+ const procedure = procedureDoc.data() as Procedure;
716
+
717
+ // --- 3. Fetch Clinic and then other Primary Documents ---
718
+ // Fetch clinic first to get its clinicGroupId
719
+ const clinicRef = this.db
720
+ .collection(CLINICS_COLLECTION)
721
+ .doc(procedure.clinicBranchId);
722
+ const clinicSnap = await clinicRef.get(); // Await here directly
723
+ if (!clinicSnap.exists) {
724
+ return {
725
+ success: false,
726
+ error: `Clinic ${procedure.clinicBranchId} not found.`,
727
+ };
728
+ }
729
+ const clinicData = clinicSnap.data() as Clinic; // Now clinicData is available
730
+
731
+ // Define other refs using clinicData for clinicGroupRef
732
+ const practitionerRef = this.db
733
+ .collection(PRACTITIONERS_COLLECTION)
734
+ .doc(procedure.practitionerId);
735
+ const patientProfileRef = this.db
736
+ .collection(PATIENTS_COLLECTION)
737
+ .doc(data.patientId);
738
+ const patientSensitiveRef = this.db
739
+ .collection(PATIENTS_COLLECTION)
740
+ .doc(data.patientId)
741
+ .collection(PATIENT_SENSITIVE_INFO_COLLECTION)
742
+ .doc(data.patientId);
743
+ const clinicGroupRef = this.db
744
+ .collection(CLINIC_GROUPS_COLLECTION)
745
+ .doc(clinicData.clinicGroupId); // Use clinicData here
746
+
747
+ const [
748
+ practitionerSnap,
749
+ patientProfileSnap,
750
+ patientSensitiveSnap,
751
+ clinicGroupSnap,
752
+ ] = await Promise.all([
753
+ // clinicRef.get() is already done via clinicSnap
754
+ practitionerRef.get(),
755
+ patientProfileRef.get(),
756
+ patientSensitiveRef.get(),
757
+ clinicGroupRef.get(), // Fetch the defined clinicGroupRef
758
+ ]);
759
+
760
+ if (!practitionerSnap.exists)
761
+ return {
762
+ success: false,
763
+ error: `Practitioner ${procedure.practitionerId} not found.`,
764
+ };
765
+ if (!patientProfileSnap.exists)
766
+ return {
767
+ success: false,
768
+ error: `PatientProfile ${data.patientId} not found.`,
769
+ };
770
+ if (!clinicGroupSnap.exists)
771
+ return {
772
+ success: false,
773
+ error: `ClinicGroup for clinic ${procedure.clinicBranchId} not found.`,
774
+ };
775
+
776
+ const practitionerData = practitionerSnap.data() as Practitioner;
777
+ const patientProfileData = patientProfileSnap.data() as PatientProfile;
778
+ const patientSensitiveData = patientSensitiveSnap.exists
779
+ ? (patientSensitiveSnap.data() as PatientSensitiveInfo)
780
+ : undefined;
781
+ const clinicGroupData = clinicGroupSnap.data() as ClinicGroup;
782
+
783
+ // --- 4. Determine initialStatus (based on clinic settings) ---
784
+ const autoConfirm = clinicGroupData.autoConfirmAppointments || false;
785
+ const initialAppointmentStatus = autoConfirm
786
+ ? AppointmentStatus.CONFIRMED
787
+ : AppointmentStatus.PENDING;
788
+ const initialCalendarEventStatus = autoConfirm
789
+ ? CalendarEventStatus.CONFIRMED
790
+ : CalendarEventStatus.PENDING;
791
+
792
+ // --- 5. Aggregate Information (Snapshots) ---
793
+ const clinicInfo: ClinicInfo = {
794
+ id: clinicSnap.id,
795
+ name: clinicData.name,
796
+ featuredPhoto:
797
+ (typeof clinicData.coverPhoto === "string"
798
+ ? clinicData.coverPhoto
799
+ : "") ||
800
+ (typeof clinicData.logo === "string" ? clinicData.logo : "") ||
801
+ "",
802
+ description: clinicData.description,
803
+ location: clinicData.location,
804
+ contactInfo: clinicData.contactInfo,
805
+ };
806
+ const practitionerInfo: PractitionerProfileInfo = {
807
+ id: practitionerSnap.id,
808
+ practitionerPhoto:
809
+ typeof practitionerData.basicInfo.profileImageUrl === "string"
810
+ ? practitionerData.basicInfo.profileImageUrl
811
+ : null,
812
+ name: `${practitionerData.basicInfo.firstName} ${practitionerData.basicInfo.lastName}`,
813
+ email: practitionerData.basicInfo.email,
814
+ phone: practitionerData.basicInfo.phoneNumber || null,
815
+ certification: practitionerData.certification,
816
+ };
817
+ const patientInfo: PatientProfileInfo = {
818
+ id: patientProfileSnap.id,
819
+ fullName:
820
+ `${patientSensitiveData?.firstName || ""} ${
821
+ patientSensitiveData?.lastName || ""
822
+ }`.trim() || patientProfileData.displayName,
823
+ email: patientSensitiveData?.email || "",
824
+ phone:
825
+ patientSensitiveData?.phoneNumber ||
826
+ patientProfileData.phoneNumber ||
827
+ null,
828
+ dateOfBirth:
829
+ patientSensitiveData?.dateOfBirth ||
830
+ patientProfileData.dateOfBirth ||
831
+ admin.firestore.Timestamp.now(),
832
+ gender: patientSensitiveData?.gender || Gender.OTHER,
833
+ };
834
+ // const procedureCategory = procedure.category as Category;
835
+ // const procedureSubCategory = procedure.subcategory as Subcategory;
836
+ // const procedureTechnology = procedure.technology as Technology;
837
+ // const procedureProduct = procedure.product as Product;
838
+
839
+ // const procedureExtendedInfo: ProcedureExtendedInfo = {
840
+ // id: procedure.id,
841
+ // name: procedure.name,
842
+ // description: procedure.description,
843
+ // cost: procedure.price,
844
+ // duration: procedure.duration,
845
+ // procedureFamily: procedure.family,
846
+ // procedureCategoryId: procedureCategory?.id || "",
847
+ // procedureCategoryName: procedureCategory?.name || "",
848
+ // procedureSubCategoryId: procedureSubCategory?.id || "",
849
+ // procedureSubCategoryName: procedureSubCategory?.name || "",
850
+ // procedureTechnologyId: procedureTechnology?.id || "",
851
+ // procedureTechnologyName: procedureTechnology?.name || "",
852
+ // procedureProductBrandId: procedureProduct.brandId || "",
853
+ // procedureProductBrandName: procedureProduct.brandName || "",
854
+ // procedureProductId: procedureProduct.id || "",
855
+ // procedureProductName: procedureProduct.name || "",
856
+ // };
857
+
858
+ // // --- 6. Determine pendingUserFormsIds and linkedFormIds ---
859
+ // let pendingUserFormsIds: string[] = [];
860
+ // let linkedFormIds: string[] = [];
861
+ // if (
862
+ // procedure.documentationTemplates &&
863
+ // Array.isArray(procedure.documentationTemplates)
864
+ // ) {
865
+ // pendingUserFormsIds = procedure.documentationTemplates
866
+ // .filter(
867
+ // (template: TechnologyDocumentationTemplate) =>
868
+ // template.isUserForm && template.isRequired
869
+ // )
870
+ // .map(
871
+ // (template: TechnologyDocumentationTemplate) => template.templateId
872
+ // );
873
+ // linkedFormIds = procedure.documentationTemplates.map(
874
+ // (template: TechnologyDocumentationTemplate) => template.templateId
875
+ // );
876
+ // }
877
+
878
+ // --- 7. Construct New Appointment Object ---
879
+ const newAppointmentId = this.db
880
+ .collection(APPOINTMENTS_COLLECTION)
881
+ .doc().id;
882
+
883
+ const eventTimeForCalendarEvents: CalendarEventTime = {
884
+ start: data.appointmentStartTime as any,
885
+ end: data.appointmentEndTime as any,
886
+ };
887
+
888
+ // Practitioner Calendar Event
889
+ const practitionerCalendarEventId = this.db
890
+ .collection(PRACTITIONERS_COLLECTION)
891
+ .doc(practitionerData.id)
892
+ .collection(CALENDAR_COLLECTION)
893
+ .doc().id;
894
+ const practitionerCalendarEventData: CalendarEvent = {
895
+ id: practitionerCalendarEventId,
896
+ appointmentId: newAppointmentId,
897
+ clinicBranchId: clinicData.id,
898
+ clinicBranchInfo: clinicInfo,
899
+ practitionerProfileId: practitionerData.id,
900
+ practitionerProfileInfo: practitionerInfo,
901
+ patientProfileId: patientProfileData.id,
902
+ patientProfileInfo: patientInfo,
903
+ procedureId: procedure.id,
904
+ procedureInfo: this._generateCalendarProcedureInfo(procedure),
905
+ eventName: `Appointment: ${procedure.name} with ${patientInfo.fullName}`,
906
+ eventLocation: clinicData.location,
907
+ eventTime: eventTimeForCalendarEvents,
908
+ description: procedure.description || "",
909
+ status: initialCalendarEventStatus,
910
+ syncStatus: CalendarSyncStatus.INTERNAL,
911
+ eventType: CalendarEventType.APPOINTMENT,
912
+ createdAt: serverTimestampValue as any,
913
+ updatedAt: serverTimestampValue as any,
914
+ };
915
+ batch.set(
916
+ this.db
917
+ .collection(PRACTITIONERS_COLLECTION)
918
+ .doc(practitionerData.id)
919
+ .collection(CALENDAR_COLLECTION)
920
+ .doc(practitionerCalendarEventId),
921
+ practitionerCalendarEventData
922
+ );
923
+
924
+ // Patient Calendar Event
925
+ // Use same ID as practitionerCalendarEventId
926
+ const patientCalendarEventData: CalendarEvent = {
927
+ id: practitionerCalendarEventId,
928
+ appointmentId: newAppointmentId,
929
+ clinicBranchId: clinicData.id,
930
+ clinicBranchInfo: clinicInfo,
931
+ practitionerProfileId: practitionerData.id,
932
+ practitionerProfileInfo: practitionerInfo,
933
+ procedureId: procedure.id,
934
+ procedureInfo: this._generateCalendarProcedureInfo(procedure),
935
+ eventName: `Appointment: ${procedure.name} at ${clinicData.name}`,
936
+ eventLocation: clinicData.location,
937
+ eventTime: eventTimeForCalendarEvents,
938
+ description: data.patientNotes || "",
939
+ status: initialCalendarEventStatus,
940
+ syncStatus: CalendarSyncStatus.INTERNAL,
941
+ eventType: CalendarEventType.APPOINTMENT,
942
+ createdAt: serverTimestampValue as any,
943
+ updatedAt: serverTimestampValue as any,
944
+ };
945
+ batch.set(
946
+ this.db
947
+ .collection(PATIENTS_COLLECTION)
948
+ .doc(patientProfileData.id)
949
+ .collection(CALENDAR_COLLECTION)
950
+ .doc(practitionerCalendarEventId),
951
+ patientCalendarEventData
952
+ );
953
+
954
+ // Clinic Calendar Event
955
+ // Use same ID as practitionerCalendarEventId
956
+ const clinicCalendarEventData: CalendarEvent = {
957
+ id: practitionerCalendarEventId,
958
+ appointmentId: newAppointmentId,
959
+ clinicBranchId: clinicData.id,
960
+ clinicBranchInfo: clinicInfo,
961
+ practitionerProfileId: practitionerData.id,
962
+ practitionerProfileInfo: practitionerInfo,
963
+ patientProfileId: patientProfileData.id,
964
+ patientProfileInfo: patientInfo,
965
+ procedureId: procedure.id,
966
+ procedureInfo: this._generateCalendarProcedureInfo(procedure),
967
+ eventName: `Appointment: ${procedure.name} for ${patientInfo.fullName} with ${practitionerInfo.name}`,
968
+ eventLocation: clinicData.location,
969
+ eventTime: eventTimeForCalendarEvents,
970
+ description: data.patientNotes || "",
971
+ status: initialCalendarEventStatus,
972
+ syncStatus: CalendarSyncStatus.INTERNAL,
973
+ eventType: CalendarEventType.APPOINTMENT,
974
+ createdAt: serverTimestampValue as any,
975
+ updatedAt: serverTimestampValue as any,
976
+ };
977
+ batch.set(
978
+ this.db
979
+ .collection(CLINICS_COLLECTION)
980
+ .doc(clinicData.id)
981
+ .collection(CALENDAR_COLLECTION)
982
+ .doc(practitionerCalendarEventId),
983
+ clinicCalendarEventData
984
+ );
985
+
986
+ // --- Resource Allocation (if procedure requires resources) ---
987
+ let resourceBookings: ResourceBookingInfo[] = [];
988
+ if (
989
+ procedure.resourceRequirements &&
990
+ procedure.resourceRequirements.length > 0
991
+ ) {
992
+ console.log(
993
+ `[BookingAdmin] Allocating resources for appointment ${newAppointmentId}, ` +
994
+ `${procedure.resourceRequirements.length} resource(s) required`
995
+ );
996
+
997
+ for (const requirement of procedure.resourceRequirements) {
998
+ // Fetch all active instances of this resource, sorted by index
999
+ const instancesSnapshot = await this.db
1000
+ .collection(CLINICS_COLLECTION)
1001
+ .doc(clinicData.id)
1002
+ .collection(RESOURCES_COLLECTION)
1003
+ .doc(requirement.resourceId)
1004
+ .collection(RESOURCE_INSTANCES_SUBCOLLECTION)
1005
+ .where("status", "==", ResourceStatus.ACTIVE)
1006
+ .orderBy("index")
1007
+ .get();
1008
+
1009
+ if (instancesSnapshot.empty) {
1010
+ return {
1011
+ success: false,
1012
+ error: `Resource "${requirement.resourceName}" has no active instances available.`,
1013
+ };
1014
+ }
1015
+
1016
+ let allocatedInstance: ResourceInstance | null = null;
1017
+
1018
+ for (const instanceDoc of instancesSnapshot.docs) {
1019
+ const instance = {
1020
+ ...instanceDoc.data(),
1021
+ id: instanceDoc.id,
1022
+ } as ResourceInstance;
1023
+
1024
+ // Check if this instance has overlapping active events during appointment time
1025
+ const overlappingEventsSnapshot = await this.db
1026
+ .collection(CLINICS_COLLECTION)
1027
+ .doc(clinicData.id)
1028
+ .collection(RESOURCES_COLLECTION)
1029
+ .doc(requirement.resourceId)
1030
+ .collection(RESOURCE_INSTANCES_SUBCOLLECTION)
1031
+ .doc(instance.id)
1032
+ .collection(RESOURCE_CALENDAR_SUBCOLLECTION)
1033
+ .where("eventTime.start", "<", data.appointmentEndTime)
1034
+ .where("status", "in", [
1035
+ CalendarEventStatus.PENDING,
1036
+ CalendarEventStatus.CONFIRMED,
1037
+ CalendarEventStatus.CHECKED_IN,
1038
+ CalendarEventStatus.IN_PROGRESS,
1039
+ ])
1040
+ .get();
1041
+
1042
+ // Post-filter: event must end after appointment start to truly overlap
1043
+ const hasOverlap = overlappingEventsSnapshot.docs.some((doc) => {
1044
+ const event = doc.data();
1045
+ return (
1046
+ event.eventTime.end.toMillis() >
1047
+ data.appointmentStartTime.toMillis()
1048
+ );
1049
+ });
1050
+
1051
+ if (!hasOverlap) {
1052
+ allocatedInstance = instance;
1053
+ break;
1054
+ }
1055
+ }
1056
+
1057
+ if (!allocatedInstance) {
1058
+ return {
1059
+ success: false,
1060
+ error: `Resource "${requirement.resourceName}" is not available at the selected time. All instances are booked.`,
1061
+ };
1062
+ }
1063
+
1064
+ // Create ResourceCalendarEvent on the allocated instance's calendar
1065
+ const resourceCalendarEventRef = this.db
1066
+ .collection(CLINICS_COLLECTION)
1067
+ .doc(clinicData.id)
1068
+ .collection(RESOURCES_COLLECTION)
1069
+ .doc(requirement.resourceId)
1070
+ .collection(RESOURCE_INSTANCES_SUBCOLLECTION)
1071
+ .doc(allocatedInstance.id)
1072
+ .collection(RESOURCE_CALENDAR_SUBCOLLECTION)
1073
+ .doc();
1074
+
1075
+ const resourceCalendarEventData = {
1076
+ id: resourceCalendarEventRef.id,
1077
+ resourceId: requirement.resourceId,
1078
+ resourceInstanceId: allocatedInstance.id,
1079
+ clinicBranchId: clinicData.id,
1080
+ eventType: CalendarEventType.RESOURCE_BOOKING,
1081
+ appointmentId: newAppointmentId,
1082
+ procedureId: procedure.id,
1083
+ practitionerId: practitionerData.id,
1084
+ patientId: data.patientId,
1085
+ eventTime: eventTimeForCalendarEvents,
1086
+ status: initialCalendarEventStatus,
1087
+ eventName: `${procedure.name} - ${allocatedInstance.label}`,
1088
+ createdAt: serverTimestampValue,
1089
+ updatedAt: serverTimestampValue,
1090
+ };
1091
+
1092
+ batch.set(resourceCalendarEventRef, resourceCalendarEventData);
1093
+
1094
+ resourceBookings.push({
1095
+ resourceId: requirement.resourceId,
1096
+ resourceName: requirement.resourceName,
1097
+ resourceInstanceId: allocatedInstance.id,
1098
+ resourceInstanceLabel: allocatedInstance.label,
1099
+ calendarEventId: resourceCalendarEventRef.id,
1100
+ });
1101
+
1102
+ console.log(
1103
+ `[BookingAdmin] Allocated resource "${requirement.resourceName}" → ` +
1104
+ `instance "${allocatedInstance.label}" (${allocatedInstance.id})`
1105
+ );
1106
+ }
1107
+ }
1108
+
1109
+ // --- Initialize Pending/Draft Filled Documents and get form IDs ---
1110
+ let initializedFormsInfo: LinkedFormInfo[] = [];
1111
+ let pendingUserFormTemplateIds: string[] = [];
1112
+ let allLinkedFormTemplateIds: string[] = [];
1113
+
1114
+ if (
1115
+ procedure.documentationTemplates &&
1116
+ Array.isArray(procedure.documentationTemplates) &&
1117
+ procedure.documentationTemplates.length > 0
1118
+ ) {
1119
+ const formInitResult =
1120
+ await this.documentManagerAdmin.batchInitializeAppointmentFormsFromTechnologyTemplates(
1121
+ batch,
1122
+ newAppointmentId,
1123
+ procedure.id, // Pass the actual procedureId for the forms
1124
+ procedure.documentationTemplates,
1125
+ data.patientId,
1126
+ procedure.practitionerId,
1127
+ procedure.clinicBranchId,
1128
+ adminTsNow.toMillis()
1129
+ );
1130
+ initializedFormsInfo = formInitResult.initializedFormsInfo;
1131
+ pendingUserFormTemplateIds = formInitResult.pendingUserFormsIds;
1132
+ allLinkedFormTemplateIds = formInitResult.allLinkedTemplateIds;
1133
+ }
1134
+
1135
+ // --- Generate appointment products from procedure ---
1136
+ const appointmentProducts = this._generateAppointmentProductsFromProcedure(procedure);
1137
+
1138
+ // --- Construct Appointment Object ---
1139
+ const newAppointmentData: Appointment = {
1140
+ id: newAppointmentId,
1141
+ calendarEventId: practitionerCalendarEventId,
1142
+ clinicBranchId: procedure.clinicBranchId,
1143
+ clinicInfo,
1144
+ clinic_tz: clinicData.location.tz || "UTC",
1145
+ practitionerId: procedure.practitionerId,
1146
+ practitionerInfo,
1147
+ patientId: data.patientId,
1148
+ patientInfo,
1149
+ procedureId: data.procedureId,
1150
+ procedureInfo: this._generateProcedureSummaryInfo(
1151
+ procedure,
1152
+ clinicData,
1153
+ practitionerData
1154
+ ),
1155
+ procedureExtendedInfo: this._generateProcedureExtendedInfo(procedure),
1156
+ status: initialAppointmentStatus,
1157
+ bookingTime: adminTsNow as any,
1158
+ confirmationTime:
1159
+ initialAppointmentStatus === AppointmentStatus.CONFIRMED
1160
+ ? (adminTsNow as any)
1161
+ : null,
1162
+ appointmentStartTime: data.appointmentStartTime as any,
1163
+ appointmentEndTime: data.appointmentEndTime as any,
1164
+ cost: procedure.price,
1165
+ currency: procedure.currency,
1166
+ paymentStatus:
1167
+ procedure.price > 0
1168
+ ? PaymentStatus.UNPAID
1169
+ : PaymentStatus.NOT_APPLICABLE,
1170
+ patientNotes: data.patientNotes || null,
1171
+ blockingConditions: procedure.blockingConditions || [],
1172
+ contraindications: (procedure as any).contraindications || [],
1173
+ preProcedureRequirements: procedure.preRequirements || [],
1174
+ postProcedureRequirements: procedure.postRequirements || [],
1175
+ pendingUserFormsIds: pendingUserFormTemplateIds,
1176
+ linkedFormIds: allLinkedFormTemplateIds,
1177
+ completedPreRequirements: [],
1178
+ completedPostRequirements: [],
1179
+ linkedForms: initializedFormsInfo,
1180
+ media: [],
1181
+ reviewInfo: null,
1182
+ metadata: {
1183
+ selectedZones: null,
1184
+ zonePhotos: null,
1185
+ zonesData: null,
1186
+ appointmentProducts: appointmentProducts,
1187
+ extendedProcedures: [],
1188
+ recommendedProcedures: [],
1189
+ finalbilling: null,
1190
+ finalizationNotes: null,
1191
+ },
1192
+ finalizedDetails: {
1193
+ by: "",
1194
+ at: adminTsNow as any,
1195
+ notes: "",
1196
+ },
1197
+ internalNotes: null,
1198
+ cancellationReason: null,
1199
+ cancellationTime: null,
1200
+ canceledBy: undefined,
1201
+ rescheduleTime: null,
1202
+ procedureActualStartTime: null,
1203
+ actualDurationMinutes: undefined,
1204
+ isRecurring: false,
1205
+ recurringAppointmentId: null,
1206
+ isArchived: false,
1207
+ ...(resourceBookings.length > 0 && { resourceBookings }),
1208
+ createdAt: adminTsNow as any,
1209
+ updatedAt: adminTsNow as any,
1210
+ };
1211
+
1212
+ batch.set(
1213
+ this.db.collection(APPOINTMENTS_COLLECTION).doc(newAppointmentId),
1214
+ newAppointmentData
1215
+ );
1216
+
1217
+ // Commit Batch
1218
+ await batch.commit();
1219
+
1220
+ console.log(
1221
+ `[BookingAdmin] Appointment ${newAppointmentId} and associated calendar events created successfully.`
1222
+ );
1223
+ return {
1224
+ success: true,
1225
+ appointmentId: newAppointmentId,
1226
+ appointmentData: newAppointmentData,
1227
+ calendarEventId: practitionerCalendarEventId,
1228
+ };
1229
+ } catch (error) {
1230
+ console.error(
1231
+ "[BookingAdmin] Critical error in orchestrateAppointmentCreation:",
1232
+ error
1233
+ );
1234
+ const errorMessage =
1235
+ error instanceof Error
1236
+ ? error.message
1237
+ : "Unknown server error during appointment creation.";
1238
+ return { success: false, error: errorMessage };
1239
+ }
1240
+ }
1241
+
1242
+ private _generateProcedureSummaryInfo(
1243
+ procedure: Procedure,
1244
+ clinicData: Clinic,
1245
+ practitionerData: Practitioner
1246
+ ): ProcedureSummaryInfo {
1247
+ const procedureCategory = procedure.category as Category;
1248
+ const procedureSubCategory = procedure.subcategory as Subcategory;
1249
+ const procedureTechnology = procedure.technology as Technology;
1250
+ const procedureProduct = procedure.product as Product;
1251
+ return {
1252
+ id: procedure.id,
1253
+ name: procedure.name,
1254
+ description: procedure.description,
1255
+ family: procedure.family,
1256
+ categoryName: procedureCategory?.name || "",
1257
+ subcategoryName: procedureSubCategory?.name || "",
1258
+ technologyName: procedureTechnology?.name || "",
1259
+ price: procedure.price,
1260
+ pricingMeasure: procedure.pricingMeasure,
1261
+ currency: procedure.currency,
1262
+ duration: procedure.duration,
1263
+ clinicId: procedure.clinicBranchId,
1264
+ clinicName: clinicData.name,
1265
+ practitionerId: procedure.practitionerId,
1266
+ practitionerName: `${practitionerData.basicInfo.firstName} ${practitionerData.basicInfo.lastName}`,
1267
+ photo:
1268
+ (procedureTechnology as any)?.photos?.[0]?.url ||
1269
+ (procedureProduct as any)?.photos?.[0]?.url ||
1270
+ "",
1271
+ brandName: (procedureProduct as any)?.brand?.name || "",
1272
+ productName: procedureProduct?.name || "",
1273
+ };
1274
+ }
1275
+
1276
+ private _generateProcedureExtendedInfo(
1277
+ procedure: Procedure
1278
+ ): ProcedureExtendedInfo {
1279
+ const procedureCategory = procedure.category as Category;
1280
+ const procedureSubCategory = procedure.subcategory as Subcategory;
1281
+ const procedureTechnology = procedure.technology as Technology;
1282
+ const procedureProduct = procedure.product as Product;
1283
+ const productsMetadata = procedure.productsMetadata || [];
1284
+
1285
+ return {
1286
+ id: procedure.id,
1287
+ name: procedure.name,
1288
+ description: procedure.description,
1289
+ cost: procedure.price,
1290
+ duration: procedure.duration,
1291
+ procedureFamily: procedure.family,
1292
+ procedureCategoryId: procedureCategory?.id || "",
1293
+ procedureCategoryName: procedureCategory?.name || "",
1294
+ procedureSubCategoryId: procedureSubCategory?.id || "",
1295
+ procedureSubCategoryName: procedureSubCategory?.name || "",
1296
+ procedureTechnologyId: procedureTechnology?.id || "",
1297
+ procedureTechnologyName: procedureTechnology?.name || "",
1298
+ procedureProductBrandId: procedureProduct?.brandId || "",
1299
+ procedureProductBrandName: procedureProduct?.brandName || "",
1300
+ procedureProducts: productsMetadata
1301
+ .filter((pp: any) => pp && pp.product) // Safety check for product-free procedures
1302
+ .map((pp: any) => ({
1303
+ productId: pp.product.id,
1304
+ productName: pp.product.name,
1305
+ brandId: pp.product.brandId,
1306
+ brandName: pp.product.brandName,
1307
+ })),
1308
+ };
1309
+ }
1310
+
1311
+ private _generateAppointmentProductsFromProcedure(procedure: Procedure): any[] {
1312
+ const productsMetadata = procedure.productsMetadata || [];
1313
+
1314
+ return productsMetadata
1315
+ .filter((pp: any) => pp && pp.product) // Safety check for product-free procedures
1316
+ .map((pp: any) => {
1317
+ const product = pp.product;
1318
+ return {
1319
+ productId: product.id,
1320
+ productName: product.name,
1321
+ brandId: product.brandId,
1322
+ brandName: product.brandName,
1323
+ procedureId: procedure.id,
1324
+ price: pp.price,
1325
+ currency: pp.currency,
1326
+ unitOfMeasurement: pp.pricingMeasure,
1327
+ };
1328
+ });
1329
+ }
1330
+ }