@blackcode_sa/metaestetics-api 1.13.5 → 1.13.8

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 (295) hide show
  1. package/dist/admin/index.d.mts +20 -1
  2. package/dist/admin/index.d.ts +20 -1
  3. package/dist/admin/index.js +217 -1
  4. package/dist/admin/index.mjs +217 -1
  5. package/dist/index.d.mts +26 -3
  6. package/dist/index.d.ts +26 -3
  7. package/dist/index.js +168 -6
  8. package/dist/index.mjs +168 -6
  9. package/package.json +121 -121
  10. package/src/__mocks__/firstore.ts +10 -10
  11. package/src/admin/aggregation/README.md +79 -79
  12. package/src/admin/aggregation/appointment/README.md +128 -128
  13. package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +1984 -1984
  14. package/src/admin/aggregation/appointment/index.ts +1 -1
  15. package/src/admin/aggregation/clinic/README.md +52 -52
  16. package/src/admin/aggregation/clinic/clinic.aggregation.service.ts +966 -703
  17. package/src/admin/aggregation/clinic/index.ts +1 -1
  18. package/src/admin/aggregation/forms/README.md +13 -13
  19. package/src/admin/aggregation/forms/filled-forms.aggregation.service.ts +322 -322
  20. package/src/admin/aggregation/forms/index.ts +1 -1
  21. package/src/admin/aggregation/index.ts +8 -8
  22. package/src/admin/aggregation/patient/README.md +27 -27
  23. package/src/admin/aggregation/patient/index.ts +1 -1
  24. package/src/admin/aggregation/patient/patient.aggregation.service.ts +141 -141
  25. package/src/admin/aggregation/practitioner/README.md +42 -42
  26. package/src/admin/aggregation/practitioner/index.ts +1 -1
  27. package/src/admin/aggregation/practitioner/practitioner.aggregation.service.ts +433 -433
  28. package/src/admin/aggregation/practitioner-invite/index.ts +1 -1
  29. package/src/admin/aggregation/practitioner-invite/practitioner-invite.aggregation.service.ts +961 -961
  30. package/src/admin/aggregation/procedure/README.md +43 -43
  31. package/src/admin/aggregation/procedure/index.ts +1 -1
  32. package/src/admin/aggregation/procedure/procedure.aggregation.service.ts +702 -702
  33. package/src/admin/aggregation/reviews/index.ts +1 -1
  34. package/src/admin/aggregation/reviews/reviews.aggregation.service.ts +689 -689
  35. package/src/admin/analytics/analytics.admin.service.ts +278 -278
  36. package/src/admin/analytics/index.ts +2 -2
  37. package/src/admin/booking/README.md +125 -125
  38. package/src/admin/booking/booking.admin.ts +1037 -1037
  39. package/src/admin/booking/booking.calculator.ts +712 -712
  40. package/src/admin/booking/booking.types.ts +59 -59
  41. package/src/admin/booking/index.ts +3 -3
  42. package/src/admin/booking/timezones-problem.md +185 -185
  43. package/src/admin/calendar/README.md +7 -7
  44. package/src/admin/calendar/calendar.admin.service.ts +345 -345
  45. package/src/admin/calendar/index.ts +1 -1
  46. package/src/admin/documentation-templates/document-manager.admin.ts +260 -260
  47. package/src/admin/documentation-templates/index.ts +1 -1
  48. package/src/admin/free-consultation/free-consultation-utils.admin.ts +148 -148
  49. package/src/admin/free-consultation/index.ts +1 -1
  50. package/src/admin/index.ts +81 -81
  51. package/src/admin/logger/index.ts +78 -78
  52. package/src/admin/mailing/README.md +95 -95
  53. package/src/admin/mailing/appointment/appointment.mailing.service.ts +732 -732
  54. package/src/admin/mailing/appointment/index.ts +1 -1
  55. package/src/admin/mailing/appointment/templates/patient/appointment-confirmed.html +40 -40
  56. package/src/admin/mailing/base.mailing.service.ts +208 -208
  57. package/src/admin/mailing/index.ts +3 -3
  58. package/src/admin/mailing/practitionerInvite/existing-practitioner-invite.mailing.ts +611 -611
  59. package/src/admin/mailing/practitionerInvite/index.ts +2 -2
  60. package/src/admin/mailing/practitionerInvite/practitionerInvite.mailing.ts +395 -395
  61. package/src/admin/mailing/practitionerInvite/templates/existing-practitioner-invitation.template.ts +155 -155
  62. package/src/admin/mailing/practitionerInvite/templates/invitation.template.ts +101 -101
  63. package/src/admin/mailing/practitionerInvite/templates/invite-accepted-notification.template.ts +228 -228
  64. package/src/admin/mailing/practitionerInvite/templates/invite-rejected-notification.template.ts +242 -242
  65. package/src/admin/notifications/index.ts +1 -1
  66. package/src/admin/notifications/notifications.admin.ts +710 -710
  67. package/src/admin/requirements/README.md +128 -128
  68. package/src/admin/requirements/index.ts +1 -1
  69. package/src/admin/requirements/patient-requirements.admin.service.ts +475 -475
  70. package/src/admin/users/index.ts +1 -1
  71. package/src/admin/users/user-profile.admin.ts +405 -405
  72. package/src/backoffice/constants/certification.constants.ts +13 -13
  73. package/src/backoffice/constants/index.ts +1 -1
  74. package/src/backoffice/errors/backoffice.errors.ts +181 -181
  75. package/src/backoffice/errors/index.ts +1 -1
  76. package/src/backoffice/expo-safe/README.md +26 -26
  77. package/src/backoffice/expo-safe/index.ts +41 -41
  78. package/src/backoffice/index.ts +5 -5
  79. package/src/backoffice/services/FIXES_README.md +102 -102
  80. package/src/backoffice/services/README.md +57 -57
  81. package/src/backoffice/services/analytics.service.proposal.md +863 -863
  82. package/src/backoffice/services/analytics.service.summary.md +143 -143
  83. package/src/backoffice/services/brand.service.ts +256 -256
  84. package/src/backoffice/services/category.service.ts +384 -384
  85. package/src/backoffice/services/constants.service.ts +385 -385
  86. package/src/backoffice/services/documentation-template.service.ts +202 -202
  87. package/src/backoffice/services/index.ts +10 -10
  88. package/src/backoffice/services/migrate-products.ts +116 -116
  89. package/src/backoffice/services/product.service.ts +553 -553
  90. package/src/backoffice/services/requirement.service.ts +235 -235
  91. package/src/backoffice/services/subcategory.service.ts +461 -461
  92. package/src/backoffice/services/technology.service.ts +1151 -1151
  93. package/src/backoffice/types/README.md +12 -12
  94. package/src/backoffice/types/admin-constants.types.ts +69 -69
  95. package/src/backoffice/types/brand.types.ts +29 -29
  96. package/src/backoffice/types/category.types.ts +67 -67
  97. package/src/backoffice/types/documentation-templates.types.ts +28 -28
  98. package/src/backoffice/types/index.ts +10 -10
  99. package/src/backoffice/types/procedure-product.types.ts +38 -38
  100. package/src/backoffice/types/product.types.ts +240 -240
  101. package/src/backoffice/types/requirement.types.ts +63 -63
  102. package/src/backoffice/types/static/README.md +18 -18
  103. package/src/backoffice/types/static/blocking-condition.types.ts +21 -21
  104. package/src/backoffice/types/static/certification.types.ts +37 -37
  105. package/src/backoffice/types/static/contraindication.types.ts +19 -19
  106. package/src/backoffice/types/static/index.ts +6 -6
  107. package/src/backoffice/types/static/pricing.types.ts +16 -16
  108. package/src/backoffice/types/static/procedure-family.types.ts +14 -14
  109. package/src/backoffice/types/static/treatment-benefit.types.ts +22 -22
  110. package/src/backoffice/types/subcategory.types.ts +34 -34
  111. package/src/backoffice/types/technology.types.ts +168 -168
  112. package/src/backoffice/validations/index.ts +1 -1
  113. package/src/backoffice/validations/schemas.ts +164 -164
  114. package/src/config/__mocks__/firebase.ts +99 -99
  115. package/src/config/firebase.ts +78 -78
  116. package/src/config/index.ts +9 -9
  117. package/src/errors/auth.error.ts +6 -6
  118. package/src/errors/auth.errors.ts +211 -200
  119. package/src/errors/clinic.errors.ts +32 -32
  120. package/src/errors/firebase.errors.ts +47 -47
  121. package/src/errors/user.errors.ts +99 -99
  122. package/src/index.backup.ts +407 -407
  123. package/src/index.ts +6 -6
  124. package/src/locales/en.ts +31 -31
  125. package/src/recommender/admin/index.ts +1 -1
  126. package/src/recommender/admin/services/recommender.service.admin.ts +5 -5
  127. package/src/recommender/front/index.ts +1 -1
  128. package/src/recommender/front/services/onboarding.service.ts +5 -5
  129. package/src/recommender/front/services/recommender.service.ts +3 -3
  130. package/src/recommender/index.ts +1 -1
  131. package/src/services/PATIENTAUTH.MD +197 -197
  132. package/src/services/README.md +106 -106
  133. package/src/services/__tests__/auth/auth.mock.test.ts +17 -17
  134. package/src/services/__tests__/auth/auth.setup.ts +293 -293
  135. package/src/services/__tests__/auth.service.test.ts +346 -346
  136. package/src/services/__tests__/base.service.test.ts +77 -77
  137. package/src/services/__tests__/user.service.test.ts +528 -528
  138. package/src/services/analytics/ARCHITECTURE.md +199 -199
  139. package/src/services/analytics/CLOUD_FUNCTIONS.md +225 -225
  140. package/src/services/analytics/GROUPED_ANALYTICS.md +501 -501
  141. package/src/services/analytics/QUICK_START.md +393 -393
  142. package/src/services/analytics/README.md +304 -304
  143. package/src/services/analytics/SUMMARY.md +141 -141
  144. package/src/services/analytics/TRENDS.md +380 -380
  145. package/src/services/analytics/USAGE_GUIDE.md +518 -518
  146. package/src/services/analytics/analytics-cloud.service.ts +222 -222
  147. package/src/services/analytics/analytics.service.ts +2142 -2142
  148. package/src/services/analytics/index.ts +4 -4
  149. package/src/services/analytics/review-analytics.service.ts +941 -941
  150. package/src/services/analytics/utils/appointment-filtering.utils.ts +138 -138
  151. package/src/services/analytics/utils/cost-calculation.utils.ts +182 -182
  152. package/src/services/analytics/utils/grouping.utils.ts +434 -434
  153. package/src/services/analytics/utils/stored-analytics.utils.ts +347 -347
  154. package/src/services/analytics/utils/time-calculation.utils.ts +186 -186
  155. package/src/services/analytics/utils/trend-calculation.utils.ts +200 -200
  156. package/src/services/appointment/README.md +17 -17
  157. package/src/services/appointment/appointment.service.ts +2558 -2558
  158. package/src/services/appointment/index.ts +1 -1
  159. package/src/services/appointment/utils/appointment.utils.ts +552 -552
  160. package/src/services/appointment/utils/extended-procedure.utils.ts +314 -314
  161. package/src/services/appointment/utils/form-initialization.utils.ts +225 -225
  162. package/src/services/appointment/utils/recommended-procedure.utils.ts +195 -195
  163. package/src/services/appointment/utils/zone-management.utils.ts +353 -353
  164. package/src/services/appointment/utils/zone-photo.utils.ts +152 -152
  165. package/src/services/auth/auth.service.ts +1043 -989
  166. package/src/services/auth/auth.v2.service.ts +961 -961
  167. package/src/services/auth/index.ts +7 -7
  168. package/src/services/auth/utils/error.utils.ts +90 -90
  169. package/src/services/auth/utils/firebase.utils.ts +49 -49
  170. package/src/services/auth/utils/index.ts +21 -21
  171. package/src/services/auth/utils/practitioner.utils.ts +125 -125
  172. package/src/services/base.service.ts +41 -41
  173. package/src/services/calendar/calendar.service.ts +1077 -1077
  174. package/src/services/calendar/calendar.v2.service.ts +1683 -1683
  175. package/src/services/calendar/calendar.v3.service.ts +313 -313
  176. package/src/services/calendar/externalCalendar.service.ts +178 -178
  177. package/src/services/calendar/index.ts +5 -5
  178. package/src/services/calendar/synced-calendars.service.ts +743 -743
  179. package/src/services/calendar/utils/appointment.utils.ts +265 -265
  180. package/src/services/calendar/utils/calendar-event.utils.ts +646 -646
  181. package/src/services/calendar/utils/clinic.utils.ts +237 -237
  182. package/src/services/calendar/utils/docs.utils.ts +157 -157
  183. package/src/services/calendar/utils/google-calendar.utils.ts +697 -697
  184. package/src/services/calendar/utils/index.ts +8 -8
  185. package/src/services/calendar/utils/patient.utils.ts +198 -198
  186. package/src/services/calendar/utils/practitioner.utils.ts +221 -221
  187. package/src/services/calendar/utils/synced-calendar.utils.ts +472 -472
  188. package/src/services/clinic/README.md +204 -204
  189. package/src/services/clinic/__tests__/clinic-admin.service.test.ts +287 -287
  190. package/src/services/clinic/__tests__/clinic-group.service.test.ts +352 -352
  191. package/src/services/clinic/__tests__/clinic.service.test.ts +354 -354
  192. package/src/services/clinic/billing-transactions.service.ts +217 -217
  193. package/src/services/clinic/clinic-admin.service.ts +202 -202
  194. package/src/services/clinic/clinic-group.service.ts +310 -310
  195. package/src/services/clinic/clinic.service.ts +708 -708
  196. package/src/services/clinic/index.ts +5 -5
  197. package/src/services/clinic/practitioner-invite.service.ts +519 -519
  198. package/src/services/clinic/utils/admin.utils.ts +551 -551
  199. package/src/services/clinic/utils/clinic-group.utils.ts +646 -646
  200. package/src/services/clinic/utils/clinic.utils.ts +949 -949
  201. package/src/services/clinic/utils/filter.utils.d.ts +23 -23
  202. package/src/services/clinic/utils/filter.utils.ts +446 -446
  203. package/src/services/clinic/utils/index.ts +11 -11
  204. package/src/services/clinic/utils/photos.utils.ts +188 -188
  205. package/src/services/clinic/utils/search.utils.ts +84 -84
  206. package/src/services/clinic/utils/tag.utils.ts +124 -124
  207. package/src/services/documentation-templates/documentation-template.service.ts +537 -537
  208. package/src/services/documentation-templates/filled-document.service.ts +587 -587
  209. package/src/services/documentation-templates/index.ts +2 -2
  210. package/src/services/index.ts +14 -14
  211. package/src/services/media/index.ts +1 -1
  212. package/src/services/media/media.service.ts +418 -418
  213. package/src/services/notifications/__tests__/notification.service.test.ts +242 -242
  214. package/src/services/notifications/index.ts +1 -1
  215. package/src/services/notifications/notification.service.ts +215 -215
  216. package/src/services/patient/README.md +48 -48
  217. package/src/services/patient/To-Do.md +43 -43
  218. package/src/services/patient/__tests__/patient.service.test.ts +294 -294
  219. package/src/services/patient/index.ts +2 -2
  220. package/src/services/patient/patient.service.ts +883 -883
  221. package/src/services/patient/patientRequirements.service.ts +285 -285
  222. package/src/services/patient/utils/aesthetic-analysis.utils.ts +176 -176
  223. package/src/services/patient/utils/clinic.utils.ts +80 -80
  224. package/src/services/patient/utils/docs.utils.ts +142 -142
  225. package/src/services/patient/utils/index.ts +9 -9
  226. package/src/services/patient/utils/location.utils.ts +126 -126
  227. package/src/services/patient/utils/medical-stuff.utils.ts +143 -143
  228. package/src/services/patient/utils/medical.utils.ts +458 -458
  229. package/src/services/patient/utils/practitioner.utils.ts +260 -260
  230. package/src/services/patient/utils/profile.utils.ts +510 -510
  231. package/src/services/patient/utils/sensitive.utils.ts +260 -260
  232. package/src/services/patient/utils/token.utils.ts +211 -211
  233. package/src/services/practitioner/README.md +145 -145
  234. package/src/services/practitioner/index.ts +1 -1
  235. package/src/services/practitioner/practitioner.service.ts +1799 -1742
  236. package/src/services/procedure/README.md +163 -163
  237. package/src/services/procedure/index.ts +1 -1
  238. package/src/services/procedure/procedure.service.ts +2307 -2200
  239. package/src/services/reviews/index.ts +1 -1
  240. package/src/services/reviews/reviews.service.ts +734 -734
  241. package/src/services/user/index.ts +1 -1
  242. package/src/services/user/user.service.ts +489 -489
  243. package/src/services/user/user.v2.service.ts +466 -466
  244. package/src/types/analytics/analytics.types.ts +597 -597
  245. package/src/types/analytics/grouped-analytics.types.ts +173 -173
  246. package/src/types/analytics/index.ts +4 -4
  247. package/src/types/analytics/stored-analytics.types.ts +137 -137
  248. package/src/types/appointment/index.ts +480 -480
  249. package/src/types/calendar/index.ts +258 -258
  250. package/src/types/calendar/synced-calendar.types.ts +66 -66
  251. package/src/types/clinic/index.ts +498 -498
  252. package/src/types/clinic/practitioner-invite.types.ts +91 -91
  253. package/src/types/clinic/preferences.types.ts +159 -159
  254. package/src/types/clinic/to-do +3 -3
  255. package/src/types/documentation-templates/index.ts +308 -308
  256. package/src/types/index.ts +47 -47
  257. package/src/types/notifications/README.md +77 -77
  258. package/src/types/notifications/index.ts +286 -286
  259. package/src/types/patient/aesthetic-analysis.types.ts +66 -66
  260. package/src/types/patient/allergies.ts +58 -58
  261. package/src/types/patient/index.ts +275 -275
  262. package/src/types/patient/medical-info.types.ts +152 -152
  263. package/src/types/patient/patient-requirements.ts +92 -92
  264. package/src/types/patient/token.types.ts +61 -61
  265. package/src/types/practitioner/index.ts +206 -206
  266. package/src/types/procedure/index.ts +181 -181
  267. package/src/types/profile/index.ts +39 -39
  268. package/src/types/reviews/index.ts +132 -132
  269. package/src/types/tz-lookup.d.ts +4 -4
  270. package/src/types/user/index.ts +38 -38
  271. package/src/utils/TIMESTAMPS.md +176 -176
  272. package/src/utils/TimestampUtils.ts +241 -241
  273. package/src/utils/index.ts +1 -1
  274. package/src/validations/appointment.schema.ts +574 -574
  275. package/src/validations/calendar.schema.ts +225 -225
  276. package/src/validations/clinic.schema.ts +494 -494
  277. package/src/validations/common.schema.ts +25 -25
  278. package/src/validations/documentation-templates/index.ts +1 -1
  279. package/src/validations/documentation-templates/template.schema.ts +220 -220
  280. package/src/validations/documentation-templates.schema.ts +10 -10
  281. package/src/validations/index.ts +20 -20
  282. package/src/validations/media.schema.ts +10 -10
  283. package/src/validations/notification.schema.ts +90 -90
  284. package/src/validations/patient/aesthetic-analysis.schema.ts +55 -55
  285. package/src/validations/patient/medical-info.schema.ts +125 -125
  286. package/src/validations/patient/patient-requirements.schema.ts +84 -84
  287. package/src/validations/patient/token.schema.ts +29 -29
  288. package/src/validations/patient.schema.ts +217 -217
  289. package/src/validations/practitioner.schema.ts +222 -222
  290. package/src/validations/procedure-product.schema.ts +41 -41
  291. package/src/validations/procedure.schema.ts +124 -124
  292. package/src/validations/profile-info.schema.ts +41 -41
  293. package/src/validations/reviews.schema.ts +195 -195
  294. package/src/validations/schemas.ts +104 -104
  295. package/src/validations/shared.schema.ts +78 -78
@@ -1,2200 +1,2307 @@
1
- import {
2
- collection,
3
- doc,
4
- getDoc,
5
- getDocs,
6
- query,
7
- where,
8
- updateDoc,
9
- setDoc,
10
- deleteDoc,
11
- Timestamp,
12
- serverTimestamp,
13
- DocumentData,
14
- writeBatch,
15
- arrayUnion,
16
- arrayRemove,
17
- FieldValue,
18
- orderBy,
19
- limit,
20
- startAfter,
21
- QueryConstraint,
22
- documentId,
23
- } from 'firebase/firestore';
24
- import { BaseService } from '../base.service';
25
- import {
26
- Procedure,
27
- CreateProcedureData,
28
- UpdateProcedureData,
29
- PROCEDURES_COLLECTION,
30
- ProcedureSummaryInfo,
31
- } from '../../types/procedure';
32
- import { createProcedureSchema, updateProcedureSchema } from '../../validations/procedure.schema';
33
- import { z } from 'zod';
34
- import { Auth } from 'firebase/auth';
35
- import { Firestore } from 'firebase/firestore';
36
- import { FirebaseApp } from 'firebase/app';
37
- import { Category, CATEGORIES_COLLECTION } from '../../backoffice/types/category.types';
38
- import { Subcategory, SUBCATEGORIES_COLLECTION } from '../../backoffice/types/subcategory.types';
39
- import { Technology, TECHNOLOGIES_COLLECTION } from '../../backoffice/types/technology.types';
40
- import { Product, PRODUCTS_COLLECTION } from '../../backoffice/types/product.types';
41
- import { CategoryService } from '../../backoffice/services/category.service';
42
- import { SubcategoryService } from '../../backoffice/services/subcategory.service';
43
- import { TechnologyService } from '../../backoffice/services/technology.service';
44
- import { ProductService } from '../../backoffice/services/product.service';
45
- import { Practitioner, PRACTITIONERS_COLLECTION } from '../../types/practitioner';
46
- import {
47
- CertificationLevel,
48
- CertificationSpecialty,
49
- ProcedureFamily,
50
- type TreatmentBenefitDynamic,
51
- } from '../../backoffice/types';
52
- import { Currency, PricingMeasure } from '../../backoffice/types/static/pricing.types';
53
- import { Clinic, CLINICS_COLLECTION } from '../../types/clinic';
54
- import { ProcedureReviewInfo } from '../../types/reviews';
55
- import { distanceBetween, geohashQueryBounds } from 'geofire-common';
56
- import { MediaService, MediaAccessLevel } from '../media/media.service';
57
- import type { ProcedureProduct } from '../../backoffice/types/procedure-product.types';
58
-
59
- export class ProcedureService extends BaseService {
60
- private categoryService: CategoryService;
61
- private subcategoryService: SubcategoryService;
62
- private technologyService: TechnologyService;
63
- private productService: ProductService;
64
- private mediaService: MediaService;
65
-
66
- constructor(
67
- db: Firestore,
68
- auth: Auth,
69
- app: FirebaseApp,
70
- categoryService: CategoryService,
71
- subcategoryService: SubcategoryService,
72
- technologyService: TechnologyService,
73
- productService: ProductService,
74
- mediaService: MediaService,
75
- ) {
76
- super(db, auth, app);
77
- this.categoryService = categoryService;
78
- this.subcategoryService = subcategoryService;
79
- this.technologyService = technologyService;
80
- this.productService = productService;
81
- this.mediaService = mediaService;
82
- }
83
-
84
- /**
85
- * Process media resource (string URL or File object)
86
- * @param media String URL or File object
87
- * @param ownerId Owner ID for the media (usually procedureId)
88
- * @param collectionName Collection name for organizing files
89
- * @returns URL string after processing
90
- */
91
- private async processMedia(
92
- media: string | File | Blob | null | undefined,
93
- ownerId: string,
94
- collectionName: string,
95
- ): Promise<string | null> {
96
- if (!media) return null;
97
-
98
- // If already a string URL, return it directly
99
- if (typeof media === 'string') {
100
- return media;
101
- }
102
-
103
- // If it's a File, upload it using MediaService
104
- if (media instanceof File || media instanceof Blob) {
105
- console.log(`[ProcedureService] Uploading ${collectionName} media for ${ownerId}`);
106
- const metadata = await this.mediaService.uploadMedia(
107
- media,
108
- ownerId,
109
- MediaAccessLevel.PUBLIC,
110
- collectionName,
111
- );
112
- return metadata.url;
113
- }
114
-
115
- return null;
116
- }
117
-
118
- /**
119
- * Process array of media resources (strings or Files)
120
- * @param mediaArray Array of string URLs or File objects
121
- * @param ownerId Owner ID for the media
122
- * @param collectionName Collection name for organizing files
123
- * @returns Array of URL strings after processing
124
- */
125
- private async processMediaArray(
126
- mediaArray: (string | File | Blob)[] | undefined,
127
- ownerId: string,
128
- collectionName: string,
129
- ): Promise<string[]> {
130
- if (!mediaArray || mediaArray.length === 0) return [];
131
-
132
- const result: string[] = [];
133
-
134
- for (const media of mediaArray) {
135
- const processedUrl = await this.processMedia(media, ownerId, collectionName);
136
- if (processedUrl) {
137
- result.push(processedUrl);
138
- }
139
- }
140
-
141
- return result;
142
- }
143
-
144
- /**
145
- * Transforms validated procedure product data (with productId) to ProcedureProduct objects (with full product)
146
- * @param productsMetadata Array of validated procedure product data (optional)
147
- * @param technologyId Technology ID to fetch products from
148
- * @returns Array of ProcedureProduct objects with full product information
149
- */
150
- private async transformProductsMetadata(
151
- productsMetadata: {
152
- productId: string;
153
- price: number;
154
- currency: Currency;
155
- pricingMeasure: PricingMeasure;
156
- isDefault?: boolean;
157
- }[] | undefined,
158
- technologyId: string,
159
- ): Promise<ProcedureProduct[]> {
160
- // Return empty array if no products metadata provided (for product-free procedures like consultations)
161
- if (!productsMetadata || productsMetadata.length === 0) {
162
- return [];
163
- }
164
-
165
- const transformedProducts: ProcedureProduct[] = [];
166
-
167
- for (const productData of productsMetadata) {
168
- // Fetch the full product object
169
- const product = await this.productService.getById(technologyId, productData.productId);
170
- if (!product) {
171
- throw new Error(
172
- `Product with ID ${productData.productId} not found for technology ${technologyId}`,
173
- );
174
- }
175
-
176
- // Transform to ProcedureProduct
177
- transformedProducts.push({
178
- product,
179
- price: productData.price,
180
- currency: productData.currency,
181
- pricingMeasure: productData.pricingMeasure,
182
- isDefault: productData.isDefault,
183
- });
184
- }
185
-
186
- return transformedProducts;
187
- }
188
-
189
- /**
190
- * Creates a new procedure
191
- * @param data - The data for creating a new procedure
192
- * @returns The created procedure
193
- */
194
- async createProcedure(data: CreateProcedureData): Promise<Procedure> {
195
- const validatedData = createProcedureSchema.parse(data);
196
-
197
- // Check if this is a product-free procedure (e.g., free consultation)
198
- const isProductFree = !validatedData.productId;
199
-
200
- // Generate procedure ID first so we can use it for media uploads
201
- const procedureId = this.generateId();
202
-
203
- // Get references to related entities (Category, Subcategory, Technology, and optionally Product)
204
- const baseEntitiesPromises: Promise<Category | Subcategory | Technology | Product | null>[] = [
205
- this.categoryService.getById(validatedData.categoryId),
206
- this.subcategoryService.getById(validatedData.categoryId, validatedData.subcategoryId),
207
- this.technologyService.getById(validatedData.technologyId),
208
- ];
209
-
210
- // Only fetch product if productId is provided
211
- if (!isProductFree) {
212
- baseEntitiesPromises.push(
213
- this.productService.getById(validatedData.technologyId, validatedData.productId!)
214
- );
215
- }
216
-
217
- const results = await Promise.all(baseEntitiesPromises);
218
- const category = results[0] as Category | null;
219
- const subcategory = results[1] as Subcategory | null;
220
- const technology = results[2] as Technology | null;
221
- const product = isProductFree ? undefined : ((results[3] as Product | null) || undefined);
222
-
223
- if (!category || !subcategory || !technology) {
224
- throw new Error('One or more required base entities not found');
225
- }
226
-
227
- // For regular procedures, validate product exists
228
- if (!isProductFree && !product) {
229
- throw new Error('Product not found for regular procedure');
230
- }
231
-
232
- // Get clinic and practitioner information for aggregation
233
- const clinicRef = doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId);
234
- const clinicSnapshot = await getDoc(clinicRef);
235
- if (!clinicSnapshot.exists()) {
236
- throw new Error(`Clinic with ID ${validatedData.clinicBranchId} not found`);
237
- }
238
- const clinic = clinicSnapshot.data() as Clinic; // Assert type
239
-
240
- const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, validatedData.practitionerId);
241
- const practitionerSnapshot = await getDoc(practitionerRef);
242
- if (!practitionerSnapshot.exists()) {
243
- throw new Error(`Practitioner with ID ${validatedData.practitionerId} not found`);
244
- }
245
- const practitioner = practitionerSnapshot.data() as Practitioner; // Assert type
246
-
247
- // Check if practitioner already has a procedure with the same technology ID in this clinic branch
248
- const existingProceduresQuery = query(
249
- collection(this.db, PROCEDURES_COLLECTION),
250
- where('practitionerId', '==', validatedData.practitionerId),
251
- where('clinicBranchId', '==', validatedData.clinicBranchId),
252
- where('isActive', '==', true)
253
- );
254
- const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
255
- const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
256
-
257
- const hasSameTechnology = existingProcedures.some(
258
- proc => proc.technology?.id === validatedData.technologyId
259
- );
260
- if (hasSameTechnology) {
261
- throw new Error(
262
- `Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} already has a procedure with technology "${technology?.name || validatedData.technologyId}" in this clinic branch`
263
- );
264
- }
265
-
266
- // Process photos if provided
267
- let processedPhotos: string[] = [];
268
- if (validatedData.photos && validatedData.photos.length > 0) {
269
- processedPhotos = await this.processMediaArray(
270
- validatedData.photos,
271
- procedureId,
272
- 'procedure-photos',
273
- );
274
- }
275
-
276
- // If no photos provided and technology has a photoTemplate, use it as default photo
277
- if (processedPhotos.length === 0 && technology.photoTemplate) {
278
- console.log(`[ProcedureService] Using technology photoTemplate as default photo: ${technology.photoTemplate}`);
279
- const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
280
- if (photoTemplateUrl) {
281
- processedPhotos.push(photoTemplateUrl);
282
- } else {
283
- console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
284
- }
285
- }
286
-
287
- // Transform productsMetadata from validation format to ProcedureProduct format
288
- const transformedProductsMetadata = await this.transformProductsMetadata(
289
- validatedData.productsMetadata,
290
- validatedData.technologyId,
291
- );
292
-
293
- // Create aggregated clinic info for the procedure document
294
- const clinicInfo = {
295
- id: clinicSnapshot.id,
296
- name: clinic.name,
297
- description: clinic.description || '',
298
- featuredPhoto:
299
- clinic.featuredPhotos && clinic.featuredPhotos.length > 0
300
- ? typeof clinic.featuredPhotos[0] === 'string'
301
- ? clinic.featuredPhotos[0]
302
- : ''
303
- : typeof clinic.coverPhoto === 'string'
304
- ? clinic.coverPhoto
305
- : '',
306
- location: clinic.location,
307
- contactInfo: clinic.contactInfo,
308
- };
309
-
310
- // Create aggregated doctor info for the procedure document
311
- const doctorInfo = {
312
- id: practitionerSnapshot.id,
313
- name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
314
- description: practitioner.basicInfo.bio || '',
315
- photo:
316
- typeof practitioner.basicInfo.profileImageUrl === 'string'
317
- ? practitioner.basicInfo.profileImageUrl
318
- : '', // Default to empty string if not a processed URL
319
- rating: practitioner.reviewInfo?.averageRating || 0,
320
- services: practitioner.procedures || [],
321
- };
322
-
323
- // Create the procedure object
324
- const { productsMetadata: _, productId: __, photos: ___, ...validatedDataWithoutProductsMetadata } = validatedData;
325
- const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
326
- id: procedureId,
327
- ...validatedDataWithoutProductsMetadata,
328
- // Ensure nameLower is always set even if omitted by client
329
- nameLower: (validatedData as any).nameLower || validatedData.name.toLowerCase(),
330
- photos: processedPhotos,
331
- category, // Embed full objects
332
- subcategory,
333
- technology,
334
- ...(product && { product }), // Only include product field if it exists (Firestore doesn't allow undefined)
335
- productsMetadata: transformedProductsMetadata, // Use transformed data, not original
336
- blockingConditions: technology.blockingConditions,
337
- contraindications: technology.contraindications || [],
338
- contraindicationIds: technology.contraindications?.map(c => c.id) || [],
339
- treatmentBenefits: technology.benefits,
340
- treatmentBenefitIds: Array.isArray(technology.benefits)
341
- ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
342
- : [],
343
- preRequirements: technology.requirements.pre,
344
- postRequirements: technology.requirements.post,
345
- certificationRequirement: technology.certificationRequirement,
346
- documentationTemplates: technology?.documentationTemplates || [],
347
- clinicInfo, // Embed aggregated info
348
- doctorInfo, // Embed aggregated info
349
- reviewInfo: {
350
- // Default empty reviews
351
- totalReviews: 0,
352
- averageRating: 0,
353
- effectivenessOfTreatment: 0,
354
- outcomeExplanation: 0,
355
- painManagement: 0,
356
- followUpCare: 0,
357
- valueForMoney: 0,
358
- recommendationPercentage: 0,
359
- },
360
- isActive: true, // Default to active
361
- };
362
-
363
- // 🔥 DEBUG: Find undefined fields before writing to Firestore
364
- console.log('🔥🔥🔥 CREATE PROCEDURE - Processing procedure:', procedureId);
365
- console.log('🔥🔥🔥 FULL PROCEDURE OBJECT:', JSON.stringify(newProcedure, null, 2));
366
-
367
- const undefinedFields: string[] = [];
368
- Object.entries(newProcedure).forEach(([key, value]) => {
369
- if (value === undefined) {
370
- undefinedFields.push(key);
371
- }
372
- });
373
- if (undefinedFields.length > 0) {
374
- console.error('🔥🔥🔥 UNDEFINED FIELDS DETECTED:', undefinedFields);
375
- throw new Error(`Cannot write procedure with undefined fields: ${undefinedFields.join(', ')}`);
376
- }
377
- console.log('🔥🔥🔥 NO UNDEFINED FIELDS - Proceeding with setDoc');
378
-
379
- // Create the procedure document
380
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
381
- await setDoc(procedureRef, {
382
- ...newProcedure,
383
- createdAt: serverTimestamp(),
384
- updatedAt: serverTimestamp(),
385
- });
386
-
387
- // Return the created procedure (fetch again to get server timestamps)
388
- const savedDoc = await getDoc(procedureRef);
389
- return savedDoc.data() as Procedure;
390
- }
391
-
392
- /**
393
- * Validates if a practitioner can perform a procedure based on certification requirements.
394
- *
395
- * @param procedure - The procedure to check
396
- * @param practitioner - The practitioner to validate
397
- * @returns true if practitioner can perform the procedure, false otherwise
398
- */
399
- canPractitionerPerformProcedure(procedure: Procedure, practitioner: Practitioner): boolean {
400
- if (!practitioner.certification) {
401
- return false;
402
- }
403
-
404
- const requiredCert = procedure.certificationRequirement;
405
- const practitionerCert = practitioner.certification;
406
-
407
- // Check certification level
408
- const levelOrder = [
409
- 'aesthetician',
410
- 'nurse_assistant',
411
- 'nurse',
412
- 'nurse_practitioner',
413
- 'physician_assistant',
414
- 'doctor',
415
- 'specialist',
416
- 'plastic_surgeon',
417
- ];
418
-
419
- const practitionerLevelIndex = levelOrder.indexOf(practitionerCert.level);
420
- const requiredLevelIndex = levelOrder.indexOf(requiredCert.minimumLevel);
421
-
422
- if (practitionerLevelIndex < requiredLevelIndex) {
423
- return false;
424
- }
425
-
426
- // Check required specialties
427
- const requiredSpecialties = requiredCert.requiredSpecialties || [];
428
- if (requiredSpecialties.length > 0) {
429
- const practitionerSpecialties = practitionerCert.specialties || [];
430
- const hasAllRequired = requiredSpecialties.every(specialty =>
431
- practitionerSpecialties.includes(specialty)
432
- );
433
- if (!hasAllRequired) {
434
- return false;
435
- }
436
- }
437
-
438
- return true;
439
- }
440
-
441
- /**
442
- * Clones an existing procedure for a target practitioner.
443
- * This creates a new procedure document with the same data as the source procedure,
444
- * but linked to the target practitioner.
445
- *
446
- * @param sourceProcedureId - The ID of the procedure to clone
447
- * @param targetPractitionerId - The ID of the practitioner to assign the cloned procedure to
448
- * @param overrides - Optional overrides for the new procedure (e.g. price, duration, isActive)
449
- * @returns The newly created procedure
450
- */
451
- async cloneProcedureForPractitioner(
452
- sourceProcedureId: string,
453
- targetPractitionerId: string,
454
- overrides?: Partial<CreateProcedureData> & { isActive?: boolean }
455
- ): Promise<Procedure> {
456
- // 1. Fetch source procedure
457
- const sourceProcedure = await this.getProcedure(sourceProcedureId);
458
- if (!sourceProcedure) {
459
- throw new Error(`Source procedure with ID ${sourceProcedureId} not found`);
460
- }
461
-
462
- // 2. Fetch target practitioner
463
- const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, targetPractitionerId);
464
- const practitionerSnapshot = await getDoc(practitionerRef);
465
- if (!practitionerSnapshot.exists()) {
466
- throw new Error(`Target practitioner with ID ${targetPractitionerId} not found`);
467
- }
468
- const practitioner = practitionerSnapshot.data() as Practitioner;
469
-
470
- // 3. Validate certification
471
- if (!this.canPractitionerPerformProcedure(sourceProcedure, practitioner)) {
472
- throw new Error(
473
- `Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} does not meet the certification requirements for this procedure`
474
- );
475
- }
476
-
477
- // 4. Check if practitioner already has a procedure with the same technology ID in this clinic branch
478
- const existingProceduresQuery = query(
479
- collection(this.db, PROCEDURES_COLLECTION),
480
- where('practitionerId', '==', targetPractitionerId),
481
- where('clinicBranchId', '==', sourceProcedure.clinicBranchId),
482
- where('isActive', '==', true)
483
- );
484
- const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
485
- const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
486
-
487
- const hasSameTechnology = existingProcedures.some(
488
- proc => proc.technology?.id === sourceProcedure.technology?.id
489
- );
490
- if (hasSameTechnology) {
491
- throw new Error(
492
- `Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} already has a procedure with technology "${sourceProcedure.technology?.name || sourceProcedure.technology?.id}" in this clinic branch`
493
- );
494
- }
495
-
496
- // 5. Prepare data for new procedure
497
- const newProcedureId = this.generateId();
498
-
499
- // Create aggregated doctor info for the new procedure
500
- const doctorInfo = {
501
- id: practitioner.id,
502
- name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
503
- description: practitioner.basicInfo.bio || '',
504
- photo:
505
- typeof practitioner.basicInfo.profileImageUrl === 'string'
506
- ? practitioner.basicInfo.profileImageUrl
507
- : '',
508
- rating: practitioner.reviewInfo?.averageRating || 0,
509
- services: practitioner.procedures || [],
510
- };
511
-
512
- // Construct the new procedure object
513
- // We copy everything from source, but override specific fields
514
- const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
515
- ...sourceProcedure,
516
- id: newProcedureId,
517
- practitionerId: targetPractitionerId,
518
- doctorInfo, // Link to new doctor
519
-
520
- // Reset review info for the new procedure
521
- reviewInfo: {
522
- totalReviews: 0,
523
- averageRating: 0,
524
- effectivenessOfTreatment: 0,
525
- outcomeExplanation: 0,
526
- painManagement: 0,
527
- followUpCare: 0,
528
- valueForMoney: 0,
529
- recommendationPercentage: 0,
530
- },
531
-
532
- // Apply any overrides if provided
533
- ...(overrides?.price !== undefined && { price: overrides.price }),
534
- ...(overrides?.duration !== undefined && { duration: overrides.duration }),
535
- ...(overrides?.description !== undefined && { description: overrides.description }),
536
-
537
- // Ensure it's active by default unless specified otherwise
538
- isActive: overrides?.isActive !== undefined ? overrides.isActive : true,
539
- };
540
-
541
- // 6. Save to Firestore
542
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, newProcedureId);
543
- await setDoc(procedureRef, {
544
- ...newProcedure,
545
- createdAt: serverTimestamp(),
546
- updatedAt: serverTimestamp(),
547
- });
548
-
549
- // 7. Return the new procedure
550
- const savedDoc = await getDoc(procedureRef);
551
- return savedDoc.data() as Procedure;
552
- }
553
-
554
- /**
555
- * Clones an existing procedure for multiple target practitioners.
556
- * This creates new procedure documents with the same data as the source procedure,
557
- * but linked to each target practitioner.
558
- *
559
- * @param sourceProcedureId - The ID of the procedure to clone
560
- * @param targetPractitionerIds - Array of practitioner IDs to assign the cloned procedure to
561
- * @param overrides - Optional overrides for the new procedures (e.g. price, duration, isActive)
562
- * @returns Array of newly created procedures
563
- */
564
- async bulkCloneProcedureForPractitioners(
565
- sourceProcedureId: string,
566
- targetPractitionerIds: string[],
567
- overrides?: Partial<CreateProcedureData> & { isActive?: boolean }
568
- ): Promise<Procedure[]> {
569
- if (!targetPractitionerIds || targetPractitionerIds.length === 0) {
570
- throw new Error('At least one target practitioner ID is required');
571
- }
572
-
573
- // 1. Fetch source procedure
574
- const sourceProcedure = await this.getProcedure(sourceProcedureId);
575
- if (!sourceProcedure) {
576
- throw new Error(`Source procedure with ID ${sourceProcedureId} not found`);
577
- }
578
-
579
- // 2. Fetch all target practitioners
580
- const practitionerPromises = targetPractitionerIds.map(id =>
581
- getDoc(doc(this.db, PRACTITIONERS_COLLECTION, id))
582
- );
583
- const practitionerSnapshots = await Promise.all(practitionerPromises);
584
-
585
- // 3. Validate all practitioners exist, can perform the procedure, and don't already have the same technology
586
- const practitioners: Practitioner[] = [];
587
- const sourceTechnologyId = sourceProcedure.technology?.id;
588
-
589
- for (let i = 0; i < practitionerSnapshots.length; i++) {
590
- const snapshot = practitionerSnapshots[i];
591
- if (!snapshot.exists()) {
592
- throw new Error(`Target practitioner with ID ${targetPractitionerIds[i]} not found`);
593
- }
594
- const practitioner = snapshot.data() as Practitioner;
595
-
596
- if (!this.canPractitionerPerformProcedure(sourceProcedure, practitioner)) {
597
- throw new Error(
598
- `Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} does not meet the certification requirements for this procedure`
599
- );
600
- }
601
-
602
- // Check if practitioner already has a procedure with the same technology ID in this clinic branch
603
- const existingProceduresQuery = query(
604
- collection(this.db, PROCEDURES_COLLECTION),
605
- where('practitionerId', '==', practitioner.id),
606
- where('clinicBranchId', '==', sourceProcedure.clinicBranchId),
607
- where('isActive', '==', true)
608
- );
609
- const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
610
- const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
611
-
612
- const hasSameTechnology = existingProcedures.some(
613
- proc => proc.technology?.id === sourceTechnologyId
614
- );
615
- if (hasSameTechnology) {
616
- throw new Error(
617
- `Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} already has a procedure with technology "${sourceProcedure.technology?.name || sourceTechnologyId}" in this clinic branch`
618
- );
619
- }
620
-
621
- practitioners.push(practitioner);
622
- }
623
-
624
- // 4. Create procedures in batch
625
- const batch = writeBatch(this.db);
626
- const newProcedures: Omit<Procedure, 'createdAt' | 'updatedAt'>[] = [];
627
-
628
- for (const practitioner of practitioners) {
629
- const newProcedureId = this.generateId();
630
-
631
- // Create aggregated doctor info for the new procedure
632
- const doctorInfo = {
633
- id: practitioner.id,
634
- name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
635
- description: practitioner.basicInfo.bio || '',
636
- photo:
637
- typeof practitioner.basicInfo.profileImageUrl === 'string'
638
- ? practitioner.basicInfo.profileImageUrl
639
- : '',
640
- rating: practitioner.reviewInfo?.averageRating || 0,
641
- services: practitioner.procedures || [],
642
- };
643
-
644
- // Construct the new procedure object
645
- const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
646
- ...sourceProcedure,
647
- id: newProcedureId,
648
- practitionerId: practitioner.id,
649
- doctorInfo,
650
-
651
- // Reset review info for the new procedure
652
- reviewInfo: {
653
- totalReviews: 0,
654
- averageRating: 0,
655
- effectivenessOfTreatment: 0,
656
- outcomeExplanation: 0,
657
- painManagement: 0,
658
- followUpCare: 0,
659
- valueForMoney: 0,
660
- recommendationPercentage: 0,
661
- },
662
-
663
- // Apply any overrides if provided
664
- ...(overrides?.price !== undefined && { price: overrides.price }),
665
- ...(overrides?.duration !== undefined && { duration: overrides.duration }),
666
- ...(overrides?.description !== undefined && { description: overrides.description }),
667
-
668
- // Ensure it's active by default unless specified otherwise
669
- isActive: overrides?.isActive !== undefined ? overrides.isActive : true,
670
- };
671
-
672
- newProcedures.push(newProcedure);
673
-
674
- // Add to batch
675
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, newProcedureId);
676
- batch.set(procedureRef, {
677
- ...newProcedure,
678
- createdAt: serverTimestamp(),
679
- updatedAt: serverTimestamp(),
680
- });
681
- }
682
-
683
- // 5. Commit batch
684
- await batch.commit();
685
-
686
- // 6. Fetch and return the created procedures
687
- const createdProcedures = await Promise.all(
688
- newProcedures.map(p => this.getProcedure(p.id))
689
- );
690
-
691
- return createdProcedures.filter((p): p is Procedure => p !== null);
692
- }
693
-
694
- /**
695
- * Creates multiple procedures for a list of practitioners based on common data.
696
- * This method is optimized for bulk creation to reduce database reads and writes.
697
- *
698
- * @param baseData - The base data for the procedures to be created, omitting the practitionerId.
699
- * @param practitionerIds - An array of practitioner IDs for whom the procedures will be created.
700
- * @returns A promise that resolves to an array of the newly created procedures.
701
- */
702
- async bulkCreateProcedures(
703
- baseData: Omit<CreateProcedureData, 'practitionerId'>,
704
- practitionerIds: string[],
705
- ): Promise<Procedure[]> {
706
- // 1. Validation
707
- if (!practitionerIds || practitionerIds.length === 0) {
708
- throw new Error('Practitioner IDs array cannot be empty.');
709
- }
710
-
711
- // Check if this is a product-free procedure
712
- const isProductFree = !baseData.productId;
713
-
714
- // Add a dummy practitionerId for the validation schema to pass
715
- const validationData = { ...baseData, practitionerId: practitionerIds[0] };
716
- const validatedData = createProcedureSchema.parse(validationData);
717
-
718
- // 2. Fetch common data once to avoid redundant reads
719
- const baseEntitiesPromises: Promise<Category | Subcategory | Technology | Product | null>[] = [
720
- this.categoryService.getById(validatedData.categoryId),
721
- this.subcategoryService.getById(validatedData.categoryId, validatedData.subcategoryId),
722
- this.technologyService.getById(validatedData.technologyId),
723
- ];
724
-
725
- // Only fetch product if productId is provided
726
- if (!isProductFree) {
727
- baseEntitiesPromises.push(
728
- this.productService.getById(validatedData.technologyId, validatedData.productId!)
729
- );
730
- }
731
-
732
- // Fetch clinic separately to maintain type safety
733
- const clinicSnapshotPromise = getDoc(doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId));
734
-
735
- const [baseResults, clinicSnapshot] = await Promise.all([
736
- Promise.all(baseEntitiesPromises),
737
- clinicSnapshotPromise
738
- ]);
739
-
740
- const category = baseResults[0] as Category | null;
741
- const subcategory = baseResults[1] as Subcategory | null;
742
- const technology = baseResults[2] as Technology | null;
743
- const product = isProductFree ? undefined : ((baseResults[3] as Product | null) || undefined);
744
-
745
- if (!category || !subcategory || !technology) {
746
- throw new Error('One or more required base entities not found');
747
- }
748
-
749
- // For regular procedures, validate product exists
750
- if (!isProductFree && !product) {
751
- throw new Error('Product not found for regular procedure');
752
- }
753
-
754
- if (!clinicSnapshot || !clinicSnapshot.exists()) {
755
- throw new Error(`Clinic with ID ${validatedData.clinicBranchId} not found`);
756
- }
757
- const clinic = clinicSnapshot.data() as Clinic;
758
-
759
- // 3. Handle media uploads once for efficiency
760
- let processedPhotos: string[] = [];
761
- if (validatedData.photos && validatedData.photos.length > 0) {
762
- const batchId = this.generateId(); // Use a single ID for all media in this batch
763
- processedPhotos = await this.processMediaArray(
764
- validatedData.photos,
765
- batchId,
766
- 'procedure-photos-batch',
767
- );
768
- }
769
-
770
- // If no photos provided and technology has a photoTemplate, use it as default photo
771
- if (processedPhotos.length === 0 && technology.photoTemplate) {
772
- console.log(`[ProcedureService] Using technology photoTemplate as default photo for bulk create: ${technology.photoTemplate}`);
773
- const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
774
- if (photoTemplateUrl) {
775
- processedPhotos.push(photoTemplateUrl);
776
- } else {
777
- console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
778
- }
779
- }
780
-
781
- // Transform productsMetadata from validation format to ProcedureProduct format
782
- const transformedProductsMetadata = await this.transformProductsMetadata(
783
- validatedData.productsMetadata,
784
- validatedData.technologyId,
785
- );
786
-
787
- // 4. Fetch all practitioner data efficiently
788
- const practitionersMap = new Map<string, Practitioner>();
789
- // Use 'in' query in chunks of 30, as this is the Firestore limit
790
- for (let i = 0; i < practitionerIds.length; i += 30) {
791
- const chunk = practitionerIds.slice(i, i + 30);
792
- const practitionersQuery = query(
793
- collection(this.db, PRACTITIONERS_COLLECTION),
794
- where(documentId(), 'in', chunk),
795
- );
796
- const practitionersSnapshot = await getDocs(practitionersQuery);
797
- practitionersSnapshot.docs.forEach(doc => {
798
- practitionersMap.set(doc.id, doc.data() as Practitioner);
799
- });
800
- }
801
-
802
- // Verify all practitioners were found
803
- if (practitionersMap.size !== practitionerIds.length) {
804
- const foundIds = Array.from(practitionersMap.keys());
805
- const notFoundIds = practitionerIds.filter(id => !foundIds.includes(id));
806
- throw new Error(`The following practitioners were not found: ${notFoundIds.join(', ')}`);
807
- }
808
-
809
- // 5. Check for duplicates across all practitioners before creating any procedures
810
- const duplicatePractitioners: string[] = [];
811
- const duplicateChecks = await Promise.all(
812
- practitionerIds.map(async (practitionerId) => {
813
- const existingProceduresQuery = query(
814
- collection(this.db, PROCEDURES_COLLECTION),
815
- where('practitionerId', '==', practitionerId),
816
- where('clinicBranchId', '==', validatedData.clinicBranchId),
817
- where('isActive', '==', true)
818
- );
819
- const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
820
- const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
821
-
822
- const hasSameTechnology = existingProcedures.some(
823
- proc => proc.technology?.id === validatedData.technologyId
824
- );
825
-
826
- return { practitionerId, hasSameTechnology };
827
- })
828
- );
829
-
830
- // Collect all practitioners with duplicates
831
- duplicateChecks.forEach(({ practitionerId, hasSameTechnology }) => {
832
- if (hasSameTechnology) {
833
- duplicatePractitioners.push(practitionerId);
834
- }
835
- });
836
-
837
- // If any duplicates found, throw error listing all of them
838
- if (duplicatePractitioners.length > 0) {
839
- const duplicateNames = duplicatePractitioners
840
- .map(id => {
841
- const practitioner = practitionersMap.get(id)!;
842
- return `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`;
843
- })
844
- .join(', ');
845
-
846
- throw new Error(
847
- `The following practitioner(s) already have a procedure with technology "${technology?.name || validatedData.technologyId}" in this clinic branch: ${duplicateNames}. Please remove them from the selection and try again.`
848
- );
849
- }
850
-
851
- // 6. Use a Firestore batch for atomic creation
852
- const batch = writeBatch(this.db);
853
- const createdProcedureIds: string[] = [];
854
- const clinicInfo = {
855
- id: clinicSnapshot.id,
856
- name: clinic.name,
857
- description: clinic.description || '',
858
- featuredPhoto:
859
- clinic.featuredPhotos && clinic.featuredPhotos.length > 0
860
- ? typeof clinic.featuredPhotos[0] === 'string'
861
- ? clinic.featuredPhotos[0]
862
- : ''
863
- : typeof clinic.coverPhoto === 'string'
864
- ? clinic.coverPhoto
865
- : '',
866
- location: clinic.location,
867
- contactInfo: clinic.contactInfo,
868
- };
869
-
870
- for (const practitionerId of practitionerIds) {
871
- const practitioner = practitionersMap.get(practitionerId)!;
872
-
873
- const doctorInfo = {
874
- id: practitioner.id,
875
- name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
876
- description: practitioner.basicInfo.bio || '',
877
- photo:
878
- typeof practitioner.basicInfo.profileImageUrl === 'string'
879
- ? practitioner.basicInfo.profileImageUrl
880
- : '',
881
- rating: practitioner.reviewInfo?.averageRating || 0,
882
- services: practitioner.procedures || [],
883
- };
884
-
885
- const procedureId = this.generateId();
886
- createdProcedureIds.push(procedureId);
887
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
888
-
889
- // Construct the new procedure, reusing common data
890
- const { productsMetadata: _, productId: __, photos: ___, ...validatedDataWithoutProductsMetadata } = validatedData;
891
- const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
892
- id: procedureId,
893
- ...validatedDataWithoutProductsMetadata,
894
- nameLower: (validatedData as any).nameLower || validatedData.name.toLowerCase(),
895
- practitionerId: practitionerId, // Override practitionerId with the correct one
896
- photos: processedPhotos,
897
- category,
898
- subcategory,
899
- technology,
900
- ...(product && { product }), // Only include product field if it exists (Firestore doesn't allow undefined)
901
- productsMetadata: transformedProductsMetadata, // Use transformed data, not original
902
- blockingConditions: technology.blockingConditions,
903
- contraindications: technology.contraindications || [],
904
- contraindicationIds: technology.contraindications?.map(c => c.id) || [],
905
- treatmentBenefits: technology.benefits,
906
- treatmentBenefitIds: Array.isArray(technology.benefits)
907
- ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
908
- : [],
909
- preRequirements: technology.requirements.pre,
910
- postRequirements: technology.requirements.post,
911
- certificationRequirement: technology.certificationRequirement,
912
- documentationTemplates: technology?.documentationTemplates || [],
913
- clinicInfo,
914
- doctorInfo, // Set specific doctor info
915
- reviewInfo: {
916
- totalReviews: 0,
917
- averageRating: 0,
918
- effectivenessOfTreatment: 0,
919
- outcomeExplanation: 0,
920
- painManagement: 0,
921
- followUpCare: 0,
922
- valueForMoney: 0,
923
- recommendationPercentage: 0,
924
- },
925
- isActive: true,
926
- };
927
-
928
- // 🔥 DEBUG: Find undefined fields before writing to Firestore
929
- console.log('🔥🔥🔥 BULK CREATE - Processing procedure:', procedureId, 'for practitioner:', practitionerId);
930
- console.log('🔥🔥🔥 FULL PROCEDURE OBJECT:', JSON.stringify(newProcedure, null, 2));
931
-
932
- const undefinedFields: string[] = [];
933
- Object.entries(newProcedure).forEach(([key, value]) => {
934
- if (value === undefined) {
935
- undefinedFields.push(key);
936
- }
937
- });
938
- if (undefinedFields.length > 0) {
939
- console.error('🔥🔥🔥 UNDEFINED FIELDS DETECTED:', undefinedFields);
940
- throw new Error(`Cannot write procedure with undefined fields: ${undefinedFields.join(', ')}`);
941
- }
942
- console.log('🔥🔥🔥 NO UNDEFINED FIELDS - Proceeding with batch.set');
943
-
944
- batch.set(procedureRef, {
945
- ...newProcedure,
946
- createdAt: serverTimestamp(),
947
- updatedAt: serverTimestamp(),
948
- });
949
- }
950
-
951
- // 7. Commit the atomic batch write
952
- await batch.commit();
953
-
954
- // 8. Fetch and return the newly created procedures
955
- const fetchedProcedures: Procedure[] = [];
956
- for (let i = 0; i < createdProcedureIds.length; i += 30) {
957
- const chunk = createdProcedureIds.slice(i, i + 30);
958
- const q = query(collection(this.db, PROCEDURES_COLLECTION), where(documentId(), 'in', chunk));
959
- const snapshot = await getDocs(q);
960
- snapshot.forEach(doc => {
961
- fetchedProcedures.push(doc.data() as Procedure);
962
- });
963
- }
964
-
965
- return fetchedProcedures;
966
- }
967
-
968
- /**
969
- * Gets a procedure by ID
970
- * @param id - The ID of the procedure to get
971
- * @returns The procedure if found, null otherwise
972
- */
973
- async getProcedure(id: string): Promise<Procedure | null> {
974
- const docRef = doc(this.db, PROCEDURES_COLLECTION, id);
975
- const docSnap = await getDoc(docRef);
976
-
977
- if (!docSnap.exists()) {
978
- return null;
979
- }
980
-
981
- return docSnap.data() as Procedure;
982
- }
983
-
984
- /**
985
- * Gets all procedures for a clinic branch
986
- * @param clinicBranchId - The ID of the clinic branch
987
- * @returns List of procedures
988
- */
989
- async getProceduresByClinicBranch(clinicBranchId: string): Promise<Procedure[]> {
990
- const q = query(
991
- collection(this.db, PROCEDURES_COLLECTION),
992
- where('clinicBranchId', '==', clinicBranchId),
993
- where('isActive', '==', true),
994
- );
995
- const snapshot = await getDocs(q);
996
- return snapshot.docs.map(doc => doc.data() as Procedure);
997
- }
998
-
999
- /**
1000
- * Gets all procedures for a practitioner
1001
- * @param practitionerId - The ID of the practitioner
1002
- * @param clinicBranchId - Optional clinic branch ID to filter by
1003
- * @returns List of procedures
1004
- */
1005
- async getProceduresByPractitioner(practitionerId: string, clinicBranchId?: string): Promise<Procedure[]> {
1006
- const constraints: QueryConstraint[] = [
1007
- where('practitionerId', '==', practitionerId),
1008
- where('isActive', '==', true),
1009
- ];
1010
-
1011
- if (clinicBranchId) {
1012
- constraints.push(where('clinicBranchId', '==', clinicBranchId));
1013
- }
1014
-
1015
- const q = query(
1016
- collection(this.db, PROCEDURES_COLLECTION),
1017
- ...constraints
1018
- );
1019
- const snapshot = await getDocs(q);
1020
- return snapshot.docs.map(doc => doc.data() as Procedure);
1021
- }
1022
-
1023
- /**
1024
- * Gets all inactive procedures for a practitioner
1025
- * @param practitionerId - The ID of the practitioner
1026
- * @returns List of inactive procedures
1027
- */
1028
- async getInactiveProceduresByPractitioner(practitionerId: string): Promise<Procedure[]> {
1029
- const q = query(
1030
- collection(this.db, PROCEDURES_COLLECTION),
1031
- where('practitionerId', '==', practitionerId),
1032
- where('isActive', '==', false),
1033
- );
1034
- const snapshot = await getDocs(q);
1035
- return snapshot.docs.map(doc => doc.data() as Procedure);
1036
- }
1037
-
1038
- /**
1039
- * Updates a procedure
1040
- * @param id - The ID of the procedure to update
1041
- * @param data - The data to update the procedure with
1042
- * @returns The updated procedure
1043
- */
1044
- async updateProcedure(id: string, data: UpdateProcedureData): Promise<Procedure> {
1045
- const validatedData = updateProcedureSchema.parse(data);
1046
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
1047
- const procedureSnapshot = await getDoc(procedureRef);
1048
-
1049
- if (!procedureSnapshot.exists()) {
1050
- throw new Error(`Procedure with ID ${id} not found`);
1051
- }
1052
-
1053
- const existingProcedure = procedureSnapshot.data() as Procedure;
1054
- let updatedProcedureData: Partial<Procedure> = {};
1055
-
1056
- // Copy validated simple fields
1057
- if (validatedData.name !== undefined) updatedProcedureData.name = validatedData.name;
1058
- if (validatedData.description !== undefined)
1059
- updatedProcedureData.description = validatedData.description;
1060
- if (validatedData.price !== undefined) updatedProcedureData.price = validatedData.price;
1061
- if (validatedData.currency !== undefined)
1062
- updatedProcedureData.currency = validatedData.currency;
1063
- if (validatedData.pricingMeasure !== undefined)
1064
- updatedProcedureData.pricingMeasure = validatedData.pricingMeasure;
1065
- if (validatedData.duration !== undefined)
1066
- updatedProcedureData.duration = validatedData.duration;
1067
- if (validatedData.isActive !== undefined)
1068
- updatedProcedureData.isActive = validatedData.isActive;
1069
-
1070
- let practitionerChanged = false;
1071
- let clinicChanged = false;
1072
- const oldPractitionerId = existingProcedure.practitionerId;
1073
- const oldClinicId = existingProcedure.clinicBranchId;
1074
- let newPractitioner: Practitioner | null = null;
1075
- let newClinic: Clinic | null = null;
1076
-
1077
- // Process photos if provided
1078
- if (validatedData.photos !== undefined) {
1079
- updatedProcedureData.photos = await this.processMediaArray(
1080
- validatedData.photos,
1081
- id,
1082
- 'procedure-photos',
1083
- );
1084
- }
1085
-
1086
- // Transform productsMetadata if provided
1087
- if (validatedData.productsMetadata !== undefined) {
1088
- const technologyId = validatedData.technologyId ?? existingProcedure.technology.id;
1089
- if (!technologyId) {
1090
- throw new Error('Technology ID is required for updating products metadata');
1091
- }
1092
- updatedProcedureData.productsMetadata = await this.transformProductsMetadata(
1093
- validatedData.productsMetadata,
1094
- technologyId,
1095
- );
1096
- }
1097
-
1098
- // --- Prepare updates and fetch new related data if IDs change ---
1099
-
1100
- // Handle Practitioner Change
1101
- if (validatedData.practitionerId && validatedData.practitionerId !== oldPractitionerId) {
1102
- practitionerChanged = true;
1103
- const newPractitionerRef = doc(
1104
- this.db,
1105
- PRACTITIONERS_COLLECTION,
1106
- validatedData.practitionerId,
1107
- );
1108
- const newPractitionerSnap = await getDoc(newPractitionerRef);
1109
- if (!newPractitionerSnap.exists())
1110
- throw new Error(`New Practitioner ${validatedData.practitionerId} not found`);
1111
- newPractitioner = newPractitionerSnap.data() as Practitioner;
1112
- // Update doctorInfo within the procedure document
1113
- updatedProcedureData.doctorInfo = {
1114
- id: newPractitioner.id,
1115
- name: `${newPractitioner.basicInfo.firstName} ${newPractitioner.basicInfo.lastName}`,
1116
- description: newPractitioner.basicInfo.bio || '',
1117
- photo:
1118
- typeof newPractitioner.basicInfo.profileImageUrl === 'string'
1119
- ? newPractitioner.basicInfo.profileImageUrl
1120
- : '', // Default to empty string if not a processed URL
1121
- rating: newPractitioner.reviewInfo?.averageRating || 0,
1122
- services: newPractitioner.procedures || [],
1123
- };
1124
- }
1125
-
1126
- // Handle Clinic Change
1127
- if (validatedData.clinicBranchId && validatedData.clinicBranchId !== oldClinicId) {
1128
- clinicChanged = true;
1129
- const newClinicRef = doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId);
1130
- const newClinicSnap = await getDoc(newClinicRef);
1131
- if (!newClinicSnap.exists())
1132
- throw new Error(`New Clinic ${validatedData.clinicBranchId} not found`);
1133
- newClinic = newClinicSnap.data() as Clinic;
1134
- // Update clinicInfo within the procedure document
1135
- updatedProcedureData.clinicInfo = {
1136
- id: newClinic.id,
1137
- name: newClinic.name,
1138
- description: newClinic.description || '',
1139
- featuredPhoto:
1140
- newClinic.featuredPhotos && newClinic.featuredPhotos.length > 0
1141
- ? typeof newClinic.featuredPhotos[0] === 'string'
1142
- ? newClinic.featuredPhotos[0]
1143
- : ''
1144
- : typeof newClinic.coverPhoto === 'string'
1145
- ? newClinic.coverPhoto
1146
- : '',
1147
- location: newClinic.location,
1148
- contactInfo: newClinic.contactInfo,
1149
- };
1150
- }
1151
-
1152
- // Handle Category/Subcategory/Technology/Product Changes
1153
- let finalCategoryId = existingProcedure.category.id;
1154
- if (validatedData.name) {
1155
- updatedProcedureData.nameLower = validatedData.name.toLowerCase();
1156
- }
1157
- if (validatedData.categoryId) {
1158
- const category = await this.categoryService.getById(validatedData.categoryId);
1159
- if (!category) throw new Error(`Category ${validatedData.categoryId} not found`);
1160
- updatedProcedureData.category = category;
1161
- finalCategoryId = category.id; // Update finalCategoryId if category changed
1162
- }
1163
-
1164
- // Only fetch subcategory if its ID is provided AND we have a valid finalCategoryId
1165
- if (validatedData.subcategoryId && finalCategoryId) {
1166
- const subcategory = await this.subcategoryService.getById(
1167
- finalCategoryId,
1168
- validatedData.subcategoryId,
1169
- );
1170
- if (!subcategory)
1171
- throw new Error(
1172
- `Subcategory ${validatedData.subcategoryId} not found for category ${finalCategoryId}`,
1173
- );
1174
- updatedProcedureData.subcategory = subcategory;
1175
- } else if (validatedData.subcategoryId) {
1176
- console.warn('Attempted to update subcategory without a valid categoryId');
1177
- }
1178
-
1179
- let finalTechnologyId = existingProcedure.technology.id;
1180
- if (validatedData.technologyId) {
1181
- const technology = await this.technologyService.getById(validatedData.technologyId);
1182
- if (!technology) throw new Error(`Technology ${validatedData.technologyId} not found`);
1183
- updatedProcedureData.technology = technology;
1184
- finalTechnologyId = technology.id; // Update finalTechnologyId if technology changed
1185
- // Update related fields derived from technology
1186
- updatedProcedureData.blockingConditions = technology.blockingConditions;
1187
- updatedProcedureData.contraindications = technology.contraindications || [];
1188
- updatedProcedureData.contraindicationIds = technology.contraindications?.map(c => c.id) || [];
1189
- updatedProcedureData.treatmentBenefits = technology.benefits;
1190
- updatedProcedureData.treatmentBenefitIds = Array.isArray(technology.benefits)
1191
- ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
1192
- : [];
1193
- updatedProcedureData.preRequirements = technology.requirements.pre;
1194
- updatedProcedureData.postRequirements = technology.requirements.post;
1195
- updatedProcedureData.certificationRequirement = technology.certificationRequirement;
1196
- updatedProcedureData.documentationTemplates = technology.documentationTemplates || [];
1197
- }
1198
-
1199
- // Only fetch product if its ID is provided AND we have a valid finalTechnologyId
1200
- if (validatedData.productId && finalTechnologyId) {
1201
- const product = await this.productService.getById(finalTechnologyId, validatedData.productId);
1202
- if (!product)
1203
- throw new Error(
1204
- `Product ${validatedData.productId} not found for technology ${finalTechnologyId}`,
1205
- );
1206
- updatedProcedureData.product = product;
1207
- } else if (validatedData.productId) {
1208
- console.warn('Attempted to update product without a valid technologyId');
1209
- }
1210
-
1211
- // Update the procedure document
1212
- await updateDoc(procedureRef, {
1213
- ...updatedProcedureData,
1214
- updatedAt: serverTimestamp(),
1215
- });
1216
-
1217
- // Return the updated procedure
1218
- const updatedSnapshot = await getDoc(procedureRef);
1219
- return updatedSnapshot.data() as Procedure;
1220
- }
1221
-
1222
- /**
1223
- * Deactivates a procedure (soft delete)
1224
- * @param id - The ID of the procedure to deactivate
1225
- */
1226
- async deactivateProcedure(id: string): Promise<void> {
1227
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
1228
- const procedureSnap = await getDoc(procedureRef);
1229
- if (!procedureSnap.exists()) {
1230
- console.warn(`Procedure ${id} not found for deactivation.`);
1231
- return;
1232
- }
1233
-
1234
- // Mark procedure as inactive
1235
- await updateDoc(procedureRef, {
1236
- isActive: false,
1237
- updatedAt: serverTimestamp(),
1238
- });
1239
- }
1240
-
1241
- /**
1242
- * Deletes a procedure permanently
1243
- * @param id - The ID of the procedure to delete
1244
- * @returns A boolean indicating if the deletion was successful
1245
- */
1246
- async deleteProcedure(id: string): Promise<boolean> {
1247
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
1248
- const procedureSnapshot = await getDoc(procedureRef);
1249
-
1250
- if (!procedureSnapshot.exists()) {
1251
- // Already deleted or never existed
1252
- return false;
1253
- }
1254
-
1255
- // Delete the procedure document
1256
- await deleteDoc(procedureRef);
1257
- return true;
1258
- }
1259
-
1260
- /**
1261
- * Gets all procedures that a practitioner is certified to perform
1262
- * @param practitioner - The practitioner's profile
1263
- * @returns Object containing allowed technologies, families, categories, subcategories
1264
- */
1265
- async getAllowedTechnologies(practitioner: Practitioner): Promise<{
1266
- technologies: Technology[];
1267
- families: ProcedureFamily[];
1268
- categories: string[];
1269
- subcategories: string[];
1270
- }> {
1271
- // This logic depends on TechnologyService and remains valid
1272
- const { technologies, families, categories, subcategories } =
1273
- await this.technologyService.getAllowedTechnologies(practitioner);
1274
-
1275
- return {
1276
- technologies,
1277
- families,
1278
- categories,
1279
- subcategories,
1280
- };
1281
- }
1282
-
1283
- /**
1284
- * Gets all procedures with optional pagination
1285
- *
1286
- * @param pagination - Optional number of procedures per page (0 or undefined returns all)
1287
- * @param lastDoc - Optional last document for pagination (if continuing from a previous page)
1288
- * @returns Object containing procedures array and the last document for pagination
1289
- */
1290
- async getAllProcedures(
1291
- pagination?: number,
1292
- lastDoc?: any,
1293
- ): Promise<{ procedures: Procedure[]; lastDoc: any }> {
1294
- try {
1295
- const proceduresCollection = collection(this.db, PROCEDURES_COLLECTION);
1296
- let proceduresQuery = query(proceduresCollection);
1297
-
1298
- // Apply pagination if specified
1299
- if (pagination && pagination > 0) {
1300
- const { limit, startAfter } = await import('firebase/firestore'); // Use dynamic import if needed top-level
1301
-
1302
- if (lastDoc) {
1303
- proceduresQuery = query(
1304
- proceduresCollection,
1305
- orderBy('name'), // Use imported orderBy
1306
- startAfter(lastDoc),
1307
- limit(pagination),
1308
- );
1309
- } else {
1310
- proceduresQuery = query(proceduresCollection, orderBy('name'), limit(pagination)); // Use imported orderBy
1311
- }
1312
- } else {
1313
- proceduresQuery = query(proceduresCollection, orderBy('name')); // Use imported orderBy
1314
- }
1315
-
1316
- const proceduresSnapshot = await getDocs(proceduresQuery);
1317
- const lastVisible = proceduresSnapshot.docs[proceduresSnapshot.docs.length - 1];
1318
-
1319
- const procedures = proceduresSnapshot.docs.map(doc => {
1320
- const data = doc.data() as Procedure;
1321
- return {
1322
- ...data,
1323
- id: doc.id, // Ensure ID is present
1324
- };
1325
- });
1326
-
1327
- return {
1328
- procedures,
1329
- lastDoc: lastVisible,
1330
- };
1331
- } catch (error) {
1332
- console.error('[PROCEDURE_SERVICE] Error getting all procedures:', error);
1333
- throw error;
1334
- }
1335
- }
1336
-
1337
- /**
1338
- * Searches and filters procedures based on multiple criteria
1339
- *
1340
- * @note Frontend MORA da šalje ceo snapshot (ili barem sva polja po kojima sortiraš, npr. nameLower) kao lastDoc za paginaciju, a ne samo id!
1341
- *
1342
- * @param filters - Various filters to apply
1343
- * @param filters.nameSearch - Optional search text for procedure name
1344
- * @param filters.treatmentBenefitIds - Optional array of treatment benefits to filter by
1345
- * @param filters.procedureFamily - Optional procedure family to filter by
1346
- * @param filters.procedureCategory - Optional procedure category to filter by
1347
- * @param filters.procedureSubcategory - Optional procedure subcategory to filter by
1348
- * @param filters.procedureTechnology - Optional procedure technology to filter by
1349
- * @param filters.location - Optional location for distance-based search
1350
- * @param filters.radiusInKm - Optional radius in kilometers (required if location is provided)
1351
- * @param filters.minPrice - Optional minimum price
1352
- * @param filters.maxPrice - Optional maximum price
1353
- * @param filters.minRating - Optional minimum rating (0-5)
1354
- * @param filters.maxRating - Optional maximum rating (0-5)
1355
- * @param filters.pagination - Optional number of results per page
1356
- * @param filters.lastDoc - Optional last document for pagination
1357
- * @param filters.isActive - Optional filter for active procedures only
1358
- * @returns Filtered procedures and the last document for pagination
1359
- */
1360
- async getProceduresByFilters(filters: {
1361
- nameSearch?: string;
1362
- treatmentBenefits?: string[];
1363
- procedureFamily?: ProcedureFamily;
1364
- procedureCategory?: string;
1365
- procedureSubcategory?: string;
1366
- procedureTechnology?: string;
1367
- location?: { latitude: number; longitude: number };
1368
- radiusInKm?: number;
1369
- minPrice?: number;
1370
- maxPrice?: number;
1371
- minRating?: number;
1372
- maxRating?: number;
1373
- pagination?: number;
1374
- lastDoc?: any;
1375
- isActive?: boolean;
1376
- practitionerId?: string;
1377
- clinicId?: string;
1378
- }): Promise<{
1379
- procedures: (Procedure & { distance?: number })[];
1380
- lastDoc: any;
1381
- }> {
1382
- try {
1383
- console.log('[PROCEDURE_SERVICE] Starting procedure filtering with multiple strategies');
1384
-
1385
- // Geo query debug i validacija
1386
- if (filters.location && filters.radiusInKm) {
1387
- console.log('[PROCEDURE_SERVICE] Executing geo query:', {
1388
- location: filters.location,
1389
- radius: filters.radiusInKm,
1390
- serviceName: 'ProcedureService',
1391
- });
1392
-
1393
- // Validacija location podataka
1394
- if (!filters.location.latitude || !filters.location.longitude) {
1395
- console.warn('[PROCEDURE_SERVICE] Invalid location data:', filters.location);
1396
- filters.location = undefined;
1397
- filters.radiusInKm = undefined;
1398
- }
1399
- }
1400
-
1401
- // Handle geo queries separately (they work differently)
1402
- const isGeoQuery = filters.location && filters.radiusInKm && filters.radiusInKm > 0;
1403
- if (isGeoQuery) {
1404
- return this.handleGeoQuery(filters);
1405
- }
1406
-
1407
- // Base constraints (used in all strategies)
1408
- const getBaseConstraints = () => {
1409
- const constraints: QueryConstraint[] = [];
1410
-
1411
- // Active status filter
1412
- if (filters.isActive !== undefined) {
1413
- constraints.push(where('isActive', '==', filters.isActive));
1414
- } else {
1415
- constraints.push(where('isActive', '==', true));
1416
- }
1417
-
1418
- // Filter constraints
1419
- if (filters.procedureFamily) {
1420
- constraints.push(where('family', '==', filters.procedureFamily));
1421
- }
1422
- if (filters.procedureCategory) {
1423
- constraints.push(where('category.id', '==', filters.procedureCategory));
1424
- }
1425
- if (filters.procedureSubcategory) {
1426
- constraints.push(where('subcategory.id', '==', filters.procedureSubcategory));
1427
- }
1428
- if (filters.procedureTechnology) {
1429
- constraints.push(where('technology.id', '==', filters.procedureTechnology));
1430
- }
1431
- if (filters.practitionerId) {
1432
- constraints.push(where('practitionerId', '==', filters.practitionerId));
1433
- }
1434
- if (filters.clinicId) {
1435
- constraints.push(where('clinicBranchId', '==', filters.clinicId));
1436
- }
1437
- if (filters.minPrice !== undefined) {
1438
- constraints.push(where('price', '>=', filters.minPrice));
1439
- }
1440
- if (filters.maxPrice !== undefined) {
1441
- constraints.push(where('price', '<=', filters.maxPrice));
1442
- }
1443
- if (filters.minRating !== undefined) {
1444
- constraints.push(where('reviewInfo.averageRating', '>=', filters.minRating));
1445
- }
1446
- if (filters.maxRating !== undefined) {
1447
- constraints.push(where('reviewInfo.averageRating', '<=', filters.maxRating));
1448
- }
1449
- if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
1450
- const benefitIdsToMatch = filters.treatmentBenefits;
1451
- constraints.push(where('treatmentBenefitIds', 'array-contains-any', benefitIdsToMatch));
1452
- }
1453
-
1454
- return constraints;
1455
- };
1456
-
1457
- // Strategy 1: Try nameLower search if nameSearch exists
1458
- if (filters.nameSearch && filters.nameSearch.trim()) {
1459
- try {
1460
- console.log('[PROCEDURE_SERVICE] Strategy 1: Trying nameLower search');
1461
- const searchTerm = filters.nameSearch.trim().toLowerCase();
1462
- const constraints = getBaseConstraints();
1463
-
1464
- // Check if we have nested field filters that might conflict with orderBy
1465
- const hasNestedFilters = !!(filters.procedureTechnology || filters.procedureCategory || filters.procedureSubcategory);
1466
-
1467
- if (hasNestedFilters) {
1468
- console.log('[PROCEDURE_SERVICE] Strategy 1: Has nested filters, will apply client-side after query');
1469
- }
1470
-
1471
- constraints.push(where('nameLower', '>=', searchTerm));
1472
- constraints.push(where('nameLower', '<=', searchTerm + '\uf8ff'));
1473
- constraints.push(orderBy('nameLower'));
1474
-
1475
- if (filters.lastDoc) {
1476
- if (typeof filters.lastDoc.data === 'function') {
1477
- constraints.push(startAfter(filters.lastDoc));
1478
- } else if (Array.isArray(filters.lastDoc)) {
1479
- constraints.push(startAfter(...filters.lastDoc));
1480
- } else {
1481
- constraints.push(startAfter(filters.lastDoc));
1482
- }
1483
- }
1484
- constraints.push(limit(filters.pagination || 10));
1485
-
1486
- const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1487
- const querySnapshot = await getDocs(q);
1488
- let procedures = querySnapshot.docs.map(
1489
- doc => ({ ...doc.data(), id: doc.id } as Procedure),
1490
- );
1491
-
1492
- // Apply client-side filters for nested fields if needed
1493
- if (hasNestedFilters) {
1494
- procedures = this.applyInMemoryFilters(procedures, filters);
1495
- }
1496
-
1497
- const lastDoc =
1498
- querySnapshot.docs.length > 0
1499
- ? querySnapshot.docs[querySnapshot.docs.length - 1]
1500
- : null;
1501
-
1502
- console.log(`[PROCEDURE_SERVICE] Strategy 1 success: ${procedures.length} procedures`);
1503
-
1504
- // Fix Load More - ako je broj rezultata manji od pagination, nema više
1505
- if (procedures.length < (filters.pagination || 10)) {
1506
- return { procedures, lastDoc: null };
1507
- }
1508
- return { procedures, lastDoc };
1509
- } catch (error) {
1510
- console.log('[PROCEDURE_SERVICE] Strategy 1 failed:', error);
1511
- }
1512
- }
1513
-
1514
- // Strategy 2: Try name field search as fallback
1515
- if (filters.nameSearch && filters.nameSearch.trim()) {
1516
- try {
1517
- console.log('[PROCEDURE_SERVICE] Strategy 2: Trying name field search');
1518
- const searchTerm = filters.nameSearch.trim().toLowerCase();
1519
- const constraints = getBaseConstraints();
1520
-
1521
- // Check if we have nested field filters that might conflict with orderBy
1522
- const hasNestedFilters = !!(filters.procedureTechnology || filters.procedureCategory || filters.procedureSubcategory);
1523
-
1524
- if (hasNestedFilters) {
1525
- console.log('[PROCEDURE_SERVICE] Strategy 2: Has nested filters, will apply client-side after query');
1526
- }
1527
-
1528
- constraints.push(where('name', '>=', searchTerm));
1529
- constraints.push(where('name', '<=', searchTerm + '\uf8ff'));
1530
- constraints.push(orderBy('name'));
1531
-
1532
- if (filters.lastDoc) {
1533
- if (typeof filters.lastDoc.data === 'function') {
1534
- constraints.push(startAfter(filters.lastDoc));
1535
- } else if (Array.isArray(filters.lastDoc)) {
1536
- constraints.push(startAfter(...filters.lastDoc));
1537
- } else {
1538
- constraints.push(startAfter(filters.lastDoc));
1539
- }
1540
- }
1541
- constraints.push(limit(filters.pagination || 10));
1542
-
1543
- const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1544
- const querySnapshot = await getDocs(q);
1545
- let procedures = querySnapshot.docs.map(
1546
- doc => ({ ...doc.data(), id: doc.id } as Procedure),
1547
- );
1548
-
1549
- // Apply client-side filters for nested fields if needed
1550
- if (hasNestedFilters) {
1551
- procedures = this.applyInMemoryFilters(procedures, filters);
1552
- }
1553
-
1554
- const lastDoc =
1555
- querySnapshot.docs.length > 0
1556
- ? querySnapshot.docs[querySnapshot.docs.length - 1]
1557
- : null;
1558
-
1559
- console.log(`[PROCEDURE_SERVICE] Strategy 2 success: ${procedures.length} procedures`);
1560
-
1561
- // Fix Load More - ako je broj rezultata manji od pagination, nema više
1562
- if (procedures.length < (filters.pagination || 10)) {
1563
- return { procedures, lastDoc: null };
1564
- }
1565
- return { procedures, lastDoc };
1566
- } catch (error) {
1567
- console.log('[PROCEDURE_SERVICE] Strategy 2 failed:', error);
1568
- }
1569
- }
1570
-
1571
- // Strategy 3: orderBy createdAt with client-side filtering
1572
- // NOTE: This strategy excludes nested field filters (technology.id, category.id, subcategory.id)
1573
- // from Firestore query because Firestore doesn't support orderBy on different field
1574
- // when using where on nested fields without a composite index.
1575
- // These filters are applied client-side instead.
1576
- try {
1577
- console.log(
1578
- '[PROCEDURE_SERVICE] Strategy 3: Using createdAt orderBy with client-side filtering',
1579
- {
1580
- procedureTechnology: filters.procedureTechnology,
1581
- hasTechnologyFilter: !!filters.procedureTechnology,
1582
- },
1583
- );
1584
-
1585
- // Build constraints WITHOUT nested field filters (these will be applied client-side)
1586
- const constraints: QueryConstraint[] = [];
1587
-
1588
- // Active status filter
1589
- if (filters.isActive !== undefined) {
1590
- constraints.push(where('isActive', '==', filters.isActive));
1591
- } else {
1592
- constraints.push(where('isActive', '==', true));
1593
- }
1594
-
1595
- // Only include non-nested field filters in Firestore query
1596
- if (filters.procedureFamily) {
1597
- constraints.push(where('family', '==', filters.procedureFamily));
1598
- }
1599
- if (filters.practitionerId) {
1600
- constraints.push(where('practitionerId', '==', filters.practitionerId));
1601
- }
1602
- if (filters.clinicId) {
1603
- constraints.push(where('clinicBranchId', '==', filters.clinicId));
1604
- }
1605
- if (filters.minPrice !== undefined) {
1606
- constraints.push(where('price', '>=', filters.minPrice));
1607
- }
1608
- if (filters.maxPrice !== undefined) {
1609
- constraints.push(where('price', '<=', filters.maxPrice));
1610
- }
1611
- if (filters.minRating !== undefined) {
1612
- constraints.push(where('reviewInfo.averageRating', '>=', filters.minRating));
1613
- }
1614
- if (filters.maxRating !== undefined) {
1615
- constraints.push(where('reviewInfo.averageRating', '<=', filters.maxRating));
1616
- }
1617
- if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
1618
- const benefitIdsToMatch = filters.treatmentBenefits;
1619
- constraints.push(where('treatmentBenefitIds', 'array-contains-any', benefitIdsToMatch));
1620
- }
1621
-
1622
- // NOTE: We intentionally EXCLUDE these nested field filters from Firestore query:
1623
- // - filters.procedureTechnology (technology.id)
1624
- // - filters.procedureCategory (category.id)
1625
- // - filters.procedureSubcategory (subcategory.id)
1626
- // These will be applied client-side in applyInMemoryFilters
1627
-
1628
- console.log(
1629
- '[PROCEDURE_SERVICE] Strategy 3 Firestore constraints (nested filters excluded):',
1630
- constraints.map(c => (c as any).fieldPath || 'unknown'),
1631
- );
1632
- constraints.push(orderBy('createdAt', 'desc'));
1633
-
1634
- if (filters.lastDoc) {
1635
- if (typeof filters.lastDoc.data === 'function') {
1636
- constraints.push(startAfter(filters.lastDoc));
1637
- } else if (Array.isArray(filters.lastDoc)) {
1638
- constraints.push(startAfter(...filters.lastDoc));
1639
- } else {
1640
- constraints.push(startAfter(filters.lastDoc));
1641
- }
1642
- }
1643
- constraints.push(limit(filters.pagination || 10));
1644
-
1645
- const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1646
- const querySnapshot = await getDocs(q);
1647
- let procedures = querySnapshot.docs.map(
1648
- doc => ({ ...doc.data(), id: doc.id } as Procedure),
1649
- );
1650
-
1651
- // Apply all client-side filters using centralized function
1652
- console.log('[PROCEDURE_SERVICE] Before applyInMemoryFilters (Strategy 3):', {
1653
- procedureCount: procedures.length,
1654
- procedureTechnology: filters.procedureTechnology,
1655
- filtersObject: {
1656
- procedureTechnology: filters.procedureTechnology,
1657
- procedureFamily: filters.procedureFamily,
1658
- procedureCategory: filters.procedureCategory,
1659
- procedureSubcategory: filters.procedureSubcategory,
1660
- },
1661
- });
1662
- procedures = this.applyInMemoryFilters(procedures, filters);
1663
- console.log('[PROCEDURE_SERVICE] After applyInMemoryFilters (Strategy 3):', {
1664
- procedureCount: procedures.length,
1665
- });
1666
-
1667
- const lastDoc =
1668
- querySnapshot.docs.length > 0 ? querySnapshot.docs[querySnapshot.docs.length - 1] : null;
1669
- console.log(`[PROCEDURE_SERVICE] Strategy 3 success: ${procedures.length} procedures`);
1670
-
1671
- // Fix Load More - ako je broj rezultata manji od pagination, nema više
1672
- if (procedures.length < (filters.pagination || 10)) {
1673
- return { procedures, lastDoc: null };
1674
- }
1675
- return { procedures, lastDoc };
1676
- } catch (error) {
1677
- console.log('[PROCEDURE_SERVICE] Strategy 3 failed:', error);
1678
- }
1679
-
1680
- // Strategy 4: Minimal query fallback
1681
- try {
1682
- console.log('[PROCEDURE_SERVICE] Strategy 4: Minimal query fallback');
1683
- const constraints: QueryConstraint[] = [
1684
- where('isActive', '==', filters.isActive !== undefined ? filters.isActive : true),
1685
- orderBy('createdAt', 'desc'),
1686
- ];
1687
- if (filters.practitionerId) {
1688
- constraints.push(where('practitionerId', '==', filters.practitionerId));
1689
- }
1690
- if (filters.clinicId) {
1691
- constraints.push(where('clinicBranchId', '==', filters.clinicId));
1692
- }
1693
- constraints.push(limit(filters.pagination || 10));
1694
-
1695
- const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1696
- const querySnapshot = await getDocs(q);
1697
- let procedures = querySnapshot.docs.map(
1698
- doc => ({ ...doc.data(), id: doc.id } as Procedure),
1699
- );
1700
-
1701
- // Apply all client-side filters using centralized function
1702
- procedures = this.applyInMemoryFilters(procedures, filters);
1703
-
1704
- const lastDoc =
1705
- querySnapshot.docs.length > 0 ? querySnapshot.docs[querySnapshot.docs.length - 1] : null;
1706
- console.log(`[PROCEDURE_SERVICE] Strategy 4 success: ${procedures.length} procedures`);
1707
-
1708
- // Fix Load More - ako je broj rezultata manji od pagination, nema više
1709
- if (procedures.length < (filters.pagination || 10)) {
1710
- return { procedures, lastDoc: null };
1711
- }
1712
- return { procedures, lastDoc };
1713
- } catch (error) {
1714
- console.log('[PROCEDURE_SERVICE] Strategy 4 failed:', error);
1715
- }
1716
-
1717
- // All strategies failed
1718
- console.log('[PROCEDURE_SERVICE] All strategies failed, returning empty result');
1719
- return { procedures: [], lastDoc: null };
1720
- } catch (error) {
1721
- console.error('[PROCEDURE_SERVICE] Error filtering procedures:', error);
1722
- return { procedures: [], lastDoc: null };
1723
- }
1724
- }
1725
-
1726
- /**
1727
- * Applies in-memory filters to procedures array
1728
- * Used when Firestore queries fail or for complex filtering
1729
- */
1730
- private applyInMemoryFilters(
1731
- procedures: Procedure[],
1732
- filters: any,
1733
- ): (Procedure & { distance?: number })[] {
1734
- let filteredProcedures = [...procedures]; // Create copy to avoid mutating original
1735
-
1736
- // Debug: Log what filters we received
1737
- console.log('[PROCEDURE_SERVICE] applyInMemoryFilters called:', {
1738
- procedureCount: procedures.length,
1739
- procedureTechnology: filters.procedureTechnology,
1740
- hasTechnologyFilter: !!filters.procedureTechnology,
1741
- allFilterKeys: Object.keys(filters).filter(k => filters[k] !== undefined && filters[k] !== null),
1742
- });
1743
-
1744
- // Name search filter
1745
- if (filters.nameSearch && filters.nameSearch.trim()) {
1746
- const searchTerm = filters.nameSearch.trim().toLowerCase();
1747
- filteredProcedures = filteredProcedures.filter(procedure => {
1748
- const name = (procedure.name || '').toLowerCase();
1749
- const nameLower = procedure.nameLower || '';
1750
- return name.includes(searchTerm) || nameLower.includes(searchTerm);
1751
- });
1752
- console.log(`[PROCEDURE_SERVICE] Applied name filter, results: ${filteredProcedures.length}`);
1753
- }
1754
-
1755
- // Price filtering
1756
- if (filters.minPrice !== undefined || filters.maxPrice !== undefined) {
1757
- filteredProcedures = filteredProcedures.filter(procedure => {
1758
- const price = procedure.price || 0;
1759
- if (filters.minPrice !== undefined && price < filters.minPrice) return false;
1760
- if (filters.maxPrice !== undefined && price > filters.maxPrice) return false;
1761
- return true;
1762
- });
1763
- console.log(
1764
- `[PROCEDURE_SERVICE] Applied price filter (${filters.minPrice}-${filters.maxPrice}), results: ${filteredProcedures.length}`,
1765
- );
1766
- }
1767
-
1768
- // Rating filtering
1769
- if (filters.minRating !== undefined || filters.maxRating !== undefined) {
1770
- filteredProcedures = filteredProcedures.filter(procedure => {
1771
- const rating = procedure.reviewInfo?.averageRating || 0;
1772
- if (filters.minRating !== undefined && rating < filters.minRating) return false;
1773
- if (filters.maxRating !== undefined && rating > filters.maxRating) return false;
1774
- return true;
1775
- });
1776
- console.log(
1777
- `[PROCEDURE_SERVICE] Applied rating filter, results: ${filteredProcedures.length}`,
1778
- );
1779
- }
1780
-
1781
- // Treatment benefits filtering
1782
- if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
1783
- const benefitIdsToMatch = filters.treatmentBenefits;
1784
- filteredProcedures = filteredProcedures.filter(procedure => {
1785
- const procedureBenefitIds = procedure.treatmentBenefitIds || [];
1786
- return benefitIdsToMatch.some((benefitId: string) =>
1787
- procedureBenefitIds.includes(benefitId),
1788
- );
1789
- });
1790
- console.log(
1791
- `[PROCEDURE_SERVICE] Applied benefits filter, results: ${filteredProcedures.length}`,
1792
- );
1793
- }
1794
-
1795
- // Procedure family filtering
1796
- if (filters.procedureFamily) {
1797
- filteredProcedures = filteredProcedures.filter(
1798
- procedure => procedure.family === filters.procedureFamily,
1799
- );
1800
- console.log(
1801
- `[PROCEDURE_SERVICE] Applied family filter, results: ${filteredProcedures.length}`,
1802
- );
1803
- }
1804
-
1805
- // Category filtering
1806
- if (filters.procedureCategory) {
1807
- filteredProcedures = filteredProcedures.filter(
1808
- procedure => procedure.category?.id === filters.procedureCategory,
1809
- );
1810
- console.log(
1811
- `[PROCEDURE_SERVICE] Applied category filter, results: ${filteredProcedures.length}`,
1812
- );
1813
- }
1814
-
1815
- // Subcategory filtering
1816
- if (filters.procedureSubcategory) {
1817
- filteredProcedures = filteredProcedures.filter(
1818
- procedure => procedure.subcategory?.id === filters.procedureSubcategory,
1819
- );
1820
- console.log(
1821
- `[PROCEDURE_SERVICE] Applied subcategory filter, results: ${filteredProcedures.length}`,
1822
- );
1823
- }
1824
-
1825
- // Technology filtering
1826
- if (filters.procedureTechnology) {
1827
- const beforeCount = filteredProcedures.length;
1828
- filteredProcedures = filteredProcedures.filter(
1829
- procedure => procedure.technology?.id === filters.procedureTechnology,
1830
- );
1831
- console.log(
1832
- `[PROCEDURE_SERVICE] Applied technology filter (${filters.procedureTechnology}), before: ${beforeCount}, after: ${filteredProcedures.length}`,
1833
- );
1834
- // Log sample technology IDs for debugging
1835
- if (beforeCount > filteredProcedures.length) {
1836
- const filteredOut = procedures
1837
- .filter(p => p.technology?.id !== filters.procedureTechnology)
1838
- .slice(0, 3)
1839
- .map(p => ({ id: p.id, techId: p.technology?.id, name: p.name }));
1840
- console.log('[PROCEDURE_SERVICE] Filtered out sample procedures:', filteredOut);
1841
- }
1842
- }
1843
-
1844
- // Practitioner filtering
1845
- if (filters.practitionerId) {
1846
- filteredProcedures = filteredProcedures.filter(
1847
- procedure => procedure.practitionerId === filters.practitionerId,
1848
- );
1849
- console.log(
1850
- `[PROCEDURE_SERVICE] Applied practitioner filter, results: ${filteredProcedures.length}`,
1851
- );
1852
- }
1853
-
1854
- // Clinic filtering
1855
- if (filters.clinicId) {
1856
- filteredProcedures = filteredProcedures.filter(
1857
- procedure => procedure.clinicBranchId === filters.clinicId,
1858
- );
1859
- console.log(
1860
- `[PROCEDURE_SERVICE] Applied clinic filter, results: ${filteredProcedures.length}`,
1861
- );
1862
- }
1863
-
1864
- // Geo-radius filter
1865
- if (filters.location && filters.radiusInKm && filters.radiusInKm > 0) {
1866
- const location = filters.location;
1867
- const radiusInKm = filters.radiusInKm;
1868
- filteredProcedures = filteredProcedures.filter(procedure => {
1869
- const clinicLocation = procedure.clinicInfo?.location;
1870
- if (!clinicLocation?.latitude || !clinicLocation?.longitude) {
1871
- return false;
1872
- }
1873
-
1874
- const distance =
1875
- distanceBetween(
1876
- [location.latitude, location.longitude],
1877
- [clinicLocation.latitude, clinicLocation.longitude],
1878
- ) / 1000; // Convert to km
1879
-
1880
- // Attach distance for frontend sorting/display
1881
- (procedure as any).distance = distance;
1882
-
1883
- return distance <= radiusInKm;
1884
- });
1885
- console.log(`[PROCEDURE_SERVICE] Applied geo filter, results: ${filteredProcedures.length}`);
1886
-
1887
- // Sort by distance when geo filtering is applied
1888
- filteredProcedures.sort((a, b) => ((a as any).distance || 0) - ((b as any).distance || 0));
1889
- }
1890
-
1891
- return filteredProcedures as (Procedure & { distance?: number })[];
1892
- }
1893
-
1894
- private handleGeoQuery(filters: any): Promise<{
1895
- procedures: (Procedure & { distance?: number })[];
1896
- lastDoc: any;
1897
- }> {
1898
- console.log('[PROCEDURE_SERVICE] Executing geo query with geohash bounds');
1899
- try {
1900
- const location = filters.location;
1901
- const radiusInKm = filters.radiusInKm;
1902
-
1903
- if (!location || !radiusInKm) {
1904
- return Promise.resolve({ procedures: [], lastDoc: null });
1905
- }
1906
-
1907
- const bounds = geohashQueryBounds([location.latitude, location.longitude], radiusInKm * 1000);
1908
-
1909
- const fetches = bounds.map(b => {
1910
- const constraints: QueryConstraint[] = [
1911
- where('clinicInfo.location.geohash', '>=', b[0]),
1912
- where('clinicInfo.location.geohash', '<=', b[1]),
1913
- where('isActive', '==', filters.isActive !== undefined ? filters.isActive : true),
1914
- ];
1915
- if (filters.practitionerId) {
1916
- constraints.push(where('practitionerId', '==', filters.practitionerId));
1917
- }
1918
- if (filters.clinicId) {
1919
- constraints.push(where('clinicBranchId', '==', filters.clinicId));
1920
- }
1921
- return getDocs(query(collection(this.db, PROCEDURES_COLLECTION), ...constraints));
1922
- });
1923
-
1924
- return Promise.all(fetches)
1925
- .then(snaps => {
1926
- const collected: Procedure[] = [];
1927
- snaps.forEach(snap => {
1928
- snap.docs.forEach(d => collected.push({ ...(d.data() as Procedure), id: d.id }));
1929
- });
1930
-
1931
- // Deduplicate by id
1932
- const uniqueMap = new Map<string, Procedure>();
1933
- for (const p of collected) {
1934
- uniqueMap.set(p.id, p);
1935
- }
1936
- let procedures = Array.from(uniqueMap.values());
1937
-
1938
- // Apply remaining filters including precise distance and sorting
1939
- procedures = this.applyInMemoryFilters(procedures, filters);
1940
-
1941
- // Manual pagination
1942
- const pageSize = filters.pagination || 10;
1943
- let startIndex = 0;
1944
- if (
1945
- filters.lastDoc &&
1946
- typeof filters.lastDoc === 'object' &&
1947
- (filters.lastDoc as any).id
1948
- ) {
1949
- const idx = procedures.findIndex(p => p.id === (filters.lastDoc as any).id);
1950
- if (idx >= 0) startIndex = idx + 1;
1951
- }
1952
- const page = procedures.slice(startIndex, startIndex + pageSize);
1953
- const newLastDoc = page.length === pageSize ? page[page.length - 1] : null;
1954
-
1955
- console.log(
1956
- `[PROCEDURE_SERVICE] Geo query success: ${page.length} (of ${procedures.length}) within ${radiusInKm}km`,
1957
- );
1958
- return { procedures: page, lastDoc: newLastDoc };
1959
- })
1960
- .catch(err => {
1961
- console.error('[PROCEDURE_SERVICE] Geo bounds fetch failed:', err);
1962
- return { procedures: [], lastDoc: null };
1963
- });
1964
- } catch (error) {
1965
- console.error('[PROCEDURE_SERVICE] Geo query failed:', error);
1966
- return Promise.resolve({ procedures: [], lastDoc: null });
1967
- }
1968
- }
1969
-
1970
- /**
1971
- * Creates a consultation procedure without requiring a product
1972
- * This is a special method for consultation procedures that don't use products
1973
- * @param data - The data for creating a consultation procedure (without productId)
1974
- * @returns The created procedure
1975
- */
1976
- async createConsultationProcedure(
1977
- data: Omit<CreateProcedureData, 'productId'>,
1978
- ): Promise<Procedure> {
1979
- // Generate procedure ID first so we can use it for media uploads
1980
- const procedureId = this.generateId();
1981
-
1982
- // Get references to related entities (Category, Subcategory, Technology)
1983
- // For consultation, we don't need a product
1984
- const [category, subcategory, technology] = await Promise.all([
1985
- this.categoryService.getByIdInternal(data.categoryId),
1986
- this.subcategoryService.getByIdInternal(data.categoryId, data.subcategoryId),
1987
- this.technologyService.getByIdInternal(data.technologyId),
1988
- ]);
1989
-
1990
- if (!category || !subcategory || !technology) {
1991
- throw new Error('One or more required base entities not found');
1992
- }
1993
-
1994
- // Get clinic and practitioner information for aggregation
1995
- const clinicRef = doc(this.db, CLINICS_COLLECTION, data.clinicBranchId);
1996
- const clinicSnapshot = await getDoc(clinicRef);
1997
- if (!clinicSnapshot.exists()) {
1998
- throw new Error(`Clinic with ID ${data.clinicBranchId} not found`);
1999
- }
2000
- const clinic = clinicSnapshot.data() as Clinic;
2001
-
2002
- const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, data.practitionerId);
2003
- const practitionerSnapshot = await getDoc(practitionerRef);
2004
- if (!practitionerSnapshot.exists()) {
2005
- throw new Error(`Practitioner with ID ${data.practitionerId} not found`);
2006
- }
2007
- const practitioner = practitionerSnapshot.data() as Practitioner;
2008
-
2009
- // Process photos if provided
2010
- let processedPhotos: string[] = [];
2011
- if (data.photos && data.photos.length > 0) {
2012
- processedPhotos = await this.processMediaArray(data.photos, procedureId, 'procedure-photos');
2013
- }
2014
-
2015
- // If no photos provided and technology has a photoTemplate, use it as default photo
2016
- if (processedPhotos.length === 0 && technology.photoTemplate) {
2017
- console.log(`[ProcedureService] Using technology photoTemplate as default photo for consultation: ${technology.photoTemplate}`);
2018
- const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
2019
- if (photoTemplateUrl) {
2020
- processedPhotos.push(photoTemplateUrl);
2021
- } else {
2022
- console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
2023
- }
2024
- }
2025
-
2026
- // Transform productsMetadata from validation format to ProcedureProduct format
2027
- // For consultations, this will return empty array since no products are provided
2028
- const transformedProductsMetadata = await this.transformProductsMetadata(
2029
- data.productsMetadata,
2030
- data.technologyId,
2031
- );
2032
-
2033
- // Create aggregated clinic info for the procedure document
2034
- const clinicInfo = {
2035
- id: clinicSnapshot.id,
2036
- name: clinic.name,
2037
- description: clinic.description || '',
2038
- featuredPhoto:
2039
- clinic.featuredPhotos && clinic.featuredPhotos.length > 0
2040
- ? typeof clinic.featuredPhotos[0] === 'string'
2041
- ? clinic.featuredPhotos[0]
2042
- : ''
2043
- : typeof clinic.coverPhoto === 'string'
2044
- ? clinic.coverPhoto
2045
- : '',
2046
- location: clinic.location,
2047
- contactInfo: clinic.contactInfo,
2048
- };
2049
-
2050
- // Create aggregated doctor info for the procedure document
2051
- const doctorInfo = {
2052
- id: practitionerSnapshot.id,
2053
- name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
2054
- description: practitioner.basicInfo.bio || '',
2055
- photo:
2056
- typeof practitioner.basicInfo.profileImageUrl === 'string'
2057
- ? practitioner.basicInfo.profileImageUrl
2058
- : '',
2059
- rating: practitioner.reviewInfo?.averageRating || 0,
2060
- services: practitioner.procedures || [],
2061
- };
2062
-
2063
- // Create the procedure object
2064
- const { productsMetadata: _, ...dataWithoutProductsMetadata } = data;
2065
- const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
2066
- id: procedureId,
2067
- ...dataWithoutProductsMetadata,
2068
- nameLower: (data as any).nameLower || data.name.toLowerCase(),
2069
- photos: processedPhotos,
2070
- category,
2071
- subcategory,
2072
- technology,
2073
- // No product field for consultations (Firestore doesn't allow undefined, so we omit it entirely)
2074
- productsMetadata: transformedProductsMetadata, // Empty array for consultations
2075
- blockingConditions: technology.blockingConditions,
2076
- contraindications: technology.contraindications || [],
2077
- contraindicationIds: technology.contraindications?.map(c => c.id) || [],
2078
- treatmentBenefits: technology.benefits,
2079
- treatmentBenefitIds: Array.isArray(technology.benefits)
2080
- ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
2081
- : [],
2082
- preRequirements: technology.requirements.pre,
2083
- postRequirements: technology.requirements.post,
2084
- certificationRequirement: technology.certificationRequirement,
2085
- documentationTemplates: technology?.documentationTemplates || [],
2086
- clinicInfo,
2087
- doctorInfo,
2088
- reviewInfo: {
2089
- totalReviews: 0,
2090
- averageRating: 0,
2091
- effectivenessOfTreatment: 0,
2092
- outcomeExplanation: 0,
2093
- painManagement: 0,
2094
- followUpCare: 0,
2095
- valueForMoney: 0,
2096
- recommendationPercentage: 0,
2097
- },
2098
- isActive: true,
2099
- };
2100
-
2101
- // Create the procedure document
2102
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
2103
- await setDoc(procedureRef, {
2104
- ...newProcedure,
2105
- createdAt: serverTimestamp(),
2106
- updatedAt: serverTimestamp(),
2107
- });
2108
-
2109
- // Return the created procedure (fetch again to get server timestamps)
2110
- const savedDoc = await getDoc(procedureRef);
2111
- return savedDoc.data() as Procedure;
2112
- }
2113
-
2114
- /**
2115
- * Gets all procedures with minimal info for map display (id, name, clinicId, clinicName, address, latitude, longitude)
2116
- * This is optimized for mobile map usage to reduce payload size.
2117
- * @returns Array of minimal procedure info for map
2118
- */
2119
- async getProceduresForMap(): Promise<
2120
- {
2121
- id: string;
2122
- name: string;
2123
- clinicId: string | undefined;
2124
- clinicName: string | undefined;
2125
- address: string;
2126
- latitude: number | undefined;
2127
- longitude: number | undefined;
2128
- }[]
2129
- > {
2130
- const proceduresRef = collection(this.db, PROCEDURES_COLLECTION);
2131
- const snapshot = await getDocs(proceduresRef);
2132
- const proceduresForMap = snapshot.docs.map(doc => {
2133
- const data = doc.data();
2134
- return {
2135
- id: doc.id,
2136
- name: data.name,
2137
- clinicId: data.clinicInfo?.id,
2138
- clinicName: data.clinicInfo?.name,
2139
- address: data.clinicInfo?.location?.address || '',
2140
- latitude: data.clinicInfo?.location?.latitude,
2141
- longitude: data.clinicInfo?.location?.longitude,
2142
- };
2143
- });
2144
- return proceduresForMap;
2145
- }
2146
-
2147
- /**
2148
- * Gets procedures filtered by clinic and practitioner with optional family filter
2149
- * @param clinicBranchId Clinic branch ID to filter by
2150
- * @param practitionerId Practitioner ID to filter by
2151
- * @param filterByFamily If true, shows only procedures of the same family as the default procedure
2152
- * @param defaultProcedureId Optional default procedure ID to determine the family
2153
- * @returns Array of procedures
2154
- */
2155
- async getProceduresForConsultation(
2156
- clinicBranchId: string,
2157
- practitionerId: string,
2158
- filterByFamily: boolean = true,
2159
- defaultProcedureId?: string
2160
- ): Promise<Procedure[]> {
2161
- let familyToFilter: ProcedureFamily | null = null;
2162
-
2163
- // If family filtering is enabled and we have a default procedure, get its family
2164
- if (filterByFamily && defaultProcedureId) {
2165
- const defaultProcedureRef = doc(this.db, PROCEDURES_COLLECTION, defaultProcedureId);
2166
- const defaultProcedureSnap = await getDoc(defaultProcedureRef);
2167
-
2168
- if (defaultProcedureSnap.exists()) {
2169
- const defaultProcedure = defaultProcedureSnap.data() as Procedure;
2170
- familyToFilter = defaultProcedure.family;
2171
- }
2172
- }
2173
-
2174
- // Build query constraints
2175
- const constraints: QueryConstraint[] = [
2176
- where('clinicBranchId', '==', clinicBranchId),
2177
- where('practitionerId', '==', practitionerId),
2178
- where('isActive', '==', true),
2179
- ];
2180
-
2181
- // Add family filter if applicable
2182
- if (filterByFamily && familyToFilter) {
2183
- constraints.push(where('family', '==', familyToFilter));
2184
- }
2185
-
2186
- // Execute query
2187
- const proceduresQuery = query(
2188
- collection(this.db, PROCEDURES_COLLECTION),
2189
- ...constraints,
2190
- orderBy('name', 'asc')
2191
- );
2192
-
2193
- const querySnapshot = await getDocs(proceduresQuery);
2194
-
2195
- return querySnapshot.docs.map(doc => ({
2196
- id: doc.id,
2197
- ...doc.data(),
2198
- } as Procedure));
2199
- }
2200
- }
1
+ import {
2
+ collection,
3
+ doc,
4
+ getDoc,
5
+ getDocs,
6
+ query,
7
+ where,
8
+ updateDoc,
9
+ setDoc,
10
+ deleteDoc,
11
+ Timestamp,
12
+ serverTimestamp,
13
+ DocumentData,
14
+ writeBatch,
15
+ arrayUnion,
16
+ arrayRemove,
17
+ FieldValue,
18
+ orderBy,
19
+ limit,
20
+ startAfter,
21
+ QueryConstraint,
22
+ documentId,
23
+ } from 'firebase/firestore';
24
+ import { BaseService } from '../base.service';
25
+ import {
26
+ Procedure,
27
+ CreateProcedureData,
28
+ UpdateProcedureData,
29
+ PROCEDURES_COLLECTION,
30
+ ProcedureSummaryInfo,
31
+ } from '../../types/procedure';
32
+ import { createProcedureSchema, updateProcedureSchema } from '../../validations/procedure.schema';
33
+ import { z } from 'zod';
34
+ import { Auth } from 'firebase/auth';
35
+ import { Firestore } from 'firebase/firestore';
36
+ import { FirebaseApp } from 'firebase/app';
37
+ import { Category, CATEGORIES_COLLECTION } from '../../backoffice/types/category.types';
38
+ import { Subcategory, SUBCATEGORIES_COLLECTION } from '../../backoffice/types/subcategory.types';
39
+ import { Technology, TECHNOLOGIES_COLLECTION } from '../../backoffice/types/technology.types';
40
+ import { Product, PRODUCTS_COLLECTION } from '../../backoffice/types/product.types';
41
+ import { CategoryService } from '../../backoffice/services/category.service';
42
+ import { SubcategoryService } from '../../backoffice/services/subcategory.service';
43
+ import { TechnologyService } from '../../backoffice/services/technology.service';
44
+ import { ProductService } from '../../backoffice/services/product.service';
45
+ import { Practitioner, PRACTITIONERS_COLLECTION } from '../../types/practitioner';
46
+ import {
47
+ CertificationLevel,
48
+ CertificationSpecialty,
49
+ ProcedureFamily,
50
+ type TreatmentBenefitDynamic,
51
+ } from '../../backoffice/types';
52
+ import { Currency, PricingMeasure } from '../../backoffice/types/static/pricing.types';
53
+ import { Clinic, CLINICS_COLLECTION } from '../../types/clinic';
54
+ import { ProcedureReviewInfo } from '../../types/reviews';
55
+ import { distanceBetween, geohashQueryBounds } from 'geofire-common';
56
+ import { MediaService, MediaAccessLevel } from '../media/media.service';
57
+ import type { ProcedureProduct } from '../../backoffice/types/procedure-product.types';
58
+
59
+ import { PractitionerService } from '../practitioner/practitioner.service';
60
+ import { PractitionerStatus } from '../../types/practitioner';
61
+
62
+ export class ProcedureService extends BaseService {
63
+ private categoryService: CategoryService;
64
+ private subcategoryService: SubcategoryService;
65
+ private technologyService: TechnologyService;
66
+ private productService: ProductService;
67
+ private mediaService: MediaService;
68
+ private practitionerService?: PractitionerService;
69
+
70
+ constructor(
71
+ db: Firestore,
72
+ auth: Auth,
73
+ app: FirebaseApp,
74
+ categoryService: CategoryService,
75
+ subcategoryService: SubcategoryService,
76
+ technologyService: TechnologyService,
77
+ productService: ProductService,
78
+ mediaService: MediaService,
79
+ ) {
80
+ super(db, auth, app);
81
+ this.categoryService = categoryService;
82
+ this.subcategoryService = subcategoryService;
83
+ this.technologyService = technologyService;
84
+ this.productService = productService;
85
+ this.mediaService = mediaService;
86
+ }
87
+
88
+ setPractitionerService(practitionerService: PractitionerService) {
89
+ this.practitionerService = practitionerService;
90
+ }
91
+
92
+ /**
93
+ * Filters out procedures from draft practitioners
94
+ * @param procedures - Array of procedures to filter
95
+ * @returns Filtered array of procedures (excluding those from draft practitioners)
96
+ */
97
+ private async filterDraftPractitionerProcedures(
98
+ procedures: Procedure[]
99
+ ): Promise<Procedure[]> {
100
+ if (!this.practitionerService || procedures.length === 0) {
101
+ return procedures;
102
+ }
103
+
104
+ try {
105
+ // Get unique practitioner IDs from procedures
106
+ const practitionerIds = Array.from(
107
+ new Set(procedures.map((p) => p.practitionerId).filter(Boolean))
108
+ );
109
+
110
+ if (practitionerIds.length === 0) {
111
+ return procedures;
112
+ }
113
+
114
+ // Fetch all practitioners in parallel
115
+ const practitionerPromises = practitionerIds.map((id) =>
116
+ this.practitionerService!.getPractitioner(id).catch(() => null)
117
+ );
118
+ const practitioners = await Promise.all(practitionerPromises);
119
+
120
+ // Create a map of practitioner ID to status
121
+ const practitionerStatusMap = new Map<string, PractitionerStatus>();
122
+ practitioners.forEach((practitioner, index) => {
123
+ if (practitioner) {
124
+ practitionerStatusMap.set(practitionerIds[index], practitioner.status);
125
+ }
126
+ });
127
+
128
+ // Filter out procedures from draft practitioners
129
+ const filteredProcedures = procedures.filter((procedure) => {
130
+ const practitionerStatus = practitionerStatusMap.get(procedure.practitionerId);
131
+ return practitionerStatus !== PractitionerStatus.DRAFT;
132
+ });
133
+
134
+ if (filteredProcedures.length !== procedures.length) {
135
+ console.log(
136
+ `[ProcedureService] Filtered out ${
137
+ procedures.length - filteredProcedures.length
138
+ } procedures from draft practitioners`
139
+ );
140
+ }
141
+
142
+ return filteredProcedures;
143
+ } catch (error) {
144
+ console.error(
145
+ '[ProcedureService] Error filtering draft practitioner procedures:',
146
+ error
147
+ );
148
+ // On error, return original procedures to avoid breaking functionality
149
+ return procedures;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Process media resource (string URL or File object)
155
+ * @param media String URL or File object
156
+ * @param ownerId Owner ID for the media (usually procedureId)
157
+ * @param collectionName Collection name for organizing files
158
+ * @returns URL string after processing
159
+ */
160
+ private async processMedia(
161
+ media: string | File | Blob | null | undefined,
162
+ ownerId: string,
163
+ collectionName: string,
164
+ ): Promise<string | null> {
165
+ if (!media) return null;
166
+
167
+ // If already a string URL, return it directly
168
+ if (typeof media === 'string') {
169
+ return media;
170
+ }
171
+
172
+ // If it's a File, upload it using MediaService
173
+ if (media instanceof File || media instanceof Blob) {
174
+ console.log(`[ProcedureService] Uploading ${collectionName} media for ${ownerId}`);
175
+ const metadata = await this.mediaService.uploadMedia(
176
+ media,
177
+ ownerId,
178
+ MediaAccessLevel.PUBLIC,
179
+ collectionName,
180
+ );
181
+ return metadata.url;
182
+ }
183
+
184
+ return null;
185
+ }
186
+
187
+ /**
188
+ * Process array of media resources (strings or Files)
189
+ * @param mediaArray Array of string URLs or File objects
190
+ * @param ownerId Owner ID for the media
191
+ * @param collectionName Collection name for organizing files
192
+ * @returns Array of URL strings after processing
193
+ */
194
+ private async processMediaArray(
195
+ mediaArray: (string | File | Blob)[] | undefined,
196
+ ownerId: string,
197
+ collectionName: string,
198
+ ): Promise<string[]> {
199
+ if (!mediaArray || mediaArray.length === 0) return [];
200
+
201
+ const result: string[] = [];
202
+
203
+ for (const media of mediaArray) {
204
+ const processedUrl = await this.processMedia(media, ownerId, collectionName);
205
+ if (processedUrl) {
206
+ result.push(processedUrl);
207
+ }
208
+ }
209
+
210
+ return result;
211
+ }
212
+
213
+ /**
214
+ * Transforms validated procedure product data (with productId) to ProcedureProduct objects (with full product)
215
+ * @param productsMetadata Array of validated procedure product data (optional)
216
+ * @param technologyId Technology ID to fetch products from
217
+ * @returns Array of ProcedureProduct objects with full product information
218
+ */
219
+ private async transformProductsMetadata(
220
+ productsMetadata: {
221
+ productId: string;
222
+ price: number;
223
+ currency: Currency;
224
+ pricingMeasure: PricingMeasure;
225
+ isDefault?: boolean;
226
+ }[] | undefined,
227
+ technologyId: string,
228
+ ): Promise<ProcedureProduct[]> {
229
+ // Return empty array if no products metadata provided (for product-free procedures like consultations)
230
+ if (!productsMetadata || productsMetadata.length === 0) {
231
+ return [];
232
+ }
233
+
234
+ const transformedProducts: ProcedureProduct[] = [];
235
+
236
+ for (const productData of productsMetadata) {
237
+ // Fetch the full product object
238
+ const product = await this.productService.getById(technologyId, productData.productId);
239
+ if (!product) {
240
+ throw new Error(
241
+ `Product with ID ${productData.productId} not found for technology ${technologyId}`,
242
+ );
243
+ }
244
+
245
+ // Transform to ProcedureProduct
246
+ transformedProducts.push({
247
+ product,
248
+ price: productData.price,
249
+ currency: productData.currency,
250
+ pricingMeasure: productData.pricingMeasure,
251
+ isDefault: productData.isDefault,
252
+ });
253
+ }
254
+
255
+ return transformedProducts;
256
+ }
257
+
258
+ /**
259
+ * Creates a new procedure
260
+ * @param data - The data for creating a new procedure
261
+ * @returns The created procedure
262
+ */
263
+ async createProcedure(data: CreateProcedureData): Promise<Procedure> {
264
+ const validatedData = createProcedureSchema.parse(data);
265
+
266
+ // Check if this is a product-free procedure (e.g., free consultation)
267
+ const isProductFree = !validatedData.productId;
268
+
269
+ // Generate procedure ID first so we can use it for media uploads
270
+ const procedureId = this.generateId();
271
+
272
+ // Get references to related entities (Category, Subcategory, Technology, and optionally Product)
273
+ const baseEntitiesPromises: Promise<Category | Subcategory | Technology | Product | null>[] = [
274
+ this.categoryService.getById(validatedData.categoryId),
275
+ this.subcategoryService.getById(validatedData.categoryId, validatedData.subcategoryId),
276
+ this.technologyService.getById(validatedData.technologyId),
277
+ ];
278
+
279
+ // Only fetch product if productId is provided
280
+ if (!isProductFree) {
281
+ baseEntitiesPromises.push(
282
+ this.productService.getById(validatedData.technologyId, validatedData.productId!)
283
+ );
284
+ }
285
+
286
+ const results = await Promise.all(baseEntitiesPromises);
287
+ const category = results[0] as Category | null;
288
+ const subcategory = results[1] as Subcategory | null;
289
+ const technology = results[2] as Technology | null;
290
+ const product = isProductFree ? undefined : ((results[3] as Product | null) || undefined);
291
+
292
+ if (!category || !subcategory || !technology) {
293
+ throw new Error('One or more required base entities not found');
294
+ }
295
+
296
+ // For regular procedures, validate product exists
297
+ if (!isProductFree && !product) {
298
+ throw new Error('Product not found for regular procedure');
299
+ }
300
+
301
+ // Get clinic and practitioner information for aggregation
302
+ const clinicRef = doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId);
303
+ const clinicSnapshot = await getDoc(clinicRef);
304
+ if (!clinicSnapshot.exists()) {
305
+ throw new Error(`Clinic with ID ${validatedData.clinicBranchId} not found`);
306
+ }
307
+ const clinic = clinicSnapshot.data() as Clinic; // Assert type
308
+
309
+ const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, validatedData.practitionerId);
310
+ const practitionerSnapshot = await getDoc(practitionerRef);
311
+ if (!practitionerSnapshot.exists()) {
312
+ throw new Error(`Practitioner with ID ${validatedData.practitionerId} not found`);
313
+ }
314
+ const practitioner = practitionerSnapshot.data() as Practitioner; // Assert type
315
+
316
+ // Check if practitioner already has a procedure with the same technology ID in this clinic branch
317
+ const existingProceduresQuery = query(
318
+ collection(this.db, PROCEDURES_COLLECTION),
319
+ where('practitionerId', '==', validatedData.practitionerId),
320
+ where('clinicBranchId', '==', validatedData.clinicBranchId),
321
+ where('isActive', '==', true)
322
+ );
323
+ const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
324
+ const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
325
+
326
+ const hasSameTechnology = existingProcedures.some(
327
+ proc => proc.technology?.id === validatedData.technologyId
328
+ );
329
+ if (hasSameTechnology) {
330
+ throw new Error(
331
+ `Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} already has a procedure with technology "${technology?.name || validatedData.technologyId}" in this clinic branch`
332
+ );
333
+ }
334
+
335
+ // Process photos if provided
336
+ let processedPhotos: string[] = [];
337
+ if (validatedData.photos && validatedData.photos.length > 0) {
338
+ processedPhotos = await this.processMediaArray(
339
+ validatedData.photos,
340
+ procedureId,
341
+ 'procedure-photos',
342
+ );
343
+ }
344
+
345
+ // If no photos provided and technology has a photoTemplate, use it as default photo
346
+ if (processedPhotos.length === 0 && technology.photoTemplate) {
347
+ console.log(`[ProcedureService] Using technology photoTemplate as default photo: ${technology.photoTemplate}`);
348
+ const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
349
+ if (photoTemplateUrl) {
350
+ processedPhotos.push(photoTemplateUrl);
351
+ } else {
352
+ console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
353
+ }
354
+ }
355
+
356
+ // Transform productsMetadata from validation format to ProcedureProduct format
357
+ const transformedProductsMetadata = await this.transformProductsMetadata(
358
+ validatedData.productsMetadata,
359
+ validatedData.technologyId,
360
+ );
361
+
362
+ // Create aggregated clinic info for the procedure document
363
+ const clinicInfo = {
364
+ id: clinicSnapshot.id,
365
+ name: clinic.name,
366
+ description: clinic.description || '',
367
+ featuredPhoto:
368
+ clinic.featuredPhotos && clinic.featuredPhotos.length > 0
369
+ ? typeof clinic.featuredPhotos[0] === 'string'
370
+ ? clinic.featuredPhotos[0]
371
+ : ''
372
+ : typeof clinic.coverPhoto === 'string'
373
+ ? clinic.coverPhoto
374
+ : '',
375
+ location: clinic.location,
376
+ contactInfo: clinic.contactInfo,
377
+ };
378
+
379
+ // Create aggregated doctor info for the procedure document
380
+ const doctorInfo = {
381
+ id: practitionerSnapshot.id,
382
+ name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
383
+ description: practitioner.basicInfo.bio || '',
384
+ photo:
385
+ typeof practitioner.basicInfo.profileImageUrl === 'string'
386
+ ? practitioner.basicInfo.profileImageUrl
387
+ : '', // Default to empty string if not a processed URL
388
+ rating: practitioner.reviewInfo?.averageRating || 0,
389
+ services: practitioner.procedures || [],
390
+ };
391
+
392
+ // Create the procedure object
393
+ const { productsMetadata: _, productId: __, photos: ___, ...validatedDataWithoutProductsMetadata } = validatedData;
394
+ const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
395
+ id: procedureId,
396
+ ...validatedDataWithoutProductsMetadata,
397
+ // Ensure nameLower is always set even if omitted by client
398
+ nameLower: (validatedData as any).nameLower || validatedData.name.toLowerCase(),
399
+ photos: processedPhotos,
400
+ category, // Embed full objects
401
+ subcategory,
402
+ technology,
403
+ ...(product && { product }), // Only include product field if it exists (Firestore doesn't allow undefined)
404
+ productsMetadata: transformedProductsMetadata, // Use transformed data, not original
405
+ blockingConditions: technology.blockingConditions,
406
+ contraindications: technology.contraindications || [],
407
+ contraindicationIds: technology.contraindications?.map(c => c.id) || [],
408
+ treatmentBenefits: technology.benefits,
409
+ treatmentBenefitIds: Array.isArray(technology.benefits)
410
+ ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
411
+ : [],
412
+ preRequirements: technology.requirements.pre,
413
+ postRequirements: technology.requirements.post,
414
+ certificationRequirement: technology.certificationRequirement,
415
+ documentationTemplates: technology?.documentationTemplates || [],
416
+ clinicInfo, // Embed aggregated info
417
+ doctorInfo, // Embed aggregated info
418
+ reviewInfo: {
419
+ // Default empty reviews
420
+ totalReviews: 0,
421
+ averageRating: 0,
422
+ effectivenessOfTreatment: 0,
423
+ outcomeExplanation: 0,
424
+ painManagement: 0,
425
+ followUpCare: 0,
426
+ valueForMoney: 0,
427
+ recommendationPercentage: 0,
428
+ },
429
+ isActive: true, // Default to active
430
+ };
431
+
432
+ // 🔥 DEBUG: Find undefined fields before writing to Firestore
433
+ console.log('🔥🔥🔥 CREATE PROCEDURE - Processing procedure:', procedureId);
434
+ console.log('🔥🔥🔥 FULL PROCEDURE OBJECT:', JSON.stringify(newProcedure, null, 2));
435
+
436
+ const undefinedFields: string[] = [];
437
+ Object.entries(newProcedure).forEach(([key, value]) => {
438
+ if (value === undefined) {
439
+ undefinedFields.push(key);
440
+ }
441
+ });
442
+ if (undefinedFields.length > 0) {
443
+ console.error('🔥🔥🔥 UNDEFINED FIELDS DETECTED:', undefinedFields);
444
+ throw new Error(`Cannot write procedure with undefined fields: ${undefinedFields.join(', ')}`);
445
+ }
446
+ console.log('🔥🔥🔥 NO UNDEFINED FIELDS - Proceeding with setDoc');
447
+
448
+ // Create the procedure document
449
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
450
+ await setDoc(procedureRef, {
451
+ ...newProcedure,
452
+ createdAt: serverTimestamp(),
453
+ updatedAt: serverTimestamp(),
454
+ });
455
+
456
+ // Return the created procedure (fetch again to get server timestamps)
457
+ const savedDoc = await getDoc(procedureRef);
458
+ return savedDoc.data() as Procedure;
459
+ }
460
+
461
+ /**
462
+ * Validates if a practitioner can perform a procedure based on certification requirements.
463
+ *
464
+ * @param procedure - The procedure to check
465
+ * @param practitioner - The practitioner to validate
466
+ * @returns true if practitioner can perform the procedure, false otherwise
467
+ */
468
+ canPractitionerPerformProcedure(procedure: Procedure, practitioner: Practitioner): boolean {
469
+ if (!practitioner.certification) {
470
+ return false;
471
+ }
472
+
473
+ const requiredCert = procedure.certificationRequirement;
474
+ const practitionerCert = practitioner.certification;
475
+
476
+ // Check certification level
477
+ const levelOrder = [
478
+ 'aesthetician',
479
+ 'nurse_assistant',
480
+ 'nurse',
481
+ 'nurse_practitioner',
482
+ 'physician_assistant',
483
+ 'doctor',
484
+ 'specialist',
485
+ 'plastic_surgeon',
486
+ ];
487
+
488
+ const practitionerLevelIndex = levelOrder.indexOf(practitionerCert.level);
489
+ const requiredLevelIndex = levelOrder.indexOf(requiredCert.minimumLevel);
490
+
491
+ if (practitionerLevelIndex < requiredLevelIndex) {
492
+ return false;
493
+ }
494
+
495
+ // Check required specialties
496
+ const requiredSpecialties = requiredCert.requiredSpecialties || [];
497
+ if (requiredSpecialties.length > 0) {
498
+ const practitionerSpecialties = practitionerCert.specialties || [];
499
+ const hasAllRequired = requiredSpecialties.every(specialty =>
500
+ practitionerSpecialties.includes(specialty)
501
+ );
502
+ if (!hasAllRequired) {
503
+ return false;
504
+ }
505
+ }
506
+
507
+ return true;
508
+ }
509
+
510
+ /**
511
+ * Clones an existing procedure for a target practitioner.
512
+ * This creates a new procedure document with the same data as the source procedure,
513
+ * but linked to the target practitioner.
514
+ *
515
+ * @param sourceProcedureId - The ID of the procedure to clone
516
+ * @param targetPractitionerId - The ID of the practitioner to assign the cloned procedure to
517
+ * @param overrides - Optional overrides for the new procedure (e.g. price, duration, isActive)
518
+ * @returns The newly created procedure
519
+ */
520
+ async cloneProcedureForPractitioner(
521
+ sourceProcedureId: string,
522
+ targetPractitionerId: string,
523
+ overrides?: Partial<CreateProcedureData> & { isActive?: boolean }
524
+ ): Promise<Procedure> {
525
+ // 1. Fetch source procedure
526
+ const sourceProcedure = await this.getProcedure(sourceProcedureId);
527
+ if (!sourceProcedure) {
528
+ throw new Error(`Source procedure with ID ${sourceProcedureId} not found`);
529
+ }
530
+
531
+ // 2. Fetch target practitioner
532
+ const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, targetPractitionerId);
533
+ const practitionerSnapshot = await getDoc(practitionerRef);
534
+ if (!practitionerSnapshot.exists()) {
535
+ throw new Error(`Target practitioner with ID ${targetPractitionerId} not found`);
536
+ }
537
+ const practitioner = practitionerSnapshot.data() as Practitioner;
538
+
539
+ // 3. Validate certification
540
+ if (!this.canPractitionerPerformProcedure(sourceProcedure, practitioner)) {
541
+ throw new Error(
542
+ `Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} does not meet the certification requirements for this procedure`
543
+ );
544
+ }
545
+
546
+ // 4. Check if practitioner already has a procedure with the same technology ID in this clinic branch
547
+ const existingProceduresQuery = query(
548
+ collection(this.db, PROCEDURES_COLLECTION),
549
+ where('practitionerId', '==', targetPractitionerId),
550
+ where('clinicBranchId', '==', sourceProcedure.clinicBranchId),
551
+ where('isActive', '==', true)
552
+ );
553
+ const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
554
+ const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
555
+
556
+ const hasSameTechnology = existingProcedures.some(
557
+ proc => proc.technology?.id === sourceProcedure.technology?.id
558
+ );
559
+ if (hasSameTechnology) {
560
+ throw new Error(
561
+ `Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} already has a procedure with technology "${sourceProcedure.technology?.name || sourceProcedure.technology?.id}" in this clinic branch`
562
+ );
563
+ }
564
+
565
+ // 5. Prepare data for new procedure
566
+ const newProcedureId = this.generateId();
567
+
568
+ // Create aggregated doctor info for the new procedure
569
+ const doctorInfo = {
570
+ id: practitioner.id,
571
+ name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
572
+ description: practitioner.basicInfo.bio || '',
573
+ photo:
574
+ typeof practitioner.basicInfo.profileImageUrl === 'string'
575
+ ? practitioner.basicInfo.profileImageUrl
576
+ : '',
577
+ rating: practitioner.reviewInfo?.averageRating || 0,
578
+ services: practitioner.procedures || [],
579
+ };
580
+
581
+ // Construct the new procedure object
582
+ // We copy everything from source, but override specific fields
583
+ const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
584
+ ...sourceProcedure,
585
+ id: newProcedureId,
586
+ practitionerId: targetPractitionerId,
587
+ doctorInfo, // Link to new doctor
588
+
589
+ // Reset review info for the new procedure
590
+ reviewInfo: {
591
+ totalReviews: 0,
592
+ averageRating: 0,
593
+ effectivenessOfTreatment: 0,
594
+ outcomeExplanation: 0,
595
+ painManagement: 0,
596
+ followUpCare: 0,
597
+ valueForMoney: 0,
598
+ recommendationPercentage: 0,
599
+ },
600
+
601
+ // Apply any overrides if provided
602
+ ...(overrides?.price !== undefined && { price: overrides.price }),
603
+ ...(overrides?.duration !== undefined && { duration: overrides.duration }),
604
+ ...(overrides?.description !== undefined && { description: overrides.description }),
605
+
606
+ // Ensure it's active by default unless specified otherwise
607
+ isActive: overrides?.isActive !== undefined ? overrides.isActive : true,
608
+ };
609
+
610
+ // 6. Save to Firestore
611
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, newProcedureId);
612
+ await setDoc(procedureRef, {
613
+ ...newProcedure,
614
+ createdAt: serverTimestamp(),
615
+ updatedAt: serverTimestamp(),
616
+ });
617
+
618
+ // 7. Return the new procedure
619
+ const savedDoc = await getDoc(procedureRef);
620
+ return savedDoc.data() as Procedure;
621
+ }
622
+
623
+ /**
624
+ * Clones an existing procedure for multiple target practitioners.
625
+ * This creates new procedure documents with the same data as the source procedure,
626
+ * but linked to each target practitioner.
627
+ *
628
+ * @param sourceProcedureId - The ID of the procedure to clone
629
+ * @param targetPractitionerIds - Array of practitioner IDs to assign the cloned procedure to
630
+ * @param overrides - Optional overrides for the new procedures (e.g. price, duration, isActive)
631
+ * @returns Array of newly created procedures
632
+ */
633
+ async bulkCloneProcedureForPractitioners(
634
+ sourceProcedureId: string,
635
+ targetPractitionerIds: string[],
636
+ overrides?: Partial<CreateProcedureData> & { isActive?: boolean }
637
+ ): Promise<Procedure[]> {
638
+ if (!targetPractitionerIds || targetPractitionerIds.length === 0) {
639
+ throw new Error('At least one target practitioner ID is required');
640
+ }
641
+
642
+ // 1. Fetch source procedure
643
+ const sourceProcedure = await this.getProcedure(sourceProcedureId);
644
+ if (!sourceProcedure) {
645
+ throw new Error(`Source procedure with ID ${sourceProcedureId} not found`);
646
+ }
647
+
648
+ // 2. Fetch all target practitioners
649
+ const practitionerPromises = targetPractitionerIds.map(id =>
650
+ getDoc(doc(this.db, PRACTITIONERS_COLLECTION, id))
651
+ );
652
+ const practitionerSnapshots = await Promise.all(practitionerPromises);
653
+
654
+ // 3. Validate all practitioners exist, can perform the procedure, and don't already have the same technology
655
+ const practitioners: Practitioner[] = [];
656
+ const sourceTechnologyId = sourceProcedure.technology?.id;
657
+
658
+ for (let i = 0; i < practitionerSnapshots.length; i++) {
659
+ const snapshot = practitionerSnapshots[i];
660
+ if (!snapshot.exists()) {
661
+ throw new Error(`Target practitioner with ID ${targetPractitionerIds[i]} not found`);
662
+ }
663
+ const practitioner = snapshot.data() as Practitioner;
664
+
665
+ if (!this.canPractitionerPerformProcedure(sourceProcedure, practitioner)) {
666
+ throw new Error(
667
+ `Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} does not meet the certification requirements for this procedure`
668
+ );
669
+ }
670
+
671
+ // Check if practitioner already has a procedure with the same technology ID in this clinic branch
672
+ const existingProceduresQuery = query(
673
+ collection(this.db, PROCEDURES_COLLECTION),
674
+ where('practitionerId', '==', practitioner.id),
675
+ where('clinicBranchId', '==', sourceProcedure.clinicBranchId),
676
+ where('isActive', '==', true)
677
+ );
678
+ const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
679
+ const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
680
+
681
+ const hasSameTechnology = existingProcedures.some(
682
+ proc => proc.technology?.id === sourceTechnologyId
683
+ );
684
+ if (hasSameTechnology) {
685
+ throw new Error(
686
+ `Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} already has a procedure with technology "${sourceProcedure.technology?.name || sourceTechnologyId}" in this clinic branch`
687
+ );
688
+ }
689
+
690
+ practitioners.push(practitioner);
691
+ }
692
+
693
+ // 4. Create procedures in batch
694
+ const batch = writeBatch(this.db);
695
+ const newProcedures: Omit<Procedure, 'createdAt' | 'updatedAt'>[] = [];
696
+
697
+ for (const practitioner of practitioners) {
698
+ const newProcedureId = this.generateId();
699
+
700
+ // Create aggregated doctor info for the new procedure
701
+ const doctorInfo = {
702
+ id: practitioner.id,
703
+ name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
704
+ description: practitioner.basicInfo.bio || '',
705
+ photo:
706
+ typeof practitioner.basicInfo.profileImageUrl === 'string'
707
+ ? practitioner.basicInfo.profileImageUrl
708
+ : '',
709
+ rating: practitioner.reviewInfo?.averageRating || 0,
710
+ services: practitioner.procedures || [],
711
+ };
712
+
713
+ // Construct the new procedure object
714
+ const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
715
+ ...sourceProcedure,
716
+ id: newProcedureId,
717
+ practitionerId: practitioner.id,
718
+ doctorInfo,
719
+
720
+ // Reset review info for the new procedure
721
+ reviewInfo: {
722
+ totalReviews: 0,
723
+ averageRating: 0,
724
+ effectivenessOfTreatment: 0,
725
+ outcomeExplanation: 0,
726
+ painManagement: 0,
727
+ followUpCare: 0,
728
+ valueForMoney: 0,
729
+ recommendationPercentage: 0,
730
+ },
731
+
732
+ // Apply any overrides if provided
733
+ ...(overrides?.price !== undefined && { price: overrides.price }),
734
+ ...(overrides?.duration !== undefined && { duration: overrides.duration }),
735
+ ...(overrides?.description !== undefined && { description: overrides.description }),
736
+
737
+ // Ensure it's active by default unless specified otherwise
738
+ isActive: overrides?.isActive !== undefined ? overrides.isActive : true,
739
+ };
740
+
741
+ newProcedures.push(newProcedure);
742
+
743
+ // Add to batch
744
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, newProcedureId);
745
+ batch.set(procedureRef, {
746
+ ...newProcedure,
747
+ createdAt: serverTimestamp(),
748
+ updatedAt: serverTimestamp(),
749
+ });
750
+ }
751
+
752
+ // 5. Commit batch
753
+ await batch.commit();
754
+
755
+ // 6. Fetch and return the created procedures
756
+ const createdProcedures = await Promise.all(
757
+ newProcedures.map(p => this.getProcedure(p.id))
758
+ );
759
+
760
+ return createdProcedures.filter((p): p is Procedure => p !== null);
761
+ }
762
+
763
+ /**
764
+ * Creates multiple procedures for a list of practitioners based on common data.
765
+ * This method is optimized for bulk creation to reduce database reads and writes.
766
+ *
767
+ * @param baseData - The base data for the procedures to be created, omitting the practitionerId.
768
+ * @param practitionerIds - An array of practitioner IDs for whom the procedures will be created.
769
+ * @returns A promise that resolves to an array of the newly created procedures.
770
+ */
771
+ async bulkCreateProcedures(
772
+ baseData: Omit<CreateProcedureData, 'practitionerId'>,
773
+ practitionerIds: string[],
774
+ ): Promise<Procedure[]> {
775
+ // 1. Validation
776
+ if (!practitionerIds || practitionerIds.length === 0) {
777
+ throw new Error('Practitioner IDs array cannot be empty.');
778
+ }
779
+
780
+ // Check if this is a product-free procedure
781
+ const isProductFree = !baseData.productId;
782
+
783
+ // Add a dummy practitionerId for the validation schema to pass
784
+ const validationData = { ...baseData, practitionerId: practitionerIds[0] };
785
+ const validatedData = createProcedureSchema.parse(validationData);
786
+
787
+ // 2. Fetch common data once to avoid redundant reads
788
+ const baseEntitiesPromises: Promise<Category | Subcategory | Technology | Product | null>[] = [
789
+ this.categoryService.getById(validatedData.categoryId),
790
+ this.subcategoryService.getById(validatedData.categoryId, validatedData.subcategoryId),
791
+ this.technologyService.getById(validatedData.technologyId),
792
+ ];
793
+
794
+ // Only fetch product if productId is provided
795
+ if (!isProductFree) {
796
+ baseEntitiesPromises.push(
797
+ this.productService.getById(validatedData.technologyId, validatedData.productId!)
798
+ );
799
+ }
800
+
801
+ // Fetch clinic separately to maintain type safety
802
+ const clinicSnapshotPromise = getDoc(doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId));
803
+
804
+ const [baseResults, clinicSnapshot] = await Promise.all([
805
+ Promise.all(baseEntitiesPromises),
806
+ clinicSnapshotPromise
807
+ ]);
808
+
809
+ const category = baseResults[0] as Category | null;
810
+ const subcategory = baseResults[1] as Subcategory | null;
811
+ const technology = baseResults[2] as Technology | null;
812
+ const product = isProductFree ? undefined : ((baseResults[3] as Product | null) || undefined);
813
+
814
+ if (!category || !subcategory || !technology) {
815
+ throw new Error('One or more required base entities not found');
816
+ }
817
+
818
+ // For regular procedures, validate product exists
819
+ if (!isProductFree && !product) {
820
+ throw new Error('Product not found for regular procedure');
821
+ }
822
+
823
+ if (!clinicSnapshot || !clinicSnapshot.exists()) {
824
+ throw new Error(`Clinic with ID ${validatedData.clinicBranchId} not found`);
825
+ }
826
+ const clinic = clinicSnapshot.data() as Clinic;
827
+
828
+ // 3. Handle media uploads once for efficiency
829
+ let processedPhotos: string[] = [];
830
+ if (validatedData.photos && validatedData.photos.length > 0) {
831
+ const batchId = this.generateId(); // Use a single ID for all media in this batch
832
+ processedPhotos = await this.processMediaArray(
833
+ validatedData.photos,
834
+ batchId,
835
+ 'procedure-photos-batch',
836
+ );
837
+ }
838
+
839
+ // If no photos provided and technology has a photoTemplate, use it as default photo
840
+ if (processedPhotos.length === 0 && technology.photoTemplate) {
841
+ console.log(`[ProcedureService] Using technology photoTemplate as default photo for bulk create: ${technology.photoTemplate}`);
842
+ const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
843
+ if (photoTemplateUrl) {
844
+ processedPhotos.push(photoTemplateUrl);
845
+ } else {
846
+ console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
847
+ }
848
+ }
849
+
850
+ // Transform productsMetadata from validation format to ProcedureProduct format
851
+ const transformedProductsMetadata = await this.transformProductsMetadata(
852
+ validatedData.productsMetadata,
853
+ validatedData.technologyId,
854
+ );
855
+
856
+ // 4. Fetch all practitioner data efficiently
857
+ const practitionersMap = new Map<string, Practitioner>();
858
+ // Use 'in' query in chunks of 30, as this is the Firestore limit
859
+ for (let i = 0; i < practitionerIds.length; i += 30) {
860
+ const chunk = practitionerIds.slice(i, i + 30);
861
+ const practitionersQuery = query(
862
+ collection(this.db, PRACTITIONERS_COLLECTION),
863
+ where(documentId(), 'in', chunk),
864
+ );
865
+ const practitionersSnapshot = await getDocs(practitionersQuery);
866
+ practitionersSnapshot.docs.forEach(doc => {
867
+ practitionersMap.set(doc.id, doc.data() as Practitioner);
868
+ });
869
+ }
870
+
871
+ // Verify all practitioners were found
872
+ if (practitionersMap.size !== practitionerIds.length) {
873
+ const foundIds = Array.from(practitionersMap.keys());
874
+ const notFoundIds = practitionerIds.filter(id => !foundIds.includes(id));
875
+ throw new Error(`The following practitioners were not found: ${notFoundIds.join(', ')}`);
876
+ }
877
+
878
+ // 5. Check for duplicates across all practitioners before creating any procedures
879
+ const duplicatePractitioners: string[] = [];
880
+ const duplicateChecks = await Promise.all(
881
+ practitionerIds.map(async (practitionerId) => {
882
+ const existingProceduresQuery = query(
883
+ collection(this.db, PROCEDURES_COLLECTION),
884
+ where('practitionerId', '==', practitionerId),
885
+ where('clinicBranchId', '==', validatedData.clinicBranchId),
886
+ where('isActive', '==', true)
887
+ );
888
+ const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
889
+ const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
890
+
891
+ const hasSameTechnology = existingProcedures.some(
892
+ proc => proc.technology?.id === validatedData.technologyId
893
+ );
894
+
895
+ return { practitionerId, hasSameTechnology };
896
+ })
897
+ );
898
+
899
+ // Collect all practitioners with duplicates
900
+ duplicateChecks.forEach(({ practitionerId, hasSameTechnology }) => {
901
+ if (hasSameTechnology) {
902
+ duplicatePractitioners.push(practitionerId);
903
+ }
904
+ });
905
+
906
+ // If any duplicates found, throw error listing all of them
907
+ if (duplicatePractitioners.length > 0) {
908
+ const duplicateNames = duplicatePractitioners
909
+ .map(id => {
910
+ const practitioner = practitionersMap.get(id)!;
911
+ return `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`;
912
+ })
913
+ .join(', ');
914
+
915
+ throw new Error(
916
+ `The following practitioner(s) already have a procedure with technology "${technology?.name || validatedData.technologyId}" in this clinic branch: ${duplicateNames}. Please remove them from the selection and try again.`
917
+ );
918
+ }
919
+
920
+ // 6. Use a Firestore batch for atomic creation
921
+ const batch = writeBatch(this.db);
922
+ const createdProcedureIds: string[] = [];
923
+ const clinicInfo = {
924
+ id: clinicSnapshot.id,
925
+ name: clinic.name,
926
+ description: clinic.description || '',
927
+ featuredPhoto:
928
+ clinic.featuredPhotos && clinic.featuredPhotos.length > 0
929
+ ? typeof clinic.featuredPhotos[0] === 'string'
930
+ ? clinic.featuredPhotos[0]
931
+ : ''
932
+ : typeof clinic.coverPhoto === 'string'
933
+ ? clinic.coverPhoto
934
+ : '',
935
+ location: clinic.location,
936
+ contactInfo: clinic.contactInfo,
937
+ };
938
+
939
+ for (const practitionerId of practitionerIds) {
940
+ const practitioner = practitionersMap.get(practitionerId)!;
941
+
942
+ const doctorInfo = {
943
+ id: practitioner.id,
944
+ name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
945
+ description: practitioner.basicInfo.bio || '',
946
+ photo:
947
+ typeof practitioner.basicInfo.profileImageUrl === 'string'
948
+ ? practitioner.basicInfo.profileImageUrl
949
+ : '',
950
+ rating: practitioner.reviewInfo?.averageRating || 0,
951
+ services: practitioner.procedures || [],
952
+ };
953
+
954
+ const procedureId = this.generateId();
955
+ createdProcedureIds.push(procedureId);
956
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
957
+
958
+ // Construct the new procedure, reusing common data
959
+ const { productsMetadata: _, productId: __, photos: ___, ...validatedDataWithoutProductsMetadata } = validatedData;
960
+ const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
961
+ id: procedureId,
962
+ ...validatedDataWithoutProductsMetadata,
963
+ nameLower: (validatedData as any).nameLower || validatedData.name.toLowerCase(),
964
+ practitionerId: practitionerId, // Override practitionerId with the correct one
965
+ photos: processedPhotos,
966
+ category,
967
+ subcategory,
968
+ technology,
969
+ ...(product && { product }), // Only include product field if it exists (Firestore doesn't allow undefined)
970
+ productsMetadata: transformedProductsMetadata, // Use transformed data, not original
971
+ blockingConditions: technology.blockingConditions,
972
+ contraindications: technology.contraindications || [],
973
+ contraindicationIds: technology.contraindications?.map(c => c.id) || [],
974
+ treatmentBenefits: technology.benefits,
975
+ treatmentBenefitIds: Array.isArray(technology.benefits)
976
+ ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
977
+ : [],
978
+ preRequirements: technology.requirements.pre,
979
+ postRequirements: technology.requirements.post,
980
+ certificationRequirement: technology.certificationRequirement,
981
+ documentationTemplates: technology?.documentationTemplates || [],
982
+ clinicInfo,
983
+ doctorInfo, // Set specific doctor info
984
+ reviewInfo: {
985
+ totalReviews: 0,
986
+ averageRating: 0,
987
+ effectivenessOfTreatment: 0,
988
+ outcomeExplanation: 0,
989
+ painManagement: 0,
990
+ followUpCare: 0,
991
+ valueForMoney: 0,
992
+ recommendationPercentage: 0,
993
+ },
994
+ isActive: true,
995
+ };
996
+
997
+ // 🔥 DEBUG: Find undefined fields before writing to Firestore
998
+ console.log('🔥🔥🔥 BULK CREATE - Processing procedure:', procedureId, 'for practitioner:', practitionerId);
999
+ console.log('🔥🔥🔥 FULL PROCEDURE OBJECT:', JSON.stringify(newProcedure, null, 2));
1000
+
1001
+ const undefinedFields: string[] = [];
1002
+ Object.entries(newProcedure).forEach(([key, value]) => {
1003
+ if (value === undefined) {
1004
+ undefinedFields.push(key);
1005
+ }
1006
+ });
1007
+ if (undefinedFields.length > 0) {
1008
+ console.error('🔥🔥🔥 UNDEFINED FIELDS DETECTED:', undefinedFields);
1009
+ throw new Error(`Cannot write procedure with undefined fields: ${undefinedFields.join(', ')}`);
1010
+ }
1011
+ console.log('🔥🔥🔥 NO UNDEFINED FIELDS - Proceeding with batch.set');
1012
+
1013
+ batch.set(procedureRef, {
1014
+ ...newProcedure,
1015
+ createdAt: serverTimestamp(),
1016
+ updatedAt: serverTimestamp(),
1017
+ });
1018
+ }
1019
+
1020
+ // 7. Commit the atomic batch write
1021
+ await batch.commit();
1022
+
1023
+ // 8. Fetch and return the newly created procedures
1024
+ const fetchedProcedures: Procedure[] = [];
1025
+ for (let i = 0; i < createdProcedureIds.length; i += 30) {
1026
+ const chunk = createdProcedureIds.slice(i, i + 30);
1027
+ const q = query(collection(this.db, PROCEDURES_COLLECTION), where(documentId(), 'in', chunk));
1028
+ const snapshot = await getDocs(q);
1029
+ snapshot.forEach(doc => {
1030
+ fetchedProcedures.push(doc.data() as Procedure);
1031
+ });
1032
+ }
1033
+
1034
+ return fetchedProcedures;
1035
+ }
1036
+
1037
+ /**
1038
+ * Gets a procedure by ID
1039
+ * @param id - The ID of the procedure to get
1040
+ * @returns The procedure if found, null otherwise
1041
+ */
1042
+ async getProcedure(id: string): Promise<Procedure | null> {
1043
+ const docRef = doc(this.db, PROCEDURES_COLLECTION, id);
1044
+ const docSnap = await getDoc(docRef);
1045
+
1046
+ if (!docSnap.exists()) {
1047
+ return null;
1048
+ }
1049
+
1050
+ return docSnap.data() as Procedure;
1051
+ }
1052
+
1053
+ /**
1054
+ * Gets all procedures for a clinic branch
1055
+ * @param clinicBranchId - The ID of the clinic branch
1056
+ * @returns List of procedures
1057
+ */
1058
+ async getProceduresByClinicBranch(clinicBranchId: string): Promise<Procedure[]> {
1059
+ const q = query(
1060
+ collection(this.db, PROCEDURES_COLLECTION),
1061
+ where('clinicBranchId', '==', clinicBranchId),
1062
+ where('isActive', '==', true),
1063
+ );
1064
+ const snapshot = await getDocs(q);
1065
+ return snapshot.docs.map(doc => doc.data() as Procedure);
1066
+ }
1067
+
1068
+ /**
1069
+ * Gets all procedures for a practitioner
1070
+ * @param practitionerId - The ID of the practitioner
1071
+ * @param clinicBranchId - Optional clinic branch ID to filter by
1072
+ * @param excludeDraftPractitioners - Whether to exclude procedures if the practitioner is in DRAFT status
1073
+ * @returns List of procedures
1074
+ */
1075
+ async getProceduresByPractitioner(
1076
+ practitionerId: string,
1077
+ clinicBranchId?: string,
1078
+ excludeDraftPractitioners: boolean = true
1079
+ ): Promise<Procedure[]> {
1080
+ const constraints: QueryConstraint[] = [
1081
+ where('practitionerId', '==', practitionerId),
1082
+ where('isActive', '==', true),
1083
+ ];
1084
+
1085
+ if (clinicBranchId) {
1086
+ constraints.push(where('clinicBranchId', '==', clinicBranchId));
1087
+ }
1088
+
1089
+ const q = query(
1090
+ collection(this.db, PROCEDURES_COLLECTION),
1091
+ ...constraints
1092
+ );
1093
+ const snapshot = await getDocs(q);
1094
+ const procedures = snapshot.docs.map(doc => doc.data() as Procedure);
1095
+
1096
+ // If we need to exclude draft practitioners and have the service available
1097
+ if (excludeDraftPractitioners && this.practitionerService) {
1098
+ try {
1099
+ const practitioner = await this.practitionerService.getPractitioner(practitionerId);
1100
+ if (practitioner && practitioner.status === PractitionerStatus.DRAFT) {
1101
+ console.log(`[ProcedureService] Excluding procedures for draft practitioner ${practitionerId}`);
1102
+ return [];
1103
+ }
1104
+ } catch (error) {
1105
+ console.error(`[ProcedureService] Error checking practitioner status for ${practitionerId}:`, error);
1106
+ // On error, default to returning procedures to avoid breaking UI
1107
+ }
1108
+ }
1109
+
1110
+ return procedures;
1111
+ }
1112
+
1113
+ /**
1114
+ * Gets all inactive procedures for a practitioner
1115
+ * @param practitionerId - The ID of the practitioner
1116
+ * @returns List of inactive procedures
1117
+ */
1118
+ async getInactiveProceduresByPractitioner(practitionerId: string): Promise<Procedure[]> {
1119
+ const q = query(
1120
+ collection(this.db, PROCEDURES_COLLECTION),
1121
+ where('practitionerId', '==', practitionerId),
1122
+ where('isActive', '==', false),
1123
+ );
1124
+ const snapshot = await getDocs(q);
1125
+ return snapshot.docs.map(doc => doc.data() as Procedure);
1126
+ }
1127
+
1128
+ /**
1129
+ * Updates a procedure
1130
+ * @param id - The ID of the procedure to update
1131
+ * @param data - The data to update the procedure with
1132
+ * @returns The updated procedure
1133
+ */
1134
+ async updateProcedure(id: string, data: UpdateProcedureData): Promise<Procedure> {
1135
+ const validatedData = updateProcedureSchema.parse(data);
1136
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
1137
+ const procedureSnapshot = await getDoc(procedureRef);
1138
+
1139
+ if (!procedureSnapshot.exists()) {
1140
+ throw new Error(`Procedure with ID ${id} not found`);
1141
+ }
1142
+
1143
+ const existingProcedure = procedureSnapshot.data() as Procedure;
1144
+ let updatedProcedureData: Partial<Procedure> = {};
1145
+
1146
+ // Copy validated simple fields
1147
+ if (validatedData.name !== undefined) updatedProcedureData.name = validatedData.name;
1148
+ if (validatedData.description !== undefined)
1149
+ updatedProcedureData.description = validatedData.description;
1150
+ if (validatedData.price !== undefined) updatedProcedureData.price = validatedData.price;
1151
+ if (validatedData.currency !== undefined)
1152
+ updatedProcedureData.currency = validatedData.currency;
1153
+ if (validatedData.pricingMeasure !== undefined)
1154
+ updatedProcedureData.pricingMeasure = validatedData.pricingMeasure;
1155
+ if (validatedData.duration !== undefined)
1156
+ updatedProcedureData.duration = validatedData.duration;
1157
+ if (validatedData.isActive !== undefined)
1158
+ updatedProcedureData.isActive = validatedData.isActive;
1159
+
1160
+ let practitionerChanged = false;
1161
+ let clinicChanged = false;
1162
+ const oldPractitionerId = existingProcedure.practitionerId;
1163
+ const oldClinicId = existingProcedure.clinicBranchId;
1164
+ let newPractitioner: Practitioner | null = null;
1165
+ let newClinic: Clinic | null = null;
1166
+
1167
+ // Process photos if provided
1168
+ if (validatedData.photos !== undefined) {
1169
+ updatedProcedureData.photos = await this.processMediaArray(
1170
+ validatedData.photos,
1171
+ id,
1172
+ 'procedure-photos',
1173
+ );
1174
+ }
1175
+
1176
+ // Transform productsMetadata if provided
1177
+ if (validatedData.productsMetadata !== undefined) {
1178
+ const technologyId = validatedData.technologyId ?? existingProcedure.technology.id;
1179
+ if (!technologyId) {
1180
+ throw new Error('Technology ID is required for updating products metadata');
1181
+ }
1182
+ updatedProcedureData.productsMetadata = await this.transformProductsMetadata(
1183
+ validatedData.productsMetadata,
1184
+ technologyId,
1185
+ );
1186
+ }
1187
+
1188
+ // --- Prepare updates and fetch new related data if IDs change ---
1189
+
1190
+ // Handle Practitioner Change
1191
+ if (validatedData.practitionerId && validatedData.practitionerId !== oldPractitionerId) {
1192
+ practitionerChanged = true;
1193
+ const newPractitionerRef = doc(
1194
+ this.db,
1195
+ PRACTITIONERS_COLLECTION,
1196
+ validatedData.practitionerId,
1197
+ );
1198
+ const newPractitionerSnap = await getDoc(newPractitionerRef);
1199
+ if (!newPractitionerSnap.exists())
1200
+ throw new Error(`New Practitioner ${validatedData.practitionerId} not found`);
1201
+ newPractitioner = newPractitionerSnap.data() as Practitioner;
1202
+ // Update doctorInfo within the procedure document
1203
+ updatedProcedureData.doctorInfo = {
1204
+ id: newPractitioner.id,
1205
+ name: `${newPractitioner.basicInfo.firstName} ${newPractitioner.basicInfo.lastName}`,
1206
+ description: newPractitioner.basicInfo.bio || '',
1207
+ photo:
1208
+ typeof newPractitioner.basicInfo.profileImageUrl === 'string'
1209
+ ? newPractitioner.basicInfo.profileImageUrl
1210
+ : '', // Default to empty string if not a processed URL
1211
+ rating: newPractitioner.reviewInfo?.averageRating || 0,
1212
+ services: newPractitioner.procedures || [],
1213
+ };
1214
+ }
1215
+
1216
+ // Handle Clinic Change
1217
+ if (validatedData.clinicBranchId && validatedData.clinicBranchId !== oldClinicId) {
1218
+ clinicChanged = true;
1219
+ const newClinicRef = doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId);
1220
+ const newClinicSnap = await getDoc(newClinicRef);
1221
+ if (!newClinicSnap.exists())
1222
+ throw new Error(`New Clinic ${validatedData.clinicBranchId} not found`);
1223
+ newClinic = newClinicSnap.data() as Clinic;
1224
+ // Update clinicInfo within the procedure document
1225
+ updatedProcedureData.clinicInfo = {
1226
+ id: newClinic.id,
1227
+ name: newClinic.name,
1228
+ description: newClinic.description || '',
1229
+ featuredPhoto:
1230
+ newClinic.featuredPhotos && newClinic.featuredPhotos.length > 0
1231
+ ? typeof newClinic.featuredPhotos[0] === 'string'
1232
+ ? newClinic.featuredPhotos[0]
1233
+ : ''
1234
+ : typeof newClinic.coverPhoto === 'string'
1235
+ ? newClinic.coverPhoto
1236
+ : '',
1237
+ location: newClinic.location,
1238
+ contactInfo: newClinic.contactInfo,
1239
+ };
1240
+ }
1241
+
1242
+ // Handle Category/Subcategory/Technology/Product Changes
1243
+ let finalCategoryId = existingProcedure.category.id;
1244
+ if (validatedData.name) {
1245
+ updatedProcedureData.nameLower = validatedData.name.toLowerCase();
1246
+ }
1247
+ if (validatedData.categoryId) {
1248
+ const category = await this.categoryService.getById(validatedData.categoryId);
1249
+ if (!category) throw new Error(`Category ${validatedData.categoryId} not found`);
1250
+ updatedProcedureData.category = category;
1251
+ finalCategoryId = category.id; // Update finalCategoryId if category changed
1252
+ }
1253
+
1254
+ // Only fetch subcategory if its ID is provided AND we have a valid finalCategoryId
1255
+ if (validatedData.subcategoryId && finalCategoryId) {
1256
+ const subcategory = await this.subcategoryService.getById(
1257
+ finalCategoryId,
1258
+ validatedData.subcategoryId,
1259
+ );
1260
+ if (!subcategory)
1261
+ throw new Error(
1262
+ `Subcategory ${validatedData.subcategoryId} not found for category ${finalCategoryId}`,
1263
+ );
1264
+ updatedProcedureData.subcategory = subcategory;
1265
+ } else if (validatedData.subcategoryId) {
1266
+ console.warn('Attempted to update subcategory without a valid categoryId');
1267
+ }
1268
+
1269
+ let finalTechnologyId = existingProcedure.technology.id;
1270
+ if (validatedData.technologyId) {
1271
+ const technology = await this.technologyService.getById(validatedData.technologyId);
1272
+ if (!technology) throw new Error(`Technology ${validatedData.technologyId} not found`);
1273
+ updatedProcedureData.technology = technology;
1274
+ finalTechnologyId = technology.id; // Update finalTechnologyId if technology changed
1275
+ // Update related fields derived from technology
1276
+ updatedProcedureData.blockingConditions = technology.blockingConditions;
1277
+ updatedProcedureData.contraindications = technology.contraindications || [];
1278
+ updatedProcedureData.contraindicationIds = technology.contraindications?.map(c => c.id) || [];
1279
+ updatedProcedureData.treatmentBenefits = technology.benefits;
1280
+ updatedProcedureData.treatmentBenefitIds = Array.isArray(technology.benefits)
1281
+ ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
1282
+ : [];
1283
+ updatedProcedureData.preRequirements = technology.requirements.pre;
1284
+ updatedProcedureData.postRequirements = technology.requirements.post;
1285
+ updatedProcedureData.certificationRequirement = technology.certificationRequirement;
1286
+ updatedProcedureData.documentationTemplates = technology.documentationTemplates || [];
1287
+ }
1288
+
1289
+ // Only fetch product if its ID is provided AND we have a valid finalTechnologyId
1290
+ if (validatedData.productId && finalTechnologyId) {
1291
+ const product = await this.productService.getById(finalTechnologyId, validatedData.productId);
1292
+ if (!product)
1293
+ throw new Error(
1294
+ `Product ${validatedData.productId} not found for technology ${finalTechnologyId}`,
1295
+ );
1296
+ updatedProcedureData.product = product;
1297
+ } else if (validatedData.productId) {
1298
+ console.warn('Attempted to update product without a valid technologyId');
1299
+ }
1300
+
1301
+ // Update the procedure document
1302
+ await updateDoc(procedureRef, {
1303
+ ...updatedProcedureData,
1304
+ updatedAt: serverTimestamp(),
1305
+ });
1306
+
1307
+ // Return the updated procedure
1308
+ const updatedSnapshot = await getDoc(procedureRef);
1309
+ return updatedSnapshot.data() as Procedure;
1310
+ }
1311
+
1312
+ /**
1313
+ * Deactivates a procedure (soft delete)
1314
+ * @param id - The ID of the procedure to deactivate
1315
+ */
1316
+ async deactivateProcedure(id: string): Promise<void> {
1317
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
1318
+ const procedureSnap = await getDoc(procedureRef);
1319
+ if (!procedureSnap.exists()) {
1320
+ console.warn(`Procedure ${id} not found for deactivation.`);
1321
+ return;
1322
+ }
1323
+
1324
+ // Mark procedure as inactive
1325
+ await updateDoc(procedureRef, {
1326
+ isActive: false,
1327
+ updatedAt: serverTimestamp(),
1328
+ });
1329
+ }
1330
+
1331
+ /**
1332
+ * Deletes a procedure permanently
1333
+ * @param id - The ID of the procedure to delete
1334
+ * @returns A boolean indicating if the deletion was successful
1335
+ */
1336
+ async deleteProcedure(id: string): Promise<boolean> {
1337
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
1338
+ const procedureSnapshot = await getDoc(procedureRef);
1339
+
1340
+ if (!procedureSnapshot.exists()) {
1341
+ // Already deleted or never existed
1342
+ return false;
1343
+ }
1344
+
1345
+ // Delete the procedure document
1346
+ await deleteDoc(procedureRef);
1347
+ return true;
1348
+ }
1349
+
1350
+ /**
1351
+ * Gets all procedures that a practitioner is certified to perform
1352
+ * @param practitioner - The practitioner's profile
1353
+ * @returns Object containing allowed technologies, families, categories, subcategories
1354
+ */
1355
+ async getAllowedTechnologies(practitioner: Practitioner): Promise<{
1356
+ technologies: Technology[];
1357
+ families: ProcedureFamily[];
1358
+ categories: string[];
1359
+ subcategories: string[];
1360
+ }> {
1361
+ // This logic depends on TechnologyService and remains valid
1362
+ const { technologies, families, categories, subcategories } =
1363
+ await this.technologyService.getAllowedTechnologies(practitioner);
1364
+
1365
+ return {
1366
+ technologies,
1367
+ families,
1368
+ categories,
1369
+ subcategories,
1370
+ };
1371
+ }
1372
+
1373
+ /**
1374
+ * Gets all procedures with optional pagination
1375
+ *
1376
+ * @param pagination - Optional number of procedures per page (0 or undefined returns all)
1377
+ * @param lastDoc - Optional last document for pagination (if continuing from a previous page)
1378
+ * @param excludeDraftPractitioners - Whether to exclude procedures from draft practitioners (default: true)
1379
+ * @returns Object containing procedures array and the last document for pagination
1380
+ */
1381
+ async getAllProcedures(
1382
+ pagination?: number,
1383
+ lastDoc?: any,
1384
+ excludeDraftPractitioners: boolean = true,
1385
+ ): Promise<{ procedures: Procedure[]; lastDoc: any }> {
1386
+ try {
1387
+ const proceduresCollection = collection(this.db, PROCEDURES_COLLECTION);
1388
+ let proceduresQuery = query(proceduresCollection);
1389
+
1390
+ // Apply pagination if specified
1391
+ if (pagination && pagination > 0) {
1392
+ const { limit, startAfter } = await import('firebase/firestore'); // Use dynamic import if needed top-level
1393
+
1394
+ if (lastDoc) {
1395
+ proceduresQuery = query(
1396
+ proceduresCollection,
1397
+ orderBy('name'), // Use imported orderBy
1398
+ startAfter(lastDoc),
1399
+ limit(pagination),
1400
+ );
1401
+ } else {
1402
+ proceduresQuery = query(proceduresCollection, orderBy('name'), limit(pagination)); // Use imported orderBy
1403
+ }
1404
+ } else {
1405
+ proceduresQuery = query(proceduresCollection, orderBy('name')); // Use imported orderBy
1406
+ }
1407
+
1408
+ const proceduresSnapshot = await getDocs(proceduresQuery);
1409
+ const lastVisible = proceduresSnapshot.docs[proceduresSnapshot.docs.length - 1];
1410
+
1411
+ let procedures = proceduresSnapshot.docs.map(doc => {
1412
+ const data = doc.data() as Procedure;
1413
+ return {
1414
+ ...data,
1415
+ id: doc.id, // Ensure ID is present
1416
+ };
1417
+ });
1418
+
1419
+ // Filter out procedures from draft practitioners if requested
1420
+ if (excludeDraftPractitioners) {
1421
+ procedures = await this.filterDraftPractitionerProcedures(procedures);
1422
+ }
1423
+
1424
+ return {
1425
+ procedures,
1426
+ lastDoc: lastVisible,
1427
+ };
1428
+ } catch (error) {
1429
+ console.error('[PROCEDURE_SERVICE] Error getting all procedures:', error);
1430
+ throw error;
1431
+ }
1432
+ }
1433
+
1434
+ /**
1435
+ * Searches and filters procedures based on multiple criteria
1436
+ *
1437
+ * @note Frontend MORA da šalje ceo snapshot (ili barem sva polja po kojima sortiraš, npr. nameLower) kao lastDoc za paginaciju, a ne samo id!
1438
+ *
1439
+ * @param filters - Various filters to apply
1440
+ * @param filters.nameSearch - Optional search text for procedure name
1441
+ * @param filters.treatmentBenefitIds - Optional array of treatment benefits to filter by
1442
+ * @param filters.procedureFamily - Optional procedure family to filter by
1443
+ * @param filters.procedureCategory - Optional procedure category to filter by
1444
+ * @param filters.procedureSubcategory - Optional procedure subcategory to filter by
1445
+ * @param filters.procedureTechnology - Optional procedure technology to filter by
1446
+ * @param filters.location - Optional location for distance-based search
1447
+ * @param filters.radiusInKm - Optional radius in kilometers (required if location is provided)
1448
+ * @param filters.minPrice - Optional minimum price
1449
+ * @param filters.maxPrice - Optional maximum price
1450
+ * @param filters.minRating - Optional minimum rating (0-5)
1451
+ * @param filters.maxRating - Optional maximum rating (0-5)
1452
+ * @param filters.pagination - Optional number of results per page
1453
+ * @param filters.lastDoc - Optional last document for pagination
1454
+ * @param filters.isActive - Optional filter for active procedures only
1455
+ * @returns Filtered procedures and the last document for pagination
1456
+ */
1457
+ async getProceduresByFilters(filters: {
1458
+ nameSearch?: string;
1459
+ treatmentBenefits?: string[];
1460
+ procedureFamily?: ProcedureFamily;
1461
+ procedureCategory?: string;
1462
+ procedureSubcategory?: string;
1463
+ procedureTechnology?: string;
1464
+ location?: { latitude: number; longitude: number };
1465
+ radiusInKm?: number;
1466
+ minPrice?: number;
1467
+ maxPrice?: number;
1468
+ minRating?: number;
1469
+ maxRating?: number;
1470
+ pagination?: number;
1471
+ lastDoc?: any;
1472
+ isActive?: boolean;
1473
+ practitionerId?: string;
1474
+ clinicId?: string;
1475
+ }): Promise<{
1476
+ procedures: (Procedure & { distance?: number })[];
1477
+ lastDoc: any;
1478
+ }> {
1479
+ try {
1480
+ console.log('[PROCEDURE_SERVICE] Starting procedure filtering with multiple strategies');
1481
+
1482
+ // Geo query debug i validacija
1483
+ if (filters.location && filters.radiusInKm) {
1484
+ console.log('[PROCEDURE_SERVICE] Executing geo query:', {
1485
+ location: filters.location,
1486
+ radius: filters.radiusInKm,
1487
+ serviceName: 'ProcedureService',
1488
+ });
1489
+
1490
+ // Validacija location podataka
1491
+ if (!filters.location.latitude || !filters.location.longitude) {
1492
+ console.warn('[PROCEDURE_SERVICE] Invalid location data:', filters.location);
1493
+ filters.location = undefined;
1494
+ filters.radiusInKm = undefined;
1495
+ }
1496
+ }
1497
+
1498
+ // Handle geo queries separately (they work differently)
1499
+ const isGeoQuery = filters.location && filters.radiusInKm && filters.radiusInKm > 0;
1500
+ if (isGeoQuery) {
1501
+ return this.handleGeoQuery(filters);
1502
+ }
1503
+
1504
+ // Base constraints (used in all strategies)
1505
+ const getBaseConstraints = () => {
1506
+ const constraints: QueryConstraint[] = [];
1507
+
1508
+ // Active status filter
1509
+ if (filters.isActive !== undefined) {
1510
+ constraints.push(where('isActive', '==', filters.isActive));
1511
+ } else {
1512
+ constraints.push(where('isActive', '==', true));
1513
+ }
1514
+
1515
+ // Filter constraints
1516
+ if (filters.procedureFamily) {
1517
+ constraints.push(where('family', '==', filters.procedureFamily));
1518
+ }
1519
+ if (filters.procedureCategory) {
1520
+ constraints.push(where('category.id', '==', filters.procedureCategory));
1521
+ }
1522
+ if (filters.procedureSubcategory) {
1523
+ constraints.push(where('subcategory.id', '==', filters.procedureSubcategory));
1524
+ }
1525
+ if (filters.procedureTechnology) {
1526
+ constraints.push(where('technology.id', '==', filters.procedureTechnology));
1527
+ }
1528
+ if (filters.practitionerId) {
1529
+ constraints.push(where('practitionerId', '==', filters.practitionerId));
1530
+ }
1531
+ if (filters.clinicId) {
1532
+ constraints.push(where('clinicBranchId', '==', filters.clinicId));
1533
+ }
1534
+ if (filters.minPrice !== undefined) {
1535
+ constraints.push(where('price', '>=', filters.minPrice));
1536
+ }
1537
+ if (filters.maxPrice !== undefined) {
1538
+ constraints.push(where('price', '<=', filters.maxPrice));
1539
+ }
1540
+ if (filters.minRating !== undefined) {
1541
+ constraints.push(where('reviewInfo.averageRating', '>=', filters.minRating));
1542
+ }
1543
+ if (filters.maxRating !== undefined) {
1544
+ constraints.push(where('reviewInfo.averageRating', '<=', filters.maxRating));
1545
+ }
1546
+ if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
1547
+ const benefitIdsToMatch = filters.treatmentBenefits;
1548
+ constraints.push(where('treatmentBenefitIds', 'array-contains-any', benefitIdsToMatch));
1549
+ }
1550
+
1551
+ return constraints;
1552
+ };
1553
+
1554
+ // Strategy 1: Try nameLower search if nameSearch exists
1555
+ if (filters.nameSearch && filters.nameSearch.trim()) {
1556
+ try {
1557
+ console.log('[PROCEDURE_SERVICE] Strategy 1: Trying nameLower search');
1558
+ const searchTerm = filters.nameSearch.trim().toLowerCase();
1559
+ const constraints = getBaseConstraints();
1560
+
1561
+ // Check if we have nested field filters that might conflict with orderBy
1562
+ const hasNestedFilters = !!(filters.procedureTechnology || filters.procedureCategory || filters.procedureSubcategory);
1563
+
1564
+ if (hasNestedFilters) {
1565
+ console.log('[PROCEDURE_SERVICE] Strategy 1: Has nested filters, will apply client-side after query');
1566
+ }
1567
+
1568
+ constraints.push(where('nameLower', '>=', searchTerm));
1569
+ constraints.push(where('nameLower', '<=', searchTerm + '\uf8ff'));
1570
+ constraints.push(orderBy('nameLower'));
1571
+
1572
+ if (filters.lastDoc) {
1573
+ if (typeof filters.lastDoc.data === 'function') {
1574
+ constraints.push(startAfter(filters.lastDoc));
1575
+ } else if (Array.isArray(filters.lastDoc)) {
1576
+ constraints.push(startAfter(...filters.lastDoc));
1577
+ } else {
1578
+ constraints.push(startAfter(filters.lastDoc));
1579
+ }
1580
+ }
1581
+ constraints.push(limit(filters.pagination || 10));
1582
+
1583
+ const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1584
+ const querySnapshot = await getDocs(q);
1585
+ let procedures = querySnapshot.docs.map(
1586
+ doc => ({ ...doc.data(), id: doc.id } as Procedure),
1587
+ );
1588
+
1589
+ // Apply client-side filters for nested fields if needed
1590
+ if (hasNestedFilters) {
1591
+ procedures = this.applyInMemoryFilters(procedures, filters);
1592
+ }
1593
+
1594
+ const lastDoc =
1595
+ querySnapshot.docs.length > 0
1596
+ ? querySnapshot.docs[querySnapshot.docs.length - 1]
1597
+ : null;
1598
+
1599
+ console.log(`[PROCEDURE_SERVICE] Strategy 1 success: ${procedures.length} procedures`);
1600
+
1601
+ // Fix Load More - ako je broj rezultata manji od pagination, nema više
1602
+ if (procedures.length < (filters.pagination || 10)) {
1603
+ return { procedures, lastDoc: null };
1604
+ }
1605
+ return { procedures, lastDoc };
1606
+ } catch (error) {
1607
+ console.log('[PROCEDURE_SERVICE] Strategy 1 failed:', error);
1608
+ }
1609
+ }
1610
+
1611
+ // Strategy 2: Try name field search as fallback
1612
+ if (filters.nameSearch && filters.nameSearch.trim()) {
1613
+ try {
1614
+ console.log('[PROCEDURE_SERVICE] Strategy 2: Trying name field search');
1615
+ const searchTerm = filters.nameSearch.trim().toLowerCase();
1616
+ const constraints = getBaseConstraints();
1617
+
1618
+ // Check if we have nested field filters that might conflict with orderBy
1619
+ const hasNestedFilters = !!(filters.procedureTechnology || filters.procedureCategory || filters.procedureSubcategory);
1620
+
1621
+ if (hasNestedFilters) {
1622
+ console.log('[PROCEDURE_SERVICE] Strategy 2: Has nested filters, will apply client-side after query');
1623
+ }
1624
+
1625
+ constraints.push(where('name', '>=', searchTerm));
1626
+ constraints.push(where('name', '<=', searchTerm + '\uf8ff'));
1627
+ constraints.push(orderBy('name'));
1628
+
1629
+ if (filters.lastDoc) {
1630
+ if (typeof filters.lastDoc.data === 'function') {
1631
+ constraints.push(startAfter(filters.lastDoc));
1632
+ } else if (Array.isArray(filters.lastDoc)) {
1633
+ constraints.push(startAfter(...filters.lastDoc));
1634
+ } else {
1635
+ constraints.push(startAfter(filters.lastDoc));
1636
+ }
1637
+ }
1638
+ constraints.push(limit(filters.pagination || 10));
1639
+
1640
+ const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1641
+ const querySnapshot = await getDocs(q);
1642
+ let procedures = querySnapshot.docs.map(
1643
+ doc => ({ ...doc.data(), id: doc.id } as Procedure),
1644
+ );
1645
+
1646
+ // Apply client-side filters for nested fields if needed
1647
+ if (hasNestedFilters) {
1648
+ procedures = this.applyInMemoryFilters(procedures, filters);
1649
+ }
1650
+
1651
+ // Filter out procedures from draft practitioners
1652
+ procedures = await this.filterDraftPractitionerProcedures(procedures);
1653
+
1654
+ const lastDoc =
1655
+ querySnapshot.docs.length > 0
1656
+ ? querySnapshot.docs[querySnapshot.docs.length - 1]
1657
+ : null;
1658
+
1659
+ console.log(`[PROCEDURE_SERVICE] Strategy 2 success: ${procedures.length} procedures`);
1660
+
1661
+ // Fix Load More - ako je broj rezultata manji od pagination, nema više
1662
+ if (procedures.length < (filters.pagination || 10)) {
1663
+ return { procedures, lastDoc: null };
1664
+ }
1665
+ return { procedures, lastDoc };
1666
+ } catch (error) {
1667
+ console.log('[PROCEDURE_SERVICE] Strategy 2 failed:', error);
1668
+ }
1669
+ }
1670
+
1671
+ // Strategy 3: orderBy createdAt with client-side filtering
1672
+ // NOTE: This strategy excludes nested field filters (technology.id, category.id, subcategory.id)
1673
+ // from Firestore query because Firestore doesn't support orderBy on different field
1674
+ // when using where on nested fields without a composite index.
1675
+ // These filters are applied client-side instead.
1676
+ try {
1677
+ console.log(
1678
+ '[PROCEDURE_SERVICE] Strategy 3: Using createdAt orderBy with client-side filtering',
1679
+ {
1680
+ procedureTechnology: filters.procedureTechnology,
1681
+ hasTechnologyFilter: !!filters.procedureTechnology,
1682
+ },
1683
+ );
1684
+
1685
+ // Build constraints WITHOUT nested field filters (these will be applied client-side)
1686
+ const constraints: QueryConstraint[] = [];
1687
+
1688
+ // Active status filter
1689
+ if (filters.isActive !== undefined) {
1690
+ constraints.push(where('isActive', '==', filters.isActive));
1691
+ } else {
1692
+ constraints.push(where('isActive', '==', true));
1693
+ }
1694
+
1695
+ // Only include non-nested field filters in Firestore query
1696
+ if (filters.procedureFamily) {
1697
+ constraints.push(where('family', '==', filters.procedureFamily));
1698
+ }
1699
+ if (filters.practitionerId) {
1700
+ constraints.push(where('practitionerId', '==', filters.practitionerId));
1701
+ }
1702
+ if (filters.clinicId) {
1703
+ constraints.push(where('clinicBranchId', '==', filters.clinicId));
1704
+ }
1705
+ if (filters.minPrice !== undefined) {
1706
+ constraints.push(where('price', '>=', filters.minPrice));
1707
+ }
1708
+ if (filters.maxPrice !== undefined) {
1709
+ constraints.push(where('price', '<=', filters.maxPrice));
1710
+ }
1711
+ if (filters.minRating !== undefined) {
1712
+ constraints.push(where('reviewInfo.averageRating', '>=', filters.minRating));
1713
+ }
1714
+ if (filters.maxRating !== undefined) {
1715
+ constraints.push(where('reviewInfo.averageRating', '<=', filters.maxRating));
1716
+ }
1717
+ if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
1718
+ const benefitIdsToMatch = filters.treatmentBenefits;
1719
+ constraints.push(where('treatmentBenefitIds', 'array-contains-any', benefitIdsToMatch));
1720
+ }
1721
+
1722
+ // NOTE: We intentionally EXCLUDE these nested field filters from Firestore query:
1723
+ // - filters.procedureTechnology (technology.id)
1724
+ // - filters.procedureCategory (category.id)
1725
+ // - filters.procedureSubcategory (subcategory.id)
1726
+ // These will be applied client-side in applyInMemoryFilters
1727
+
1728
+ console.log(
1729
+ '[PROCEDURE_SERVICE] Strategy 3 Firestore constraints (nested filters excluded):',
1730
+ constraints.map(c => (c as any).fieldPath || 'unknown'),
1731
+ );
1732
+ constraints.push(orderBy('createdAt', 'desc'));
1733
+
1734
+ if (filters.lastDoc) {
1735
+ if (typeof filters.lastDoc.data === 'function') {
1736
+ constraints.push(startAfter(filters.lastDoc));
1737
+ } else if (Array.isArray(filters.lastDoc)) {
1738
+ constraints.push(startAfter(...filters.lastDoc));
1739
+ } else {
1740
+ constraints.push(startAfter(filters.lastDoc));
1741
+ }
1742
+ }
1743
+ constraints.push(limit(filters.pagination || 10));
1744
+
1745
+ const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1746
+ const querySnapshot = await getDocs(q);
1747
+ let procedures = querySnapshot.docs.map(
1748
+ doc => ({ ...doc.data(), id: doc.id } as Procedure),
1749
+ );
1750
+
1751
+ // Apply all client-side filters using centralized function
1752
+ console.log('[PROCEDURE_SERVICE] Before applyInMemoryFilters (Strategy 3):', {
1753
+ procedureCount: procedures.length,
1754
+ procedureTechnology: filters.procedureTechnology,
1755
+ filtersObject: {
1756
+ procedureTechnology: filters.procedureTechnology,
1757
+ procedureFamily: filters.procedureFamily,
1758
+ procedureCategory: filters.procedureCategory,
1759
+ procedureSubcategory: filters.procedureSubcategory,
1760
+ },
1761
+ });
1762
+ procedures = this.applyInMemoryFilters(procedures, filters);
1763
+
1764
+ // Filter out procedures from draft practitioners
1765
+ procedures = await this.filterDraftPractitionerProcedures(procedures);
1766
+
1767
+ console.log('[PROCEDURE_SERVICE] After applyInMemoryFilters (Strategy 3):', {
1768
+ procedureCount: procedures.length,
1769
+ });
1770
+
1771
+ const lastDoc =
1772
+ querySnapshot.docs.length > 0 ? querySnapshot.docs[querySnapshot.docs.length - 1] : null;
1773
+ console.log(`[PROCEDURE_SERVICE] Strategy 3 success: ${procedures.length} procedures`);
1774
+
1775
+ // Fix Load More - ako je broj rezultata manji od pagination, nema više
1776
+ if (procedures.length < (filters.pagination || 10)) {
1777
+ return { procedures, lastDoc: null };
1778
+ }
1779
+ return { procedures, lastDoc };
1780
+ } catch (error) {
1781
+ console.log('[PROCEDURE_SERVICE] Strategy 3 failed:', error);
1782
+ }
1783
+
1784
+ // Strategy 4: Minimal query fallback
1785
+ try {
1786
+ console.log('[PROCEDURE_SERVICE] Strategy 4: Minimal query fallback');
1787
+ const constraints: QueryConstraint[] = [
1788
+ where('isActive', '==', filters.isActive !== undefined ? filters.isActive : true),
1789
+ orderBy('createdAt', 'desc'),
1790
+ ];
1791
+ if (filters.practitionerId) {
1792
+ constraints.push(where('practitionerId', '==', filters.practitionerId));
1793
+ }
1794
+ if (filters.clinicId) {
1795
+ constraints.push(where('clinicBranchId', '==', filters.clinicId));
1796
+ }
1797
+ constraints.push(limit(filters.pagination || 10));
1798
+
1799
+ const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1800
+ const querySnapshot = await getDocs(q);
1801
+ let procedures = querySnapshot.docs.map(
1802
+ doc => ({ ...doc.data(), id: doc.id } as Procedure),
1803
+ );
1804
+
1805
+ // Apply all client-side filters using centralized function
1806
+ procedures = this.applyInMemoryFilters(procedures, filters);
1807
+
1808
+ // Filter out procedures from draft practitioners
1809
+ procedures = await this.filterDraftPractitionerProcedures(procedures);
1810
+
1811
+ const lastDoc =
1812
+ querySnapshot.docs.length > 0 ? querySnapshot.docs[querySnapshot.docs.length - 1] : null;
1813
+ console.log(`[PROCEDURE_SERVICE] Strategy 4 success: ${procedures.length} procedures`);
1814
+
1815
+ // Fix Load More - ako je broj rezultata manji od pagination, nema više
1816
+ if (procedures.length < (filters.pagination || 10)) {
1817
+ return { procedures, lastDoc: null };
1818
+ }
1819
+ return { procedures, lastDoc };
1820
+ } catch (error) {
1821
+ console.log('[PROCEDURE_SERVICE] Strategy 4 failed:', error);
1822
+ }
1823
+
1824
+ // All strategies failed
1825
+ console.log('[PROCEDURE_SERVICE] All strategies failed, returning empty result');
1826
+ return { procedures: [], lastDoc: null };
1827
+ } catch (error) {
1828
+ console.error('[PROCEDURE_SERVICE] Error filtering procedures:', error);
1829
+ return { procedures: [], lastDoc: null };
1830
+ }
1831
+ }
1832
+
1833
+ /**
1834
+ * Applies in-memory filters to procedures array
1835
+ * Used when Firestore queries fail or for complex filtering
1836
+ */
1837
+ private applyInMemoryFilters(
1838
+ procedures: Procedure[],
1839
+ filters: any,
1840
+ ): (Procedure & { distance?: number })[] {
1841
+ let filteredProcedures = [...procedures]; // Create copy to avoid mutating original
1842
+
1843
+ // Debug: Log what filters we received
1844
+ console.log('[PROCEDURE_SERVICE] applyInMemoryFilters called:', {
1845
+ procedureCount: procedures.length,
1846
+ procedureTechnology: filters.procedureTechnology,
1847
+ hasTechnologyFilter: !!filters.procedureTechnology,
1848
+ allFilterKeys: Object.keys(filters).filter(k => filters[k] !== undefined && filters[k] !== null),
1849
+ });
1850
+
1851
+ // Name search filter
1852
+ if (filters.nameSearch && filters.nameSearch.trim()) {
1853
+ const searchTerm = filters.nameSearch.trim().toLowerCase();
1854
+ filteredProcedures = filteredProcedures.filter(procedure => {
1855
+ const name = (procedure.name || '').toLowerCase();
1856
+ const nameLower = procedure.nameLower || '';
1857
+ return name.includes(searchTerm) || nameLower.includes(searchTerm);
1858
+ });
1859
+ console.log(`[PROCEDURE_SERVICE] Applied name filter, results: ${filteredProcedures.length}`);
1860
+ }
1861
+
1862
+ // Price filtering
1863
+ if (filters.minPrice !== undefined || filters.maxPrice !== undefined) {
1864
+ filteredProcedures = filteredProcedures.filter(procedure => {
1865
+ const price = procedure.price || 0;
1866
+ if (filters.minPrice !== undefined && price < filters.minPrice) return false;
1867
+ if (filters.maxPrice !== undefined && price > filters.maxPrice) return false;
1868
+ return true;
1869
+ });
1870
+ console.log(
1871
+ `[PROCEDURE_SERVICE] Applied price filter (${filters.minPrice}-${filters.maxPrice}), results: ${filteredProcedures.length}`,
1872
+ );
1873
+ }
1874
+
1875
+ // Rating filtering
1876
+ if (filters.minRating !== undefined || filters.maxRating !== undefined) {
1877
+ filteredProcedures = filteredProcedures.filter(procedure => {
1878
+ const rating = procedure.reviewInfo?.averageRating || 0;
1879
+ if (filters.minRating !== undefined && rating < filters.minRating) return false;
1880
+ if (filters.maxRating !== undefined && rating > filters.maxRating) return false;
1881
+ return true;
1882
+ });
1883
+ console.log(
1884
+ `[PROCEDURE_SERVICE] Applied rating filter, results: ${filteredProcedures.length}`,
1885
+ );
1886
+ }
1887
+
1888
+ // Treatment benefits filtering
1889
+ if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
1890
+ const benefitIdsToMatch = filters.treatmentBenefits;
1891
+ filteredProcedures = filteredProcedures.filter(procedure => {
1892
+ const procedureBenefitIds = procedure.treatmentBenefitIds || [];
1893
+ return benefitIdsToMatch.some((benefitId: string) =>
1894
+ procedureBenefitIds.includes(benefitId),
1895
+ );
1896
+ });
1897
+ console.log(
1898
+ `[PROCEDURE_SERVICE] Applied benefits filter, results: ${filteredProcedures.length}`,
1899
+ );
1900
+ }
1901
+
1902
+ // Procedure family filtering
1903
+ if (filters.procedureFamily) {
1904
+ filteredProcedures = filteredProcedures.filter(
1905
+ procedure => procedure.family === filters.procedureFamily,
1906
+ );
1907
+ console.log(
1908
+ `[PROCEDURE_SERVICE] Applied family filter, results: ${filteredProcedures.length}`,
1909
+ );
1910
+ }
1911
+
1912
+ // Category filtering
1913
+ if (filters.procedureCategory) {
1914
+ filteredProcedures = filteredProcedures.filter(
1915
+ procedure => procedure.category?.id === filters.procedureCategory,
1916
+ );
1917
+ console.log(
1918
+ `[PROCEDURE_SERVICE] Applied category filter, results: ${filteredProcedures.length}`,
1919
+ );
1920
+ }
1921
+
1922
+ // Subcategory filtering
1923
+ if (filters.procedureSubcategory) {
1924
+ filteredProcedures = filteredProcedures.filter(
1925
+ procedure => procedure.subcategory?.id === filters.procedureSubcategory,
1926
+ );
1927
+ console.log(
1928
+ `[PROCEDURE_SERVICE] Applied subcategory filter, results: ${filteredProcedures.length}`,
1929
+ );
1930
+ }
1931
+
1932
+ // Technology filtering
1933
+ if (filters.procedureTechnology) {
1934
+ const beforeCount = filteredProcedures.length;
1935
+ filteredProcedures = filteredProcedures.filter(
1936
+ procedure => procedure.technology?.id === filters.procedureTechnology,
1937
+ );
1938
+ console.log(
1939
+ `[PROCEDURE_SERVICE] Applied technology filter (${filters.procedureTechnology}), before: ${beforeCount}, after: ${filteredProcedures.length}`,
1940
+ );
1941
+ // Log sample technology IDs for debugging
1942
+ if (beforeCount > filteredProcedures.length) {
1943
+ const filteredOut = procedures
1944
+ .filter(p => p.technology?.id !== filters.procedureTechnology)
1945
+ .slice(0, 3)
1946
+ .map(p => ({ id: p.id, techId: p.technology?.id, name: p.name }));
1947
+ console.log('[PROCEDURE_SERVICE] Filtered out sample procedures:', filteredOut);
1948
+ }
1949
+ }
1950
+
1951
+ // Practitioner filtering
1952
+ if (filters.practitionerId) {
1953
+ filteredProcedures = filteredProcedures.filter(
1954
+ procedure => procedure.practitionerId === filters.practitionerId,
1955
+ );
1956
+ console.log(
1957
+ `[PROCEDURE_SERVICE] Applied practitioner filter, results: ${filteredProcedures.length}`,
1958
+ );
1959
+ }
1960
+
1961
+ // Clinic filtering
1962
+ if (filters.clinicId) {
1963
+ filteredProcedures = filteredProcedures.filter(
1964
+ procedure => procedure.clinicBranchId === filters.clinicId,
1965
+ );
1966
+ console.log(
1967
+ `[PROCEDURE_SERVICE] Applied clinic filter, results: ${filteredProcedures.length}`,
1968
+ );
1969
+ }
1970
+
1971
+ // Geo-radius filter
1972
+ if (filters.location && filters.radiusInKm && filters.radiusInKm > 0) {
1973
+ const location = filters.location;
1974
+ const radiusInKm = filters.radiusInKm;
1975
+ filteredProcedures = filteredProcedures.filter(procedure => {
1976
+ const clinicLocation = procedure.clinicInfo?.location;
1977
+ if (!clinicLocation?.latitude || !clinicLocation?.longitude) {
1978
+ return false;
1979
+ }
1980
+
1981
+ const distance =
1982
+ distanceBetween(
1983
+ [location.latitude, location.longitude],
1984
+ [clinicLocation.latitude, clinicLocation.longitude],
1985
+ ) / 1000; // Convert to km
1986
+
1987
+ // Attach distance for frontend sorting/display
1988
+ (procedure as any).distance = distance;
1989
+
1990
+ return distance <= radiusInKm;
1991
+ });
1992
+ console.log(`[PROCEDURE_SERVICE] Applied geo filter, results: ${filteredProcedures.length}`);
1993
+
1994
+ // Sort by distance when geo filtering is applied
1995
+ filteredProcedures.sort((a, b) => ((a as any).distance || 0) - ((b as any).distance || 0));
1996
+ }
1997
+
1998
+ return filteredProcedures as (Procedure & { distance?: number })[];
1999
+ }
2000
+
2001
+ private handleGeoQuery(filters: any): Promise<{
2002
+ procedures: (Procedure & { distance?: number })[];
2003
+ lastDoc: any;
2004
+ }> {
2005
+ console.log('[PROCEDURE_SERVICE] Executing geo query with geohash bounds');
2006
+ try {
2007
+ const location = filters.location;
2008
+ const radiusInKm = filters.radiusInKm;
2009
+
2010
+ if (!location || !radiusInKm) {
2011
+ return Promise.resolve({ procedures: [], lastDoc: null });
2012
+ }
2013
+
2014
+ const bounds = geohashQueryBounds([location.latitude, location.longitude], radiusInKm * 1000);
2015
+
2016
+ const fetches = bounds.map(b => {
2017
+ const constraints: QueryConstraint[] = [
2018
+ where('clinicInfo.location.geohash', '>=', b[0]),
2019
+ where('clinicInfo.location.geohash', '<=', b[1]),
2020
+ where('isActive', '==', filters.isActive !== undefined ? filters.isActive : true),
2021
+ ];
2022
+ if (filters.practitionerId) {
2023
+ constraints.push(where('practitionerId', '==', filters.practitionerId));
2024
+ }
2025
+ if (filters.clinicId) {
2026
+ constraints.push(where('clinicBranchId', '==', filters.clinicId));
2027
+ }
2028
+ return getDocs(query(collection(this.db, PROCEDURES_COLLECTION), ...constraints));
2029
+ });
2030
+
2031
+ return Promise.all(fetches)
2032
+ .then(snaps => {
2033
+ const collected: Procedure[] = [];
2034
+ snaps.forEach(snap => {
2035
+ snap.docs.forEach(d => collected.push({ ...(d.data() as Procedure), id: d.id }));
2036
+ });
2037
+
2038
+ // Deduplicate by id
2039
+ const uniqueMap = new Map<string, Procedure>();
2040
+ for (const p of collected) {
2041
+ uniqueMap.set(p.id, p);
2042
+ }
2043
+ let procedures = Array.from(uniqueMap.values());
2044
+
2045
+ // Apply remaining filters including precise distance and sorting
2046
+ procedures = this.applyInMemoryFilters(procedures, filters);
2047
+
2048
+ // Manual pagination
2049
+ const pageSize = filters.pagination || 10;
2050
+ let startIndex = 0;
2051
+ if (
2052
+ filters.lastDoc &&
2053
+ typeof filters.lastDoc === 'object' &&
2054
+ (filters.lastDoc as any).id
2055
+ ) {
2056
+ const idx = procedures.findIndex(p => p.id === (filters.lastDoc as any).id);
2057
+ if (idx >= 0) startIndex = idx + 1;
2058
+ }
2059
+ const page = procedures.slice(startIndex, startIndex + pageSize);
2060
+ const newLastDoc = page.length === pageSize ? page[page.length - 1] : null;
2061
+
2062
+ console.log(
2063
+ `[PROCEDURE_SERVICE] Geo query success: ${page.length} (of ${procedures.length}) within ${radiusInKm}km`,
2064
+ );
2065
+ return { procedures: page, lastDoc: newLastDoc };
2066
+ })
2067
+ .catch(err => {
2068
+ console.error('[PROCEDURE_SERVICE] Geo bounds fetch failed:', err);
2069
+ return { procedures: [], lastDoc: null };
2070
+ });
2071
+ } catch (error) {
2072
+ console.error('[PROCEDURE_SERVICE] Geo query failed:', error);
2073
+ return Promise.resolve({ procedures: [], lastDoc: null });
2074
+ }
2075
+ }
2076
+
2077
+ /**
2078
+ * Creates a consultation procedure without requiring a product
2079
+ * This is a special method for consultation procedures that don't use products
2080
+ * @param data - The data for creating a consultation procedure (without productId)
2081
+ * @returns The created procedure
2082
+ */
2083
+ async createConsultationProcedure(
2084
+ data: Omit<CreateProcedureData, 'productId'>,
2085
+ ): Promise<Procedure> {
2086
+ // Generate procedure ID first so we can use it for media uploads
2087
+ const procedureId = this.generateId();
2088
+
2089
+ // Get references to related entities (Category, Subcategory, Technology)
2090
+ // For consultation, we don't need a product
2091
+ const [category, subcategory, technology] = await Promise.all([
2092
+ this.categoryService.getByIdInternal(data.categoryId),
2093
+ this.subcategoryService.getByIdInternal(data.categoryId, data.subcategoryId),
2094
+ this.technologyService.getByIdInternal(data.technologyId),
2095
+ ]);
2096
+
2097
+ if (!category || !subcategory || !technology) {
2098
+ throw new Error('One or more required base entities not found');
2099
+ }
2100
+
2101
+ // Get clinic and practitioner information for aggregation
2102
+ const clinicRef = doc(this.db, CLINICS_COLLECTION, data.clinicBranchId);
2103
+ const clinicSnapshot = await getDoc(clinicRef);
2104
+ if (!clinicSnapshot.exists()) {
2105
+ throw new Error(`Clinic with ID ${data.clinicBranchId} not found`);
2106
+ }
2107
+ const clinic = clinicSnapshot.data() as Clinic;
2108
+
2109
+ const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, data.practitionerId);
2110
+ const practitionerSnapshot = await getDoc(practitionerRef);
2111
+ if (!practitionerSnapshot.exists()) {
2112
+ throw new Error(`Practitioner with ID ${data.practitionerId} not found`);
2113
+ }
2114
+ const practitioner = practitionerSnapshot.data() as Practitioner;
2115
+
2116
+ // Process photos if provided
2117
+ let processedPhotos: string[] = [];
2118
+ if (data.photos && data.photos.length > 0) {
2119
+ processedPhotos = await this.processMediaArray(data.photos, procedureId, 'procedure-photos');
2120
+ }
2121
+
2122
+ // If no photos provided and technology has a photoTemplate, use it as default photo
2123
+ if (processedPhotos.length === 0 && technology.photoTemplate) {
2124
+ console.log(`[ProcedureService] Using technology photoTemplate as default photo for consultation: ${technology.photoTemplate}`);
2125
+ const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
2126
+ if (photoTemplateUrl) {
2127
+ processedPhotos.push(photoTemplateUrl);
2128
+ } else {
2129
+ console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
2130
+ }
2131
+ }
2132
+
2133
+ // Transform productsMetadata from validation format to ProcedureProduct format
2134
+ // For consultations, this will return empty array since no products are provided
2135
+ const transformedProductsMetadata = await this.transformProductsMetadata(
2136
+ data.productsMetadata,
2137
+ data.technologyId,
2138
+ );
2139
+
2140
+ // Create aggregated clinic info for the procedure document
2141
+ const clinicInfo = {
2142
+ id: clinicSnapshot.id,
2143
+ name: clinic.name,
2144
+ description: clinic.description || '',
2145
+ featuredPhoto:
2146
+ clinic.featuredPhotos && clinic.featuredPhotos.length > 0
2147
+ ? typeof clinic.featuredPhotos[0] === 'string'
2148
+ ? clinic.featuredPhotos[0]
2149
+ : ''
2150
+ : typeof clinic.coverPhoto === 'string'
2151
+ ? clinic.coverPhoto
2152
+ : '',
2153
+ location: clinic.location,
2154
+ contactInfo: clinic.contactInfo,
2155
+ };
2156
+
2157
+ // Create aggregated doctor info for the procedure document
2158
+ const doctorInfo = {
2159
+ id: practitionerSnapshot.id,
2160
+ name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
2161
+ description: practitioner.basicInfo.bio || '',
2162
+ photo:
2163
+ typeof practitioner.basicInfo.profileImageUrl === 'string'
2164
+ ? practitioner.basicInfo.profileImageUrl
2165
+ : '',
2166
+ rating: practitioner.reviewInfo?.averageRating || 0,
2167
+ services: practitioner.procedures || [],
2168
+ };
2169
+
2170
+ // Create the procedure object
2171
+ const { productsMetadata: _, ...dataWithoutProductsMetadata } = data;
2172
+ const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
2173
+ id: procedureId,
2174
+ ...dataWithoutProductsMetadata,
2175
+ nameLower: (data as any).nameLower || data.name.toLowerCase(),
2176
+ photos: processedPhotos,
2177
+ category,
2178
+ subcategory,
2179
+ technology,
2180
+ // No product field for consultations (Firestore doesn't allow undefined, so we omit it entirely)
2181
+ productsMetadata: transformedProductsMetadata, // Empty array for consultations
2182
+ blockingConditions: technology.blockingConditions,
2183
+ contraindications: technology.contraindications || [],
2184
+ contraindicationIds: technology.contraindications?.map(c => c.id) || [],
2185
+ treatmentBenefits: technology.benefits,
2186
+ treatmentBenefitIds: Array.isArray(technology.benefits)
2187
+ ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
2188
+ : [],
2189
+ preRequirements: technology.requirements.pre,
2190
+ postRequirements: technology.requirements.post,
2191
+ certificationRequirement: technology.certificationRequirement,
2192
+ documentationTemplates: technology?.documentationTemplates || [],
2193
+ clinicInfo,
2194
+ doctorInfo,
2195
+ reviewInfo: {
2196
+ totalReviews: 0,
2197
+ averageRating: 0,
2198
+ effectivenessOfTreatment: 0,
2199
+ outcomeExplanation: 0,
2200
+ painManagement: 0,
2201
+ followUpCare: 0,
2202
+ valueForMoney: 0,
2203
+ recommendationPercentage: 0,
2204
+ },
2205
+ isActive: true,
2206
+ };
2207
+
2208
+ // Create the procedure document
2209
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
2210
+ await setDoc(procedureRef, {
2211
+ ...newProcedure,
2212
+ createdAt: serverTimestamp(),
2213
+ updatedAt: serverTimestamp(),
2214
+ });
2215
+
2216
+ // Return the created procedure (fetch again to get server timestamps)
2217
+ const savedDoc = await getDoc(procedureRef);
2218
+ return savedDoc.data() as Procedure;
2219
+ }
2220
+
2221
+ /**
2222
+ * Gets all procedures with minimal info for map display (id, name, clinicId, clinicName, address, latitude, longitude)
2223
+ * This is optimized for mobile map usage to reduce payload size.
2224
+ * @returns Array of minimal procedure info for map
2225
+ */
2226
+ async getProceduresForMap(): Promise<
2227
+ {
2228
+ id: string;
2229
+ name: string;
2230
+ clinicId: string | undefined;
2231
+ clinicName: string | undefined;
2232
+ address: string;
2233
+ latitude: number | undefined;
2234
+ longitude: number | undefined;
2235
+ }[]
2236
+ > {
2237
+ const proceduresRef = collection(this.db, PROCEDURES_COLLECTION);
2238
+ const snapshot = await getDocs(proceduresRef);
2239
+ const proceduresForMap = snapshot.docs.map(doc => {
2240
+ const data = doc.data();
2241
+ return {
2242
+ id: doc.id,
2243
+ name: data.name,
2244
+ clinicId: data.clinicInfo?.id,
2245
+ clinicName: data.clinicInfo?.name,
2246
+ address: data.clinicInfo?.location?.address || '',
2247
+ latitude: data.clinicInfo?.location?.latitude,
2248
+ longitude: data.clinicInfo?.location?.longitude,
2249
+ };
2250
+ });
2251
+ return proceduresForMap;
2252
+ }
2253
+
2254
+ /**
2255
+ * Gets procedures filtered by clinic and practitioner with optional family filter
2256
+ * @param clinicBranchId Clinic branch ID to filter by
2257
+ * @param practitionerId Practitioner ID to filter by
2258
+ * @param filterByFamily If true, shows only procedures of the same family as the default procedure
2259
+ * @param defaultProcedureId Optional default procedure ID to determine the family
2260
+ * @returns Array of procedures
2261
+ */
2262
+ async getProceduresForConsultation(
2263
+ clinicBranchId: string,
2264
+ practitionerId: string,
2265
+ filterByFamily: boolean = true,
2266
+ defaultProcedureId?: string
2267
+ ): Promise<Procedure[]> {
2268
+ let familyToFilter: ProcedureFamily | null = null;
2269
+
2270
+ // If family filtering is enabled and we have a default procedure, get its family
2271
+ if (filterByFamily && defaultProcedureId) {
2272
+ const defaultProcedureRef = doc(this.db, PROCEDURES_COLLECTION, defaultProcedureId);
2273
+ const defaultProcedureSnap = await getDoc(defaultProcedureRef);
2274
+
2275
+ if (defaultProcedureSnap.exists()) {
2276
+ const defaultProcedure = defaultProcedureSnap.data() as Procedure;
2277
+ familyToFilter = defaultProcedure.family;
2278
+ }
2279
+ }
2280
+
2281
+ // Build query constraints
2282
+ const constraints: QueryConstraint[] = [
2283
+ where('clinicBranchId', '==', clinicBranchId),
2284
+ where('practitionerId', '==', practitionerId),
2285
+ where('isActive', '==', true),
2286
+ ];
2287
+
2288
+ // Add family filter if applicable
2289
+ if (filterByFamily && familyToFilter) {
2290
+ constraints.push(where('family', '==', familyToFilter));
2291
+ }
2292
+
2293
+ // Execute query
2294
+ const proceduresQuery = query(
2295
+ collection(this.db, PROCEDURES_COLLECTION),
2296
+ ...constraints,
2297
+ orderBy('name', 'asc')
2298
+ );
2299
+
2300
+ const querySnapshot = await getDocs(proceduresQuery);
2301
+
2302
+ return querySnapshot.docs.map(doc => ({
2303
+ id: doc.id,
2304
+ ...doc.data(),
2305
+ } as Procedure));
2306
+ }
2307
+ }