@blackcode_sa/metaestetics-api 1.13.4 → 1.13.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/dist/admin/index.d.mts +15 -28
  2. package/dist/admin/index.d.ts +15 -28
  3. package/dist/index.d.mts +16 -29
  4. package/dist/index.d.ts +16 -29
  5. package/dist/index.js +1 -0
  6. package/dist/index.mjs +1 -0
  7. package/package.json +121 -119
  8. package/src/__mocks__/firstore.ts +10 -10
  9. package/src/admin/aggregation/README.md +79 -79
  10. package/src/admin/aggregation/appointment/README.md +128 -128
  11. package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +1984 -1984
  12. package/src/admin/aggregation/appointment/index.ts +1 -1
  13. package/src/admin/aggregation/clinic/README.md +52 -52
  14. package/src/admin/aggregation/clinic/clinic.aggregation.service.ts +703 -703
  15. package/src/admin/aggregation/clinic/index.ts +1 -1
  16. package/src/admin/aggregation/forms/README.md +13 -13
  17. package/src/admin/aggregation/forms/filled-forms.aggregation.service.ts +322 -322
  18. package/src/admin/aggregation/forms/index.ts +1 -1
  19. package/src/admin/aggregation/index.ts +8 -8
  20. package/src/admin/aggregation/patient/README.md +27 -27
  21. package/src/admin/aggregation/patient/index.ts +1 -1
  22. package/src/admin/aggregation/patient/patient.aggregation.service.ts +141 -141
  23. package/src/admin/aggregation/practitioner/README.md +42 -42
  24. package/src/admin/aggregation/practitioner/index.ts +1 -1
  25. package/src/admin/aggregation/practitioner/practitioner.aggregation.service.ts +433 -433
  26. package/src/admin/aggregation/practitioner-invite/index.ts +1 -1
  27. package/src/admin/aggregation/practitioner-invite/practitioner-invite.aggregation.service.ts +961 -961
  28. package/src/admin/aggregation/procedure/README.md +43 -43
  29. package/src/admin/aggregation/procedure/index.ts +1 -1
  30. package/src/admin/aggregation/procedure/procedure.aggregation.service.ts +702 -702
  31. package/src/admin/aggregation/reviews/index.ts +1 -1
  32. package/src/admin/aggregation/reviews/reviews.aggregation.service.ts +689 -689
  33. package/src/admin/analytics/analytics.admin.service.ts +278 -278
  34. package/src/admin/analytics/index.ts +2 -2
  35. package/src/admin/booking/README.md +125 -125
  36. package/src/admin/booking/booking.admin.ts +1037 -1037
  37. package/src/admin/booking/booking.calculator.ts +712 -712
  38. package/src/admin/booking/booking.types.ts +59 -59
  39. package/src/admin/booking/index.ts +3 -3
  40. package/src/admin/booking/timezones-problem.md +185 -185
  41. package/src/admin/calendar/README.md +7 -7
  42. package/src/admin/calendar/calendar.admin.service.ts +345 -345
  43. package/src/admin/calendar/index.ts +1 -1
  44. package/src/admin/documentation-templates/document-manager.admin.ts +260 -260
  45. package/src/admin/documentation-templates/index.ts +1 -1
  46. package/src/admin/free-consultation/free-consultation-utils.admin.ts +148 -148
  47. package/src/admin/free-consultation/index.ts +1 -1
  48. package/src/admin/index.ts +81 -81
  49. package/src/admin/logger/index.ts +78 -78
  50. package/src/admin/mailing/README.md +95 -95
  51. package/src/admin/mailing/appointment/appointment.mailing.service.ts +732 -732
  52. package/src/admin/mailing/appointment/index.ts +1 -1
  53. package/src/admin/mailing/appointment/templates/patient/appointment-confirmed.html +40 -40
  54. package/src/admin/mailing/base.mailing.service.ts +208 -208
  55. package/src/admin/mailing/index.ts +3 -3
  56. package/src/admin/mailing/practitionerInvite/existing-practitioner-invite.mailing.ts +611 -611
  57. package/src/admin/mailing/practitionerInvite/index.ts +2 -2
  58. package/src/admin/mailing/practitionerInvite/practitionerInvite.mailing.ts +395 -395
  59. package/src/admin/mailing/practitionerInvite/templates/existing-practitioner-invitation.template.ts +155 -155
  60. package/src/admin/mailing/practitionerInvite/templates/invitation.template.ts +101 -101
  61. package/src/admin/mailing/practitionerInvite/templates/invite-accepted-notification.template.ts +228 -228
  62. package/src/admin/mailing/practitionerInvite/templates/invite-rejected-notification.template.ts +242 -242
  63. package/src/admin/notifications/index.ts +1 -1
  64. package/src/admin/notifications/notifications.admin.ts +710 -710
  65. package/src/admin/requirements/README.md +128 -128
  66. package/src/admin/requirements/index.ts +1 -1
  67. package/src/admin/requirements/patient-requirements.admin.service.ts +475 -475
  68. package/src/admin/users/index.ts +1 -1
  69. package/src/admin/users/user-profile.admin.ts +405 -405
  70. package/src/backoffice/constants/certification.constants.ts +13 -13
  71. package/src/backoffice/constants/index.ts +1 -1
  72. package/src/backoffice/errors/backoffice.errors.ts +181 -181
  73. package/src/backoffice/errors/index.ts +1 -1
  74. package/src/backoffice/expo-safe/README.md +26 -26
  75. package/src/backoffice/expo-safe/index.ts +41 -41
  76. package/src/backoffice/index.ts +5 -5
  77. package/src/backoffice/services/FIXES_README.md +102 -102
  78. package/src/backoffice/services/README.md +57 -57
  79. package/src/backoffice/services/analytics.service.proposal.md +863 -863
  80. package/src/backoffice/services/analytics.service.summary.md +143 -143
  81. package/src/backoffice/services/brand.service.ts +256 -256
  82. package/src/backoffice/services/category.service.ts +384 -384
  83. package/src/backoffice/services/constants.service.ts +385 -385
  84. package/src/backoffice/services/documentation-template.service.ts +202 -202
  85. package/src/backoffice/services/index.ts +10 -10
  86. package/src/backoffice/services/migrate-products.ts +116 -116
  87. package/src/backoffice/services/product.service.ts +553 -553
  88. package/src/backoffice/services/requirement.service.ts +235 -235
  89. package/src/backoffice/services/subcategory.service.ts +461 -461
  90. package/src/backoffice/services/technology.service.ts +1151 -1151
  91. package/src/backoffice/types/README.md +12 -12
  92. package/src/backoffice/types/admin-constants.types.ts +69 -69
  93. package/src/backoffice/types/brand.types.ts +29 -29
  94. package/src/backoffice/types/category.types.ts +67 -67
  95. package/src/backoffice/types/documentation-templates.types.ts +28 -28
  96. package/src/backoffice/types/index.ts +10 -10
  97. package/src/backoffice/types/procedure-product.types.ts +38 -38
  98. package/src/backoffice/types/product.types.ts +240 -240
  99. package/src/backoffice/types/requirement.types.ts +63 -63
  100. package/src/backoffice/types/static/README.md +18 -18
  101. package/src/backoffice/types/static/blocking-condition.types.ts +21 -21
  102. package/src/backoffice/types/static/certification.types.ts +37 -37
  103. package/src/backoffice/types/static/contraindication.types.ts +19 -19
  104. package/src/backoffice/types/static/index.ts +6 -6
  105. package/src/backoffice/types/static/pricing.types.ts +16 -16
  106. package/src/backoffice/types/static/procedure-family.types.ts +14 -14
  107. package/src/backoffice/types/static/treatment-benefit.types.ts +22 -22
  108. package/src/backoffice/types/subcategory.types.ts +34 -34
  109. package/src/backoffice/types/technology.types.ts +168 -168
  110. package/src/backoffice/validations/index.ts +1 -1
  111. package/src/backoffice/validations/schemas.ts +164 -164
  112. package/src/config/__mocks__/firebase.ts +99 -99
  113. package/src/config/firebase.ts +78 -78
  114. package/src/config/index.ts +9 -9
  115. package/src/errors/auth.error.ts +6 -6
  116. package/src/errors/auth.errors.ts +200 -200
  117. package/src/errors/clinic.errors.ts +32 -32
  118. package/src/errors/firebase.errors.ts +47 -47
  119. package/src/errors/user.errors.ts +99 -99
  120. package/src/index.backup.ts +407 -407
  121. package/src/index.ts +6 -6
  122. package/src/locales/en.ts +31 -31
  123. package/src/recommender/admin/index.ts +1 -1
  124. package/src/recommender/admin/services/recommender.service.admin.ts +5 -5
  125. package/src/recommender/front/index.ts +1 -1
  126. package/src/recommender/front/services/onboarding.service.ts +5 -5
  127. package/src/recommender/front/services/recommender.service.ts +3 -3
  128. package/src/recommender/index.ts +1 -1
  129. package/src/services/PATIENTAUTH.MD +197 -197
  130. package/src/services/README.md +106 -106
  131. package/src/services/__tests__/auth/auth.mock.test.ts +17 -17
  132. package/src/services/__tests__/auth/auth.setup.ts +293 -293
  133. package/src/services/__tests__/auth.service.test.ts +346 -346
  134. package/src/services/__tests__/base.service.test.ts +77 -77
  135. package/src/services/__tests__/user.service.test.ts +528 -528
  136. package/src/services/analytics/ARCHITECTURE.md +199 -199
  137. package/src/services/analytics/CLOUD_FUNCTIONS.md +225 -225
  138. package/src/services/analytics/GROUPED_ANALYTICS.md +501 -501
  139. package/src/services/analytics/QUICK_START.md +393 -393
  140. package/src/services/analytics/README.md +304 -304
  141. package/src/services/analytics/SUMMARY.md +141 -141
  142. package/src/services/analytics/TRENDS.md +380 -380
  143. package/src/services/analytics/USAGE_GUIDE.md +518 -518
  144. package/src/services/analytics/analytics-cloud.service.ts +222 -222
  145. package/src/services/analytics/analytics.service.ts +2142 -2142
  146. package/src/services/analytics/index.ts +4 -4
  147. package/src/services/analytics/review-analytics.service.ts +941 -941
  148. package/src/services/analytics/utils/appointment-filtering.utils.ts +138 -138
  149. package/src/services/analytics/utils/cost-calculation.utils.ts +182 -182
  150. package/src/services/analytics/utils/grouping.utils.ts +434 -434
  151. package/src/services/analytics/utils/stored-analytics.utils.ts +347 -347
  152. package/src/services/analytics/utils/time-calculation.utils.ts +186 -186
  153. package/src/services/analytics/utils/trend-calculation.utils.ts +200 -200
  154. package/src/services/appointment/README.md +17 -17
  155. package/src/services/appointment/appointment.service.ts +2558 -2558
  156. package/src/services/appointment/index.ts +1 -1
  157. package/src/services/appointment/utils/appointment.utils.ts +552 -552
  158. package/src/services/appointment/utils/extended-procedure.utils.ts +314 -314
  159. package/src/services/appointment/utils/form-initialization.utils.ts +225 -225
  160. package/src/services/appointment/utils/recommended-procedure.utils.ts +195 -195
  161. package/src/services/appointment/utils/zone-management.utils.ts +353 -353
  162. package/src/services/appointment/utils/zone-photo.utils.ts +152 -152
  163. package/src/services/auth/auth.service.ts +989 -989
  164. package/src/services/auth/auth.v2.service.ts +961 -961
  165. package/src/services/auth/index.ts +7 -7
  166. package/src/services/auth/utils/error.utils.ts +90 -90
  167. package/src/services/auth/utils/firebase.utils.ts +49 -49
  168. package/src/services/auth/utils/index.ts +21 -21
  169. package/src/services/auth/utils/practitioner.utils.ts +125 -125
  170. package/src/services/base.service.ts +41 -41
  171. package/src/services/calendar/calendar.service.ts +1077 -1077
  172. package/src/services/calendar/calendar.v2.service.ts +1683 -1683
  173. package/src/services/calendar/calendar.v3.service.ts +313 -313
  174. package/src/services/calendar/externalCalendar.service.ts +178 -178
  175. package/src/services/calendar/index.ts +5 -5
  176. package/src/services/calendar/synced-calendars.service.ts +743 -743
  177. package/src/services/calendar/utils/appointment.utils.ts +265 -265
  178. package/src/services/calendar/utils/calendar-event.utils.ts +646 -646
  179. package/src/services/calendar/utils/clinic.utils.ts +237 -237
  180. package/src/services/calendar/utils/docs.utils.ts +157 -157
  181. package/src/services/calendar/utils/google-calendar.utils.ts +697 -697
  182. package/src/services/calendar/utils/index.ts +8 -8
  183. package/src/services/calendar/utils/patient.utils.ts +198 -198
  184. package/src/services/calendar/utils/practitioner.utils.ts +221 -221
  185. package/src/services/calendar/utils/synced-calendar.utils.ts +472 -472
  186. package/src/services/clinic/README.md +204 -204
  187. package/src/services/clinic/__tests__/clinic-admin.service.test.ts +287 -287
  188. package/src/services/clinic/__tests__/clinic-group.service.test.ts +352 -352
  189. package/src/services/clinic/__tests__/clinic.service.test.ts +354 -354
  190. package/src/services/clinic/billing-transactions.service.ts +217 -217
  191. package/src/services/clinic/clinic-admin.service.ts +202 -202
  192. package/src/services/clinic/clinic-group.service.ts +310 -310
  193. package/src/services/clinic/clinic.service.ts +708 -708
  194. package/src/services/clinic/index.ts +5 -5
  195. package/src/services/clinic/practitioner-invite.service.ts +519 -519
  196. package/src/services/clinic/utils/admin.utils.ts +551 -551
  197. package/src/services/clinic/utils/clinic-group.utils.ts +646 -646
  198. package/src/services/clinic/utils/clinic.utils.ts +949 -949
  199. package/src/services/clinic/utils/filter.utils.d.ts +23 -23
  200. package/src/services/clinic/utils/filter.utils.ts +446 -446
  201. package/src/services/clinic/utils/index.ts +11 -11
  202. package/src/services/clinic/utils/photos.utils.ts +188 -188
  203. package/src/services/clinic/utils/search.utils.ts +84 -84
  204. package/src/services/clinic/utils/tag.utils.ts +124 -124
  205. package/src/services/documentation-templates/documentation-template.service.ts +537 -537
  206. package/src/services/documentation-templates/filled-document.service.ts +587 -587
  207. package/src/services/documentation-templates/index.ts +2 -2
  208. package/src/services/index.ts +14 -14
  209. package/src/services/media/index.ts +1 -1
  210. package/src/services/media/media.service.ts +418 -418
  211. package/src/services/notifications/__tests__/notification.service.test.ts +242 -242
  212. package/src/services/notifications/index.ts +1 -1
  213. package/src/services/notifications/notification.service.ts +215 -215
  214. package/src/services/patient/README.md +48 -48
  215. package/src/services/patient/To-Do.md +43 -43
  216. package/src/services/patient/__tests__/patient.service.test.ts +294 -294
  217. package/src/services/patient/index.ts +2 -2
  218. package/src/services/patient/patient.service.ts +883 -883
  219. package/src/services/patient/patientRequirements.service.ts +285 -285
  220. package/src/services/patient/utils/aesthetic-analysis.utils.ts +176 -176
  221. package/src/services/patient/utils/clinic.utils.ts +80 -80
  222. package/src/services/patient/utils/docs.utils.ts +142 -142
  223. package/src/services/patient/utils/index.ts +9 -9
  224. package/src/services/patient/utils/location.utils.ts +126 -126
  225. package/src/services/patient/utils/medical-stuff.utils.ts +143 -143
  226. package/src/services/patient/utils/medical.utils.ts +458 -458
  227. package/src/services/patient/utils/practitioner.utils.ts +260 -260
  228. package/src/services/patient/utils/profile.utils.ts +510 -510
  229. package/src/services/patient/utils/sensitive.utils.ts +260 -260
  230. package/src/services/patient/utils/token.utils.ts +211 -211
  231. package/src/services/practitioner/README.md +145 -145
  232. package/src/services/practitioner/index.ts +1 -1
  233. package/src/services/practitioner/practitioner.service.ts +1742 -1742
  234. package/src/services/procedure/README.md +163 -163
  235. package/src/services/procedure/index.ts +1 -1
  236. package/src/services/procedure/procedure.service.ts +2200 -2200
  237. package/src/services/reviews/index.ts +1 -1
  238. package/src/services/reviews/reviews.service.ts +734 -734
  239. package/src/services/user/index.ts +1 -1
  240. package/src/services/user/user.service.ts +489 -489
  241. package/src/services/user/user.v2.service.ts +466 -466
  242. package/src/types/analytics/analytics.types.ts +597 -597
  243. package/src/types/analytics/grouped-analytics.types.ts +173 -173
  244. package/src/types/analytics/index.ts +4 -4
  245. package/src/types/analytics/stored-analytics.types.ts +137 -137
  246. package/src/types/appointment/index.ts +480 -480
  247. package/src/types/calendar/index.ts +258 -258
  248. package/src/types/calendar/synced-calendar.types.ts +66 -66
  249. package/src/types/clinic/index.ts +498 -489
  250. package/src/types/clinic/practitioner-invite.types.ts +91 -91
  251. package/src/types/clinic/preferences.types.ts +159 -159
  252. package/src/types/clinic/to-do +3 -3
  253. package/src/types/documentation-templates/index.ts +308 -308
  254. package/src/types/index.ts +47 -47
  255. package/src/types/notifications/README.md +77 -77
  256. package/src/types/notifications/index.ts +286 -286
  257. package/src/types/patient/aesthetic-analysis.types.ts +66 -66
  258. package/src/types/patient/allergies.ts +58 -58
  259. package/src/types/patient/index.ts +275 -275
  260. package/src/types/patient/medical-info.types.ts +152 -152
  261. package/src/types/patient/patient-requirements.ts +92 -92
  262. package/src/types/patient/token.types.ts +61 -61
  263. package/src/types/practitioner/index.ts +206 -206
  264. package/src/types/procedure/index.ts +181 -181
  265. package/src/types/profile/index.ts +39 -39
  266. package/src/types/reviews/index.ts +132 -132
  267. package/src/types/tz-lookup.d.ts +4 -4
  268. package/src/types/user/index.ts +38 -38
  269. package/src/utils/TIMESTAMPS.md +176 -176
  270. package/src/utils/TimestampUtils.ts +241 -241
  271. package/src/utils/index.ts +1 -1
  272. package/src/validations/appointment.schema.ts +574 -574
  273. package/src/validations/calendar.schema.ts +225 -225
  274. package/src/validations/clinic.schema.ts +494 -493
  275. package/src/validations/common.schema.ts +25 -25
  276. package/src/validations/documentation-templates/index.ts +1 -1
  277. package/src/validations/documentation-templates/template.schema.ts +220 -220
  278. package/src/validations/documentation-templates.schema.ts +10 -10
  279. package/src/validations/index.ts +20 -20
  280. package/src/validations/media.schema.ts +10 -10
  281. package/src/validations/notification.schema.ts +90 -90
  282. package/src/validations/patient/aesthetic-analysis.schema.ts +55 -55
  283. package/src/validations/patient/medical-info.schema.ts +125 -125
  284. package/src/validations/patient/patient-requirements.schema.ts +84 -84
  285. package/src/validations/patient/token.schema.ts +29 -29
  286. package/src/validations/patient.schema.ts +217 -217
  287. package/src/validations/practitioner.schema.ts +222 -222
  288. package/src/validations/procedure-product.schema.ts +41 -41
  289. package/src/validations/procedure.schema.ts +124 -124
  290. package/src/validations/profile-info.schema.ts +41 -41
  291. package/src/validations/reviews.schema.ts +195 -195
  292. package/src/validations/schemas.ts +104 -104
  293. package/src/validations/shared.schema.ts +78 -78
@@ -1,2200 +1,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
- 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
+ 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
+ }