@blackcode_sa/metaestetics-api 1.12.65 → 1.12.67

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 (273) hide show
  1. package/dist/admin/index.d.mts +2 -0
  2. package/dist/admin/index.d.ts +2 -0
  3. package/dist/admin/index.js +45 -4
  4. package/dist/admin/index.mjs +45 -4
  5. package/dist/backoffice/index.d.mts +33 -0
  6. package/dist/backoffice/index.d.ts +33 -0
  7. package/dist/backoffice/index.js +63 -0
  8. package/dist/backoffice/index.mjs +63 -0
  9. package/dist/index.d.mts +35 -0
  10. package/dist/index.d.ts +35 -0
  11. package/dist/index.js +116 -11
  12. package/dist/index.mjs +116 -11
  13. package/package.json +119 -119
  14. package/src/__mocks__/firstore.ts +10 -10
  15. package/src/admin/aggregation/README.md +79 -79
  16. package/src/admin/aggregation/appointment/README.md +128 -128
  17. package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +1844 -1844
  18. package/src/admin/aggregation/appointment/index.ts +1 -1
  19. package/src/admin/aggregation/clinic/README.md +52 -52
  20. package/src/admin/aggregation/clinic/clinic.aggregation.service.ts +703 -703
  21. package/src/admin/aggregation/clinic/index.ts +1 -1
  22. package/src/admin/aggregation/forms/README.md +13 -13
  23. package/src/admin/aggregation/forms/filled-forms.aggregation.service.ts +322 -322
  24. package/src/admin/aggregation/forms/index.ts +1 -1
  25. package/src/admin/aggregation/index.ts +8 -8
  26. package/src/admin/aggregation/patient/README.md +27 -27
  27. package/src/admin/aggregation/patient/index.ts +1 -1
  28. package/src/admin/aggregation/patient/patient.aggregation.service.ts +141 -141
  29. package/src/admin/aggregation/practitioner/README.md +42 -42
  30. package/src/admin/aggregation/practitioner/index.ts +1 -1
  31. package/src/admin/aggregation/practitioner/practitioner.aggregation.service.ts +433 -433
  32. package/src/admin/aggregation/practitioner-invite/index.ts +1 -1
  33. package/src/admin/aggregation/practitioner-invite/practitioner-invite.aggregation.service.ts +961 -961
  34. package/src/admin/aggregation/procedure/README.md +43 -43
  35. package/src/admin/aggregation/procedure/index.ts +1 -1
  36. package/src/admin/aggregation/procedure/procedure.aggregation.service.ts +702 -702
  37. package/src/admin/aggregation/reviews/index.ts +1 -1
  38. package/src/admin/aggregation/reviews/reviews.aggregation.service.ts +689 -641
  39. package/src/admin/booking/README.md +125 -125
  40. package/src/admin/booking/booking.admin.ts +1037 -1037
  41. package/src/admin/booking/booking.calculator.ts +712 -712
  42. package/src/admin/booking/booking.types.ts +59 -59
  43. package/src/admin/booking/index.ts +3 -3
  44. package/src/admin/booking/timezones-problem.md +185 -185
  45. package/src/admin/calendar/README.md +7 -7
  46. package/src/admin/calendar/calendar.admin.service.ts +345 -345
  47. package/src/admin/calendar/index.ts +1 -1
  48. package/src/admin/documentation-templates/document-manager.admin.ts +260 -260
  49. package/src/admin/documentation-templates/index.ts +1 -1
  50. package/src/admin/free-consultation/free-consultation-utils.admin.ts +148 -148
  51. package/src/admin/free-consultation/index.ts +1 -1
  52. package/src/admin/index.ts +75 -75
  53. package/src/admin/logger/index.ts +78 -78
  54. package/src/admin/mailing/README.md +95 -95
  55. package/src/admin/mailing/appointment/appointment.mailing.service.ts +732 -732
  56. package/src/admin/mailing/appointment/index.ts +1 -1
  57. package/src/admin/mailing/appointment/templates/patient/appointment-confirmed.html +40 -40
  58. package/src/admin/mailing/base.mailing.service.ts +208 -208
  59. package/src/admin/mailing/index.ts +3 -3
  60. package/src/admin/mailing/practitionerInvite/existing-practitioner-invite.mailing.ts +611 -611
  61. package/src/admin/mailing/practitionerInvite/index.ts +2 -2
  62. package/src/admin/mailing/practitionerInvite/practitionerInvite.mailing.ts +395 -395
  63. package/src/admin/mailing/practitionerInvite/templates/existing-practitioner-invitation.template.ts +155 -155
  64. package/src/admin/mailing/practitionerInvite/templates/invitation.template.ts +101 -101
  65. package/src/admin/mailing/practitionerInvite/templates/invite-accepted-notification.template.ts +228 -228
  66. package/src/admin/mailing/practitionerInvite/templates/invite-rejected-notification.template.ts +242 -242
  67. package/src/admin/notifications/index.ts +1 -1
  68. package/src/admin/notifications/notifications.admin.ts +710 -710
  69. package/src/admin/requirements/README.md +128 -128
  70. package/src/admin/requirements/index.ts +1 -1
  71. package/src/admin/requirements/patient-requirements.admin.service.ts +475 -475
  72. package/src/admin/users/index.ts +1 -1
  73. package/src/admin/users/user-profile.admin.ts +405 -405
  74. package/src/backoffice/constants/certification.constants.ts +13 -13
  75. package/src/backoffice/constants/index.ts +1 -1
  76. package/src/backoffice/errors/backoffice.errors.ts +181 -181
  77. package/src/backoffice/errors/index.ts +1 -1
  78. package/src/backoffice/expo-safe/README.md +26 -26
  79. package/src/backoffice/expo-safe/index.ts +41 -41
  80. package/src/backoffice/index.ts +5 -5
  81. package/src/backoffice/services/FIXES_README.md +102 -102
  82. package/src/backoffice/services/README.md +40 -40
  83. package/src/backoffice/services/brand.service.ts +256 -256
  84. package/src/backoffice/services/category.service.ts +341 -318
  85. package/src/backoffice/services/constants.service.ts +385 -385
  86. package/src/backoffice/services/documentation-template.service.ts +202 -202
  87. package/src/backoffice/services/index.ts +10 -10
  88. package/src/backoffice/services/migrate-products.ts +116 -116
  89. package/src/backoffice/services/product.service.ts +553 -553
  90. package/src/backoffice/services/requirement.service.ts +235 -235
  91. package/src/backoffice/services/subcategory.service.ts +417 -395
  92. package/src/backoffice/services/technology.service.ts +1104 -1083
  93. package/src/backoffice/types/README.md +12 -12
  94. package/src/backoffice/types/admin-constants.types.ts +69 -69
  95. package/src/backoffice/types/brand.types.ts +29 -29
  96. package/src/backoffice/types/category.types.ts +67 -62
  97. package/src/backoffice/types/documentation-templates.types.ts +28 -28
  98. package/src/backoffice/types/index.ts +10 -10
  99. package/src/backoffice/types/procedure-product.types.ts +38 -38
  100. package/src/backoffice/types/product.types.ts +240 -240
  101. package/src/backoffice/types/requirement.types.ts +63 -63
  102. package/src/backoffice/types/static/README.md +18 -18
  103. package/src/backoffice/types/static/blocking-condition.types.ts +21 -21
  104. package/src/backoffice/types/static/certification.types.ts +37 -37
  105. package/src/backoffice/types/static/contraindication.types.ts +19 -19
  106. package/src/backoffice/types/static/index.ts +6 -6
  107. package/src/backoffice/types/static/pricing.types.ts +16 -16
  108. package/src/backoffice/types/static/procedure-family.types.ts +14 -14
  109. package/src/backoffice/types/static/treatment-benefit.types.ts +22 -22
  110. package/src/backoffice/types/subcategory.types.ts +34 -34
  111. package/src/backoffice/types/technology.types.ts +168 -163
  112. package/src/backoffice/validations/index.ts +1 -1
  113. package/src/backoffice/validations/schemas.ts +164 -164
  114. package/src/config/__mocks__/firebase.ts +99 -99
  115. package/src/config/firebase.ts +78 -78
  116. package/src/config/index.ts +9 -9
  117. package/src/errors/auth.error.ts +6 -6
  118. package/src/errors/auth.errors.ts +200 -200
  119. package/src/errors/clinic.errors.ts +32 -32
  120. package/src/errors/firebase.errors.ts +47 -47
  121. package/src/errors/user.errors.ts +99 -99
  122. package/src/index.backup.ts +407 -407
  123. package/src/index.ts +6 -6
  124. package/src/locales/en.ts +31 -31
  125. package/src/recommender/admin/index.ts +1 -1
  126. package/src/recommender/admin/services/recommender.service.admin.ts +5 -5
  127. package/src/recommender/front/index.ts +1 -1
  128. package/src/recommender/front/services/onboarding.service.ts +5 -5
  129. package/src/recommender/front/services/recommender.service.ts +3 -3
  130. package/src/recommender/index.ts +1 -1
  131. package/src/services/PATIENTAUTH.MD +197 -197
  132. package/src/services/README.md +106 -106
  133. package/src/services/__tests__/auth/auth.mock.test.ts +17 -17
  134. package/src/services/__tests__/auth/auth.setup.ts +293 -293
  135. package/src/services/__tests__/auth.service.test.ts +346 -346
  136. package/src/services/__tests__/base.service.test.ts +77 -77
  137. package/src/services/__tests__/user.service.test.ts +528 -528
  138. package/src/services/appointment/README.md +17 -17
  139. package/src/services/appointment/appointment.service.ts +2505 -2505
  140. package/src/services/appointment/index.ts +1 -1
  141. package/src/services/appointment/utils/appointment.utils.ts +552 -552
  142. package/src/services/appointment/utils/extended-procedure.utils.ts +314 -314
  143. package/src/services/appointment/utils/form-initialization.utils.ts +225 -225
  144. package/src/services/appointment/utils/recommended-procedure.utils.ts +195 -195
  145. package/src/services/appointment/utils/zone-management.utils.ts +353 -353
  146. package/src/services/appointment/utils/zone-photo.utils.ts +152 -152
  147. package/src/services/auth/auth.service.ts +989 -989
  148. package/src/services/auth/auth.v2.service.ts +961 -961
  149. package/src/services/auth/index.ts +7 -7
  150. package/src/services/auth/utils/error.utils.ts +90 -90
  151. package/src/services/auth/utils/firebase.utils.ts +49 -49
  152. package/src/services/auth/utils/index.ts +21 -21
  153. package/src/services/auth/utils/practitioner.utils.ts +125 -125
  154. package/src/services/base.service.ts +41 -41
  155. package/src/services/calendar/calendar.service.ts +1077 -1077
  156. package/src/services/calendar/calendar.v2.service.ts +1683 -1683
  157. package/src/services/calendar/calendar.v3.service.ts +313 -313
  158. package/src/services/calendar/externalCalendar.service.ts +178 -178
  159. package/src/services/calendar/index.ts +5 -5
  160. package/src/services/calendar/synced-calendars.service.ts +743 -743
  161. package/src/services/calendar/utils/appointment.utils.ts +265 -265
  162. package/src/services/calendar/utils/calendar-event.utils.ts +646 -646
  163. package/src/services/calendar/utils/clinic.utils.ts +237 -237
  164. package/src/services/calendar/utils/docs.utils.ts +157 -157
  165. package/src/services/calendar/utils/google-calendar.utils.ts +697 -697
  166. package/src/services/calendar/utils/index.ts +8 -8
  167. package/src/services/calendar/utils/patient.utils.ts +198 -198
  168. package/src/services/calendar/utils/practitioner.utils.ts +221 -221
  169. package/src/services/calendar/utils/synced-calendar.utils.ts +472 -472
  170. package/src/services/clinic/README.md +204 -204
  171. package/src/services/clinic/__tests__/clinic-admin.service.test.ts +287 -287
  172. package/src/services/clinic/__tests__/clinic-group.service.test.ts +352 -352
  173. package/src/services/clinic/__tests__/clinic.service.test.ts +354 -354
  174. package/src/services/clinic/billing-transactions.service.ts +217 -217
  175. package/src/services/clinic/clinic-admin.service.ts +202 -202
  176. package/src/services/clinic/clinic-group.service.ts +310 -310
  177. package/src/services/clinic/clinic.service.ts +708 -708
  178. package/src/services/clinic/index.ts +5 -5
  179. package/src/services/clinic/practitioner-invite.service.ts +519 -519
  180. package/src/services/clinic/utils/admin.utils.ts +551 -551
  181. package/src/services/clinic/utils/clinic-group.utils.ts +646 -646
  182. package/src/services/clinic/utils/clinic.utils.ts +949 -949
  183. package/src/services/clinic/utils/filter.utils.d.ts +23 -23
  184. package/src/services/clinic/utils/filter.utils.ts +446 -446
  185. package/src/services/clinic/utils/index.ts +11 -11
  186. package/src/services/clinic/utils/photos.utils.ts +188 -188
  187. package/src/services/clinic/utils/search.utils.ts +84 -84
  188. package/src/services/clinic/utils/tag.utils.ts +124 -124
  189. package/src/services/documentation-templates/documentation-template.service.ts +537 -537
  190. package/src/services/documentation-templates/filled-document.service.ts +587 -587
  191. package/src/services/documentation-templates/index.ts +2 -2
  192. package/src/services/index.ts +13 -13
  193. package/src/services/media/index.ts +1 -1
  194. package/src/services/media/media.service.ts +418 -418
  195. package/src/services/notifications/__tests__/notification.service.test.ts +242 -242
  196. package/src/services/notifications/index.ts +1 -1
  197. package/src/services/notifications/notification.service.ts +215 -215
  198. package/src/services/patient/README.md +48 -48
  199. package/src/services/patient/To-Do.md +43 -43
  200. package/src/services/patient/__tests__/patient.service.test.ts +294 -294
  201. package/src/services/patient/index.ts +2 -2
  202. package/src/services/patient/patient.service.ts +883 -883
  203. package/src/services/patient/patientRequirements.service.ts +285 -285
  204. package/src/services/patient/utils/aesthetic-analysis.utils.ts +176 -176
  205. package/src/services/patient/utils/clinic.utils.ts +80 -80
  206. package/src/services/patient/utils/docs.utils.ts +142 -142
  207. package/src/services/patient/utils/index.ts +9 -9
  208. package/src/services/patient/utils/location.utils.ts +126 -126
  209. package/src/services/patient/utils/medical-stuff.utils.ts +143 -143
  210. package/src/services/patient/utils/medical.utils.ts +458 -458
  211. package/src/services/patient/utils/practitioner.utils.ts +260 -260
  212. package/src/services/patient/utils/profile.utils.ts +510 -510
  213. package/src/services/patient/utils/sensitive.utils.ts +260 -260
  214. package/src/services/patient/utils/token.utils.ts +211 -211
  215. package/src/services/practitioner/README.md +145 -145
  216. package/src/services/practitioner/index.ts +1 -1
  217. package/src/services/practitioner/practitioner.service.ts +1742 -1742
  218. package/src/services/procedure/README.md +163 -163
  219. package/src/services/procedure/index.ts +1 -1
  220. package/src/services/procedure/procedure.service.ts +1715 -1715
  221. package/src/services/reviews/index.ts +1 -1
  222. package/src/services/reviews/reviews.service.ts +683 -636
  223. package/src/services/user/index.ts +1 -1
  224. package/src/services/user/user.service.ts +489 -489
  225. package/src/services/user/user.v2.service.ts +466 -466
  226. package/src/types/appointment/index.ts +480 -480
  227. package/src/types/calendar/index.ts +258 -258
  228. package/src/types/calendar/synced-calendar.types.ts +66 -66
  229. package/src/types/clinic/index.ts +489 -489
  230. package/src/types/clinic/practitioner-invite.types.ts +91 -91
  231. package/src/types/clinic/preferences.types.ts +159 -159
  232. package/src/types/clinic/to-do +3 -3
  233. package/src/types/documentation-templates/index.ts +308 -308
  234. package/src/types/index.ts +44 -44
  235. package/src/types/notifications/README.md +77 -77
  236. package/src/types/notifications/index.ts +265 -265
  237. package/src/types/patient/aesthetic-analysis.types.ts +66 -66
  238. package/src/types/patient/allergies.ts +58 -58
  239. package/src/types/patient/index.ts +275 -275
  240. package/src/types/patient/medical-info.types.ts +152 -152
  241. package/src/types/patient/patient-requirements.ts +92 -92
  242. package/src/types/patient/token.types.ts +61 -61
  243. package/src/types/practitioner/index.ts +206 -206
  244. package/src/types/procedure/index.ts +181 -181
  245. package/src/types/profile/index.ts +39 -39
  246. package/src/types/reviews/index.ts +132 -130
  247. package/src/types/tz-lookup.d.ts +4 -4
  248. package/src/types/user/index.ts +38 -38
  249. package/src/utils/TIMESTAMPS.md +176 -176
  250. package/src/utils/TimestampUtils.ts +241 -241
  251. package/src/utils/index.ts +1 -1
  252. package/src/validations/appointment.schema.ts +574 -574
  253. package/src/validations/calendar.schema.ts +225 -225
  254. package/src/validations/clinic.schema.ts +493 -493
  255. package/src/validations/common.schema.ts +25 -25
  256. package/src/validations/documentation-templates/index.ts +1 -1
  257. package/src/validations/documentation-templates/template.schema.ts +220 -220
  258. package/src/validations/documentation-templates.schema.ts +10 -10
  259. package/src/validations/index.ts +20 -20
  260. package/src/validations/media.schema.ts +10 -10
  261. package/src/validations/notification.schema.ts +90 -90
  262. package/src/validations/patient/aesthetic-analysis.schema.ts +55 -55
  263. package/src/validations/patient/medical-info.schema.ts +125 -125
  264. package/src/validations/patient/patient-requirements.schema.ts +84 -84
  265. package/src/validations/patient/token.schema.ts +29 -29
  266. package/src/validations/patient.schema.ts +217 -217
  267. package/src/validations/practitioner.schema.ts +222 -222
  268. package/src/validations/procedure-product.schema.ts +41 -41
  269. package/src/validations/procedure.schema.ts +124 -124
  270. package/src/validations/profile-info.schema.ts +41 -41
  271. package/src/validations/reviews.schema.ts +195 -189
  272. package/src/validations/schemas.ts +104 -104
  273. package/src/validations/shared.schema.ts +78 -78
@@ -1,1715 +1,1715 @@
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
- // Process photos if provided
248
- let processedPhotos: string[] = [];
249
- if (validatedData.photos && validatedData.photos.length > 0) {
250
- processedPhotos = await this.processMediaArray(
251
- validatedData.photos,
252
- procedureId,
253
- 'procedure-photos',
254
- );
255
- }
256
-
257
- // If no photos provided and technology has a photoTemplate, use it as default photo
258
- if (processedPhotos.length === 0 && technology.photoTemplate) {
259
- console.log(`[ProcedureService] Using technology photoTemplate as default photo: ${technology.photoTemplate}`);
260
- const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
261
- if (photoTemplateUrl) {
262
- processedPhotos.push(photoTemplateUrl);
263
- } else {
264
- console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
265
- }
266
- }
267
-
268
- // Transform productsMetadata from validation format to ProcedureProduct format
269
- const transformedProductsMetadata = await this.transformProductsMetadata(
270
- validatedData.productsMetadata,
271
- validatedData.technologyId,
272
- );
273
-
274
- // Create aggregated clinic info for the procedure document
275
- const clinicInfo = {
276
- id: clinicSnapshot.id,
277
- name: clinic.name,
278
- description: clinic.description || '',
279
- featuredPhoto:
280
- clinic.featuredPhotos && clinic.featuredPhotos.length > 0
281
- ? typeof clinic.featuredPhotos[0] === 'string'
282
- ? clinic.featuredPhotos[0]
283
- : ''
284
- : typeof clinic.coverPhoto === 'string'
285
- ? clinic.coverPhoto
286
- : '',
287
- location: clinic.location,
288
- contactInfo: clinic.contactInfo,
289
- };
290
-
291
- // Create aggregated doctor info for the procedure document
292
- const doctorInfo = {
293
- id: practitionerSnapshot.id,
294
- name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
295
- description: practitioner.basicInfo.bio || '',
296
- photo:
297
- typeof practitioner.basicInfo.profileImageUrl === 'string'
298
- ? practitioner.basicInfo.profileImageUrl
299
- : '', // Default to empty string if not a processed URL
300
- rating: practitioner.reviewInfo?.averageRating || 0,
301
- services: practitioner.procedures || [],
302
- };
303
-
304
- // Create the procedure object
305
- const { productsMetadata: _, productId: __, photos: ___, ...validatedDataWithoutProductsMetadata } = validatedData;
306
- const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
307
- id: procedureId,
308
- ...validatedDataWithoutProductsMetadata,
309
- // Ensure nameLower is always set even if omitted by client
310
- nameLower: (validatedData as any).nameLower || validatedData.name.toLowerCase(),
311
- photos: processedPhotos,
312
- category, // Embed full objects
313
- subcategory,
314
- technology,
315
- ...(product && { product }), // Only include product field if it exists (Firestore doesn't allow undefined)
316
- productsMetadata: transformedProductsMetadata, // Use transformed data, not original
317
- blockingConditions: technology.blockingConditions,
318
- contraindications: technology.contraindications || [],
319
- contraindicationIds: technology.contraindications?.map(c => c.id) || [],
320
- treatmentBenefits: technology.benefits,
321
- treatmentBenefitIds: Array.isArray(technology.benefits)
322
- ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
323
- : [],
324
- preRequirements: technology.requirements.pre,
325
- postRequirements: technology.requirements.post,
326
- certificationRequirement: technology.certificationRequirement,
327
- documentationTemplates: technology?.documentationTemplates || [],
328
- clinicInfo, // Embed aggregated info
329
- doctorInfo, // Embed aggregated info
330
- reviewInfo: {
331
- // Default empty reviews
332
- totalReviews: 0,
333
- averageRating: 0,
334
- effectivenessOfTreatment: 0,
335
- outcomeExplanation: 0,
336
- painManagement: 0,
337
- followUpCare: 0,
338
- valueForMoney: 0,
339
- recommendationPercentage: 0,
340
- },
341
- isActive: true, // Default to active
342
- };
343
-
344
- // 🔥 DEBUG: Find undefined fields before writing to Firestore
345
- console.log('🔥🔥🔥 CREATE PROCEDURE - Processing procedure:', procedureId);
346
- console.log('🔥🔥🔥 FULL PROCEDURE OBJECT:', JSON.stringify(newProcedure, null, 2));
347
-
348
- const undefinedFields: string[] = [];
349
- Object.entries(newProcedure).forEach(([key, value]) => {
350
- if (value === undefined) {
351
- undefinedFields.push(key);
352
- }
353
- });
354
- if (undefinedFields.length > 0) {
355
- console.error('🔥🔥🔥 UNDEFINED FIELDS DETECTED:', undefinedFields);
356
- throw new Error(`Cannot write procedure with undefined fields: ${undefinedFields.join(', ')}`);
357
- }
358
- console.log('🔥🔥🔥 NO UNDEFINED FIELDS - Proceeding with setDoc');
359
-
360
- // Create the procedure document
361
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
362
- await setDoc(procedureRef, {
363
- ...newProcedure,
364
- createdAt: serverTimestamp(),
365
- updatedAt: serverTimestamp(),
366
- });
367
-
368
- // Return the created procedure (fetch again to get server timestamps)
369
- const savedDoc = await getDoc(procedureRef);
370
- return savedDoc.data() as Procedure;
371
- }
372
-
373
- /**
374
- * Creates multiple procedures for a list of practitioners based on common data.
375
- * This method is optimized for bulk creation to reduce database reads and writes.
376
- *
377
- * @param baseData - The base data for the procedures to be created, omitting the practitionerId.
378
- * @param practitionerIds - An array of practitioner IDs for whom the procedures will be created.
379
- * @returns A promise that resolves to an array of the newly created procedures.
380
- */
381
- async bulkCreateProcedures(
382
- baseData: Omit<CreateProcedureData, 'practitionerId'>,
383
- practitionerIds: string[],
384
- ): Promise<Procedure[]> {
385
- // 1. Validation
386
- if (!practitionerIds || practitionerIds.length === 0) {
387
- throw new Error('Practitioner IDs array cannot be empty.');
388
- }
389
-
390
- // Check if this is a product-free procedure
391
- const isProductFree = !baseData.productId;
392
-
393
- // Add a dummy practitionerId for the validation schema to pass
394
- const validationData = { ...baseData, practitionerId: practitionerIds[0] };
395
- const validatedData = createProcedureSchema.parse(validationData);
396
-
397
- // 2. Fetch common data once to avoid redundant reads
398
- const baseEntitiesPromises: Promise<Category | Subcategory | Technology | Product | null>[] = [
399
- this.categoryService.getById(validatedData.categoryId),
400
- this.subcategoryService.getById(validatedData.categoryId, validatedData.subcategoryId),
401
- this.technologyService.getById(validatedData.technologyId),
402
- ];
403
-
404
- // Only fetch product if productId is provided
405
- if (!isProductFree) {
406
- baseEntitiesPromises.push(
407
- this.productService.getById(validatedData.technologyId, validatedData.productId!)
408
- );
409
- }
410
-
411
- // Fetch clinic separately to maintain type safety
412
- const clinicSnapshotPromise = getDoc(doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId));
413
-
414
- const [baseResults, clinicSnapshot] = await Promise.all([
415
- Promise.all(baseEntitiesPromises),
416
- clinicSnapshotPromise
417
- ]);
418
-
419
- const category = baseResults[0] as Category | null;
420
- const subcategory = baseResults[1] as Subcategory | null;
421
- const technology = baseResults[2] as Technology | null;
422
- const product = isProductFree ? undefined : ((baseResults[3] as Product | null) || undefined);
423
-
424
- if (!category || !subcategory || !technology) {
425
- throw new Error('One or more required base entities not found');
426
- }
427
-
428
- // For regular procedures, validate product exists
429
- if (!isProductFree && !product) {
430
- throw new Error('Product not found for regular procedure');
431
- }
432
-
433
- if (!clinicSnapshot || !clinicSnapshot.exists()) {
434
- throw new Error(`Clinic with ID ${validatedData.clinicBranchId} not found`);
435
- }
436
- const clinic = clinicSnapshot.data() as Clinic;
437
-
438
- // 3. Handle media uploads once for efficiency
439
- let processedPhotos: string[] = [];
440
- if (validatedData.photos && validatedData.photos.length > 0) {
441
- const batchId = this.generateId(); // Use a single ID for all media in this batch
442
- processedPhotos = await this.processMediaArray(
443
- validatedData.photos,
444
- batchId,
445
- 'procedure-photos-batch',
446
- );
447
- }
448
-
449
- // If no photos provided and technology has a photoTemplate, use it as default photo
450
- if (processedPhotos.length === 0 && technology.photoTemplate) {
451
- console.log(`[ProcedureService] Using technology photoTemplate as default photo for bulk create: ${technology.photoTemplate}`);
452
- const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
453
- if (photoTemplateUrl) {
454
- processedPhotos.push(photoTemplateUrl);
455
- } else {
456
- console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
457
- }
458
- }
459
-
460
- // Transform productsMetadata from validation format to ProcedureProduct format
461
- const transformedProductsMetadata = await this.transformProductsMetadata(
462
- validatedData.productsMetadata,
463
- validatedData.technologyId,
464
- );
465
-
466
- // 4. Fetch all practitioner data efficiently
467
- const practitionersMap = new Map<string, Practitioner>();
468
- // Use 'in' query in chunks of 30, as this is the Firestore limit
469
- for (let i = 0; i < practitionerIds.length; i += 30) {
470
- const chunk = practitionerIds.slice(i, i + 30);
471
- const practitionersQuery = query(
472
- collection(this.db, PRACTITIONERS_COLLECTION),
473
- where(documentId(), 'in', chunk),
474
- );
475
- const practitionersSnapshot = await getDocs(practitionersQuery);
476
- practitionersSnapshot.docs.forEach(doc => {
477
- practitionersMap.set(doc.id, doc.data() as Practitioner);
478
- });
479
- }
480
-
481
- // Verify all practitioners were found
482
- if (practitionersMap.size !== practitionerIds.length) {
483
- const foundIds = Array.from(practitionersMap.keys());
484
- const notFoundIds = practitionerIds.filter(id => !foundIds.includes(id));
485
- throw new Error(`The following practitioners were not found: ${notFoundIds.join(', ')}`);
486
- }
487
-
488
- // 5. Use a Firestore batch for atomic creation
489
- const batch = writeBatch(this.db);
490
- const createdProcedureIds: string[] = [];
491
- const clinicInfo = {
492
- id: clinicSnapshot.id,
493
- name: clinic.name,
494
- description: clinic.description || '',
495
- featuredPhoto:
496
- clinic.featuredPhotos && clinic.featuredPhotos.length > 0
497
- ? typeof clinic.featuredPhotos[0] === 'string'
498
- ? clinic.featuredPhotos[0]
499
- : ''
500
- : typeof clinic.coverPhoto === 'string'
501
- ? clinic.coverPhoto
502
- : '',
503
- location: clinic.location,
504
- contactInfo: clinic.contactInfo,
505
- };
506
-
507
- for (const practitionerId of practitionerIds) {
508
- const practitioner = practitionersMap.get(practitionerId)!;
509
-
510
- const doctorInfo = {
511
- id: practitioner.id,
512
- name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
513
- description: practitioner.basicInfo.bio || '',
514
- photo:
515
- typeof practitioner.basicInfo.profileImageUrl === 'string'
516
- ? practitioner.basicInfo.profileImageUrl
517
- : '',
518
- rating: practitioner.reviewInfo?.averageRating || 0,
519
- services: practitioner.procedures || [],
520
- };
521
-
522
- const procedureId = this.generateId();
523
- createdProcedureIds.push(procedureId);
524
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
525
-
526
- // Construct the new procedure, reusing common data
527
- const { productsMetadata: _, productId: __, photos: ___, ...validatedDataWithoutProductsMetadata } = validatedData;
528
- const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
529
- id: procedureId,
530
- ...validatedDataWithoutProductsMetadata,
531
- nameLower: (validatedData as any).nameLower || validatedData.name.toLowerCase(),
532
- practitionerId: practitionerId, // Override practitionerId with the correct one
533
- photos: processedPhotos,
534
- category,
535
- subcategory,
536
- technology,
537
- ...(product && { product }), // Only include product field if it exists (Firestore doesn't allow undefined)
538
- productsMetadata: transformedProductsMetadata, // Use transformed data, not original
539
- blockingConditions: technology.blockingConditions,
540
- contraindications: technology.contraindications || [],
541
- contraindicationIds: technology.contraindications?.map(c => c.id) || [],
542
- treatmentBenefits: technology.benefits,
543
- treatmentBenefitIds: Array.isArray(technology.benefits)
544
- ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
545
- : [],
546
- preRequirements: technology.requirements.pre,
547
- postRequirements: technology.requirements.post,
548
- certificationRequirement: technology.certificationRequirement,
549
- documentationTemplates: technology?.documentationTemplates || [],
550
- clinicInfo,
551
- doctorInfo, // Set specific doctor info
552
- reviewInfo: {
553
- totalReviews: 0,
554
- averageRating: 0,
555
- effectivenessOfTreatment: 0,
556
- outcomeExplanation: 0,
557
- painManagement: 0,
558
- followUpCare: 0,
559
- valueForMoney: 0,
560
- recommendationPercentage: 0,
561
- },
562
- isActive: true,
563
- };
564
-
565
- // 🔥 DEBUG: Find undefined fields before writing to Firestore
566
- console.log('🔥🔥🔥 BULK CREATE - Processing procedure:', procedureId, 'for practitioner:', practitionerId);
567
- console.log('🔥🔥🔥 FULL PROCEDURE OBJECT:', JSON.stringify(newProcedure, null, 2));
568
-
569
- const undefinedFields: string[] = [];
570
- Object.entries(newProcedure).forEach(([key, value]) => {
571
- if (value === undefined) {
572
- undefinedFields.push(key);
573
- }
574
- });
575
- if (undefinedFields.length > 0) {
576
- console.error('🔥🔥🔥 UNDEFINED FIELDS DETECTED:', undefinedFields);
577
- throw new Error(`Cannot write procedure with undefined fields: ${undefinedFields.join(', ')}`);
578
- }
579
- console.log('🔥🔥🔥 NO UNDEFINED FIELDS - Proceeding with batch.set');
580
-
581
- batch.set(procedureRef, {
582
- ...newProcedure,
583
- createdAt: serverTimestamp(),
584
- updatedAt: serverTimestamp(),
585
- });
586
- }
587
-
588
- // 6. Commit the atomic batch write
589
- await batch.commit();
590
-
591
- // 7. Fetch and return the newly created procedures
592
- const fetchedProcedures: Procedure[] = [];
593
- for (let i = 0; i < createdProcedureIds.length; i += 30) {
594
- const chunk = createdProcedureIds.slice(i, i + 30);
595
- const q = query(collection(this.db, PROCEDURES_COLLECTION), where(documentId(), 'in', chunk));
596
- const snapshot = await getDocs(q);
597
- snapshot.forEach(doc => {
598
- fetchedProcedures.push(doc.data() as Procedure);
599
- });
600
- }
601
-
602
- return fetchedProcedures;
603
- }
604
-
605
- /**
606
- * Gets a procedure by ID
607
- * @param id - The ID of the procedure to get
608
- * @returns The procedure if found, null otherwise
609
- */
610
- async getProcedure(id: string): Promise<Procedure | null> {
611
- const docRef = doc(this.db, PROCEDURES_COLLECTION, id);
612
- const docSnap = await getDoc(docRef);
613
-
614
- if (!docSnap.exists()) {
615
- return null;
616
- }
617
-
618
- return docSnap.data() as Procedure;
619
- }
620
-
621
- /**
622
- * Gets all procedures for a clinic branch
623
- * @param clinicBranchId - The ID of the clinic branch
624
- * @returns List of procedures
625
- */
626
- async getProceduresByClinicBranch(clinicBranchId: string): Promise<Procedure[]> {
627
- const q = query(
628
- collection(this.db, PROCEDURES_COLLECTION),
629
- where('clinicBranchId', '==', clinicBranchId),
630
- where('isActive', '==', true),
631
- );
632
- const snapshot = await getDocs(q);
633
- return snapshot.docs.map(doc => doc.data() as Procedure);
634
- }
635
-
636
- /**
637
- * Gets all procedures for a practitioner
638
- * @param practitionerId - The ID of the practitioner
639
- * @returns List of procedures
640
- */
641
- async getProceduresByPractitioner(practitionerId: string): Promise<Procedure[]> {
642
- const q = query(
643
- collection(this.db, PROCEDURES_COLLECTION),
644
- where('practitionerId', '==', practitionerId),
645
- where('isActive', '==', true),
646
- );
647
- const snapshot = await getDocs(q);
648
- return snapshot.docs.map(doc => doc.data() as Procedure);
649
- }
650
-
651
- /**
652
- * Gets all inactive procedures for a practitioner
653
- * @param practitionerId - The ID of the practitioner
654
- * @returns List of inactive procedures
655
- */
656
- async getInactiveProceduresByPractitioner(practitionerId: string): Promise<Procedure[]> {
657
- const q = query(
658
- collection(this.db, PROCEDURES_COLLECTION),
659
- where('practitionerId', '==', practitionerId),
660
- where('isActive', '==', false),
661
- );
662
- const snapshot = await getDocs(q);
663
- return snapshot.docs.map(doc => doc.data() as Procedure);
664
- }
665
-
666
- /**
667
- * Updates a procedure
668
- * @param id - The ID of the procedure to update
669
- * @param data - The data to update the procedure with
670
- * @returns The updated procedure
671
- */
672
- async updateProcedure(id: string, data: UpdateProcedureData): Promise<Procedure> {
673
- const validatedData = updateProcedureSchema.parse(data);
674
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
675
- const procedureSnapshot = await getDoc(procedureRef);
676
-
677
- if (!procedureSnapshot.exists()) {
678
- throw new Error(`Procedure with ID ${id} not found`);
679
- }
680
-
681
- const existingProcedure = procedureSnapshot.data() as Procedure;
682
- let updatedProcedureData: Partial<Procedure> = {};
683
-
684
- // Copy validated simple fields
685
- if (validatedData.name !== undefined) updatedProcedureData.name = validatedData.name;
686
- if (validatedData.description !== undefined)
687
- updatedProcedureData.description = validatedData.description;
688
- if (validatedData.price !== undefined) updatedProcedureData.price = validatedData.price;
689
- if (validatedData.currency !== undefined)
690
- updatedProcedureData.currency = validatedData.currency;
691
- if (validatedData.pricingMeasure !== undefined)
692
- updatedProcedureData.pricingMeasure = validatedData.pricingMeasure;
693
- if (validatedData.duration !== undefined)
694
- updatedProcedureData.duration = validatedData.duration;
695
- if (validatedData.isActive !== undefined)
696
- updatedProcedureData.isActive = validatedData.isActive;
697
-
698
- let practitionerChanged = false;
699
- let clinicChanged = false;
700
- const oldPractitionerId = existingProcedure.practitionerId;
701
- const oldClinicId = existingProcedure.clinicBranchId;
702
- let newPractitioner: Practitioner | null = null;
703
- let newClinic: Clinic | null = null;
704
-
705
- // Process photos if provided
706
- if (validatedData.photos !== undefined) {
707
- updatedProcedureData.photos = await this.processMediaArray(
708
- validatedData.photos,
709
- id,
710
- 'procedure-photos',
711
- );
712
- }
713
-
714
- // Transform productsMetadata if provided
715
- if (validatedData.productsMetadata !== undefined) {
716
- const technologyId = validatedData.technologyId ?? existingProcedure.technology.id;
717
- if (!technologyId) {
718
- throw new Error('Technology ID is required for updating products metadata');
719
- }
720
- updatedProcedureData.productsMetadata = await this.transformProductsMetadata(
721
- validatedData.productsMetadata,
722
- technologyId,
723
- );
724
- }
725
-
726
- // --- Prepare updates and fetch new related data if IDs change ---
727
-
728
- // Handle Practitioner Change
729
- if (validatedData.practitionerId && validatedData.practitionerId !== oldPractitionerId) {
730
- practitionerChanged = true;
731
- const newPractitionerRef = doc(
732
- this.db,
733
- PRACTITIONERS_COLLECTION,
734
- validatedData.practitionerId,
735
- );
736
- const newPractitionerSnap = await getDoc(newPractitionerRef);
737
- if (!newPractitionerSnap.exists())
738
- throw new Error(`New Practitioner ${validatedData.practitionerId} not found`);
739
- newPractitioner = newPractitionerSnap.data() as Practitioner;
740
- // Update doctorInfo within the procedure document
741
- updatedProcedureData.doctorInfo = {
742
- id: newPractitioner.id,
743
- name: `${newPractitioner.basicInfo.firstName} ${newPractitioner.basicInfo.lastName}`,
744
- description: newPractitioner.basicInfo.bio || '',
745
- photo:
746
- typeof newPractitioner.basicInfo.profileImageUrl === 'string'
747
- ? newPractitioner.basicInfo.profileImageUrl
748
- : '', // Default to empty string if not a processed URL
749
- rating: newPractitioner.reviewInfo?.averageRating || 0,
750
- services: newPractitioner.procedures || [],
751
- };
752
- }
753
-
754
- // Handle Clinic Change
755
- if (validatedData.clinicBranchId && validatedData.clinicBranchId !== oldClinicId) {
756
- clinicChanged = true;
757
- const newClinicRef = doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId);
758
- const newClinicSnap = await getDoc(newClinicRef);
759
- if (!newClinicSnap.exists())
760
- throw new Error(`New Clinic ${validatedData.clinicBranchId} not found`);
761
- newClinic = newClinicSnap.data() as Clinic;
762
- // Update clinicInfo within the procedure document
763
- updatedProcedureData.clinicInfo = {
764
- id: newClinic.id,
765
- name: newClinic.name,
766
- description: newClinic.description || '',
767
- featuredPhoto:
768
- newClinic.featuredPhotos && newClinic.featuredPhotos.length > 0
769
- ? typeof newClinic.featuredPhotos[0] === 'string'
770
- ? newClinic.featuredPhotos[0]
771
- : ''
772
- : typeof newClinic.coverPhoto === 'string'
773
- ? newClinic.coverPhoto
774
- : '',
775
- location: newClinic.location,
776
- contactInfo: newClinic.contactInfo,
777
- };
778
- }
779
-
780
- // Handle Category/Subcategory/Technology/Product Changes
781
- let finalCategoryId = existingProcedure.category.id;
782
- if (validatedData.name) {
783
- updatedProcedureData.nameLower = validatedData.name.toLowerCase();
784
- }
785
- if (validatedData.categoryId) {
786
- const category = await this.categoryService.getById(validatedData.categoryId);
787
- if (!category) throw new Error(`Category ${validatedData.categoryId} not found`);
788
- updatedProcedureData.category = category;
789
- finalCategoryId = category.id; // Update finalCategoryId if category changed
790
- }
791
-
792
- // Only fetch subcategory if its ID is provided AND we have a valid finalCategoryId
793
- if (validatedData.subcategoryId && finalCategoryId) {
794
- const subcategory = await this.subcategoryService.getById(
795
- finalCategoryId,
796
- validatedData.subcategoryId,
797
- );
798
- if (!subcategory)
799
- throw new Error(
800
- `Subcategory ${validatedData.subcategoryId} not found for category ${finalCategoryId}`,
801
- );
802
- updatedProcedureData.subcategory = subcategory;
803
- } else if (validatedData.subcategoryId) {
804
- console.warn('Attempted to update subcategory without a valid categoryId');
805
- }
806
-
807
- let finalTechnologyId = existingProcedure.technology.id;
808
- if (validatedData.technologyId) {
809
- const technology = await this.technologyService.getById(validatedData.technologyId);
810
- if (!technology) throw new Error(`Technology ${validatedData.technologyId} not found`);
811
- updatedProcedureData.technology = technology;
812
- finalTechnologyId = technology.id; // Update finalTechnologyId if technology changed
813
- // Update related fields derived from technology
814
- updatedProcedureData.blockingConditions = technology.blockingConditions;
815
- updatedProcedureData.contraindications = technology.contraindications || [];
816
- updatedProcedureData.contraindicationIds = technology.contraindications?.map(c => c.id) || [];
817
- updatedProcedureData.treatmentBenefits = technology.benefits;
818
- updatedProcedureData.treatmentBenefitIds = Array.isArray(technology.benefits)
819
- ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
820
- : [];
821
- updatedProcedureData.preRequirements = technology.requirements.pre;
822
- updatedProcedureData.postRequirements = technology.requirements.post;
823
- updatedProcedureData.certificationRequirement = technology.certificationRequirement;
824
- updatedProcedureData.documentationTemplates = technology.documentationTemplates || [];
825
- }
826
-
827
- // Only fetch product if its ID is provided AND we have a valid finalTechnologyId
828
- if (validatedData.productId && finalTechnologyId) {
829
- const product = await this.productService.getById(finalTechnologyId, validatedData.productId);
830
- if (!product)
831
- throw new Error(
832
- `Product ${validatedData.productId} not found for technology ${finalTechnologyId}`,
833
- );
834
- updatedProcedureData.product = product;
835
- } else if (validatedData.productId) {
836
- console.warn('Attempted to update product without a valid technologyId');
837
- }
838
-
839
- // Update the procedure document
840
- await updateDoc(procedureRef, {
841
- ...updatedProcedureData,
842
- updatedAt: serverTimestamp(),
843
- });
844
-
845
- // Return the updated procedure
846
- const updatedSnapshot = await getDoc(procedureRef);
847
- return updatedSnapshot.data() as Procedure;
848
- }
849
-
850
- /**
851
- * Deactivates a procedure (soft delete)
852
- * @param id - The ID of the procedure to deactivate
853
- */
854
- async deactivateProcedure(id: string): Promise<void> {
855
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
856
- const procedureSnap = await getDoc(procedureRef);
857
- if (!procedureSnap.exists()) {
858
- console.warn(`Procedure ${id} not found for deactivation.`);
859
- return;
860
- }
861
-
862
- // Mark procedure as inactive
863
- await updateDoc(procedureRef, {
864
- isActive: false,
865
- updatedAt: serverTimestamp(),
866
- });
867
- }
868
-
869
- /**
870
- * Deletes a procedure permanently
871
- * @param id - The ID of the procedure to delete
872
- * @returns A boolean indicating if the deletion was successful
873
- */
874
- async deleteProcedure(id: string): Promise<boolean> {
875
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
876
- const procedureSnapshot = await getDoc(procedureRef);
877
-
878
- if (!procedureSnapshot.exists()) {
879
- // Already deleted or never existed
880
- return false;
881
- }
882
-
883
- // Delete the procedure document
884
- await deleteDoc(procedureRef);
885
- return true;
886
- }
887
-
888
- /**
889
- * Gets all procedures that a practitioner is certified to perform
890
- * @param practitioner - The practitioner's profile
891
- * @returns Object containing allowed technologies, families, categories, subcategories
892
- */
893
- async getAllowedTechnologies(practitioner: Practitioner): Promise<{
894
- technologies: Technology[];
895
- families: ProcedureFamily[];
896
- categories: string[];
897
- subcategories: string[];
898
- }> {
899
- // This logic depends on TechnologyService and remains valid
900
- const { technologies, families, categories, subcategories } =
901
- await this.technologyService.getAllowedTechnologies(practitioner);
902
-
903
- return {
904
- technologies,
905
- families,
906
- categories,
907
- subcategories,
908
- };
909
- }
910
-
911
- /**
912
- * Gets all procedures with optional pagination
913
- *
914
- * @param pagination - Optional number of procedures per page (0 or undefined returns all)
915
- * @param lastDoc - Optional last document for pagination (if continuing from a previous page)
916
- * @returns Object containing procedures array and the last document for pagination
917
- */
918
- async getAllProcedures(
919
- pagination?: number,
920
- lastDoc?: any,
921
- ): Promise<{ procedures: Procedure[]; lastDoc: any }> {
922
- try {
923
- const proceduresCollection = collection(this.db, PROCEDURES_COLLECTION);
924
- let proceduresQuery = query(proceduresCollection);
925
-
926
- // Apply pagination if specified
927
- if (pagination && pagination > 0) {
928
- const { limit, startAfter } = await import('firebase/firestore'); // Use dynamic import if needed top-level
929
-
930
- if (lastDoc) {
931
- proceduresQuery = query(
932
- proceduresCollection,
933
- orderBy('name'), // Use imported orderBy
934
- startAfter(lastDoc),
935
- limit(pagination),
936
- );
937
- } else {
938
- proceduresQuery = query(proceduresCollection, orderBy('name'), limit(pagination)); // Use imported orderBy
939
- }
940
- } else {
941
- proceduresQuery = query(proceduresCollection, orderBy('name')); // Use imported orderBy
942
- }
943
-
944
- const proceduresSnapshot = await getDocs(proceduresQuery);
945
- const lastVisible = proceduresSnapshot.docs[proceduresSnapshot.docs.length - 1];
946
-
947
- const procedures = proceduresSnapshot.docs.map(doc => {
948
- const data = doc.data() as Procedure;
949
- return {
950
- ...data,
951
- id: doc.id, // Ensure ID is present
952
- };
953
- });
954
-
955
- return {
956
- procedures,
957
- lastDoc: lastVisible,
958
- };
959
- } catch (error) {
960
- console.error('[PROCEDURE_SERVICE] Error getting all procedures:', error);
961
- throw error;
962
- }
963
- }
964
-
965
- /**
966
- * Searches and filters procedures based on multiple criteria
967
- *
968
- * @note Frontend MORA da šalje ceo snapshot (ili barem sva polja po kojima sortiraš, npr. nameLower) kao lastDoc za paginaciju, a ne samo id!
969
- *
970
- * @param filters - Various filters to apply
971
- * @param filters.nameSearch - Optional search text for procedure name
972
- * @param filters.treatmentBenefitIds - Optional array of treatment benefits to filter by
973
- * @param filters.procedureFamily - Optional procedure family to filter by
974
- * @param filters.procedureCategory - Optional procedure category to filter by
975
- * @param filters.procedureSubcategory - Optional procedure subcategory to filter by
976
- * @param filters.procedureTechnology - Optional procedure technology to filter by
977
- * @param filters.location - Optional location for distance-based search
978
- * @param filters.radiusInKm - Optional radius in kilometers (required if location is provided)
979
- * @param filters.minPrice - Optional minimum price
980
- * @param filters.maxPrice - Optional maximum price
981
- * @param filters.minRating - Optional minimum rating (0-5)
982
- * @param filters.maxRating - Optional maximum rating (0-5)
983
- * @param filters.pagination - Optional number of results per page
984
- * @param filters.lastDoc - Optional last document for pagination
985
- * @param filters.isActive - Optional filter for active procedures only
986
- * @returns Filtered procedures and the last document for pagination
987
- */
988
- async getProceduresByFilters(filters: {
989
- nameSearch?: string;
990
- treatmentBenefits?: string[];
991
- procedureFamily?: ProcedureFamily;
992
- procedureCategory?: string;
993
- procedureSubcategory?: string;
994
- procedureTechnology?: string;
995
- location?: { latitude: number; longitude: number };
996
- radiusInKm?: number;
997
- minPrice?: number;
998
- maxPrice?: number;
999
- minRating?: number;
1000
- maxRating?: number;
1001
- pagination?: number;
1002
- lastDoc?: any;
1003
- isActive?: boolean;
1004
- practitionerId?: string;
1005
- clinicId?: string;
1006
- }): Promise<{
1007
- procedures: (Procedure & { distance?: number })[];
1008
- lastDoc: any;
1009
- }> {
1010
- try {
1011
- console.log('[PROCEDURE_SERVICE] Starting procedure filtering with multiple strategies');
1012
-
1013
- // Geo query debug i validacija
1014
- if (filters.location && filters.radiusInKm) {
1015
- console.log('[PROCEDURE_SERVICE] Executing geo query:', {
1016
- location: filters.location,
1017
- radius: filters.radiusInKm,
1018
- serviceName: 'ProcedureService',
1019
- });
1020
-
1021
- // Validacija location podataka
1022
- if (!filters.location.latitude || !filters.location.longitude) {
1023
- console.warn('[PROCEDURE_SERVICE] Invalid location data:', filters.location);
1024
- filters.location = undefined;
1025
- filters.radiusInKm = undefined;
1026
- }
1027
- }
1028
-
1029
- // Handle geo queries separately (they work differently)
1030
- const isGeoQuery = filters.location && filters.radiusInKm && filters.radiusInKm > 0;
1031
- if (isGeoQuery) {
1032
- return this.handleGeoQuery(filters);
1033
- }
1034
-
1035
- // Base constraints (used in all strategies)
1036
- const getBaseConstraints = () => {
1037
- const constraints: QueryConstraint[] = [];
1038
-
1039
- // Active status filter
1040
- if (filters.isActive !== undefined) {
1041
- constraints.push(where('isActive', '==', filters.isActive));
1042
- } else {
1043
- constraints.push(where('isActive', '==', true));
1044
- }
1045
-
1046
- // Filter constraints
1047
- if (filters.procedureFamily) {
1048
- constraints.push(where('family', '==', filters.procedureFamily));
1049
- }
1050
- if (filters.procedureCategory) {
1051
- constraints.push(where('category.id', '==', filters.procedureCategory));
1052
- }
1053
- if (filters.procedureSubcategory) {
1054
- constraints.push(where('subcategory.id', '==', filters.procedureSubcategory));
1055
- }
1056
- if (filters.procedureTechnology) {
1057
- constraints.push(where('technology.id', '==', filters.procedureTechnology));
1058
- }
1059
- if (filters.practitionerId) {
1060
- constraints.push(where('practitionerId', '==', filters.practitionerId));
1061
- }
1062
- if (filters.clinicId) {
1063
- constraints.push(where('clinicBranchId', '==', filters.clinicId));
1064
- }
1065
- if (filters.minPrice !== undefined) {
1066
- constraints.push(where('price', '>=', filters.minPrice));
1067
- }
1068
- if (filters.maxPrice !== undefined) {
1069
- constraints.push(where('price', '<=', filters.maxPrice));
1070
- }
1071
- if (filters.minRating !== undefined) {
1072
- constraints.push(where('reviewInfo.averageRating', '>=', filters.minRating));
1073
- }
1074
- if (filters.maxRating !== undefined) {
1075
- constraints.push(where('reviewInfo.averageRating', '<=', filters.maxRating));
1076
- }
1077
- if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
1078
- const benefitIdsToMatch = filters.treatmentBenefits;
1079
- constraints.push(where('treatmentBenefitIds', 'array-contains-any', benefitIdsToMatch));
1080
- }
1081
-
1082
- return constraints;
1083
- };
1084
-
1085
- // Strategy 1: Try nameLower search if nameSearch exists
1086
- if (filters.nameSearch && filters.nameSearch.trim()) {
1087
- try {
1088
- console.log('[PROCEDURE_SERVICE] Strategy 1: Trying nameLower search');
1089
- const searchTerm = filters.nameSearch.trim().toLowerCase();
1090
- const constraints = getBaseConstraints();
1091
- constraints.push(where('nameLower', '>=', searchTerm));
1092
- constraints.push(where('nameLower', '<=', searchTerm + '\uf8ff'));
1093
- constraints.push(orderBy('nameLower'));
1094
-
1095
- if (filters.lastDoc) {
1096
- if (typeof filters.lastDoc.data === 'function') {
1097
- constraints.push(startAfter(filters.lastDoc));
1098
- } else if (Array.isArray(filters.lastDoc)) {
1099
- constraints.push(startAfter(...filters.lastDoc));
1100
- } else {
1101
- constraints.push(startAfter(filters.lastDoc));
1102
- }
1103
- }
1104
- constraints.push(limit(filters.pagination || 10));
1105
-
1106
- const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1107
- const querySnapshot = await getDocs(q);
1108
- const procedures = querySnapshot.docs.map(
1109
- doc => ({ ...doc.data(), id: doc.id } as Procedure),
1110
- );
1111
- const lastDoc =
1112
- querySnapshot.docs.length > 0
1113
- ? querySnapshot.docs[querySnapshot.docs.length - 1]
1114
- : null;
1115
-
1116
- console.log(`[PROCEDURE_SERVICE] Strategy 1 success: ${procedures.length} procedures`);
1117
-
1118
- // Fix Load More - ako je broj rezultata manji od pagination, nema više
1119
- if (procedures.length < (filters.pagination || 10)) {
1120
- return { procedures, lastDoc: null };
1121
- }
1122
- return { procedures, lastDoc };
1123
- } catch (error) {
1124
- console.log('[PROCEDURE_SERVICE] Strategy 1 failed:', error);
1125
- }
1126
- }
1127
-
1128
- // Strategy 2: Try name field search as fallback
1129
- if (filters.nameSearch && filters.nameSearch.trim()) {
1130
- try {
1131
- console.log('[PROCEDURE_SERVICE] Strategy 2: Trying name field search');
1132
- const searchTerm = filters.nameSearch.trim().toLowerCase();
1133
- const constraints = getBaseConstraints();
1134
- constraints.push(where('name', '>=', searchTerm));
1135
- constraints.push(where('name', '<=', searchTerm + '\uf8ff'));
1136
- constraints.push(orderBy('name'));
1137
-
1138
- if (filters.lastDoc) {
1139
- if (typeof filters.lastDoc.data === 'function') {
1140
- constraints.push(startAfter(filters.lastDoc));
1141
- } else if (Array.isArray(filters.lastDoc)) {
1142
- constraints.push(startAfter(...filters.lastDoc));
1143
- } else {
1144
- constraints.push(startAfter(filters.lastDoc));
1145
- }
1146
- }
1147
- constraints.push(limit(filters.pagination || 10));
1148
-
1149
- const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1150
- const querySnapshot = await getDocs(q);
1151
- const procedures = querySnapshot.docs.map(
1152
- doc => ({ ...doc.data(), id: doc.id } as Procedure),
1153
- );
1154
- const lastDoc =
1155
- querySnapshot.docs.length > 0
1156
- ? querySnapshot.docs[querySnapshot.docs.length - 1]
1157
- : null;
1158
-
1159
- console.log(`[PROCEDURE_SERVICE] Strategy 2 success: ${procedures.length} procedures`);
1160
-
1161
- // Fix Load More - ako je broj rezultata manji od pagination, nema više
1162
- if (procedures.length < (filters.pagination || 10)) {
1163
- return { procedures, lastDoc: null };
1164
- }
1165
- return { procedures, lastDoc };
1166
- } catch (error) {
1167
- console.log('[PROCEDURE_SERVICE] Strategy 2 failed:', error);
1168
- }
1169
- }
1170
-
1171
- // Strategy 3: orderBy createdAt with client-side filtering
1172
- try {
1173
- console.log(
1174
- '[PROCEDURE_SERVICE] Strategy 3: Using createdAt orderBy with client-side filtering',
1175
- );
1176
- const constraints = getBaseConstraints();
1177
- constraints.push(orderBy('createdAt', 'desc'));
1178
-
1179
- if (filters.lastDoc) {
1180
- if (typeof filters.lastDoc.data === 'function') {
1181
- constraints.push(startAfter(filters.lastDoc));
1182
- } else if (Array.isArray(filters.lastDoc)) {
1183
- constraints.push(startAfter(...filters.lastDoc));
1184
- } else {
1185
- constraints.push(startAfter(filters.lastDoc));
1186
- }
1187
- }
1188
- constraints.push(limit(filters.pagination || 10));
1189
-
1190
- const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1191
- const querySnapshot = await getDocs(q);
1192
- let procedures = querySnapshot.docs.map(
1193
- doc => ({ ...doc.data(), id: doc.id } as Procedure),
1194
- );
1195
-
1196
- // Apply all client-side filters using centralized function
1197
- procedures = this.applyInMemoryFilters(procedures, filters);
1198
-
1199
- const lastDoc =
1200
- querySnapshot.docs.length > 0 ? querySnapshot.docs[querySnapshot.docs.length - 1] : null;
1201
- console.log(`[PROCEDURE_SERVICE] Strategy 3 success: ${procedures.length} procedures`);
1202
-
1203
- // Fix Load More - ako je broj rezultata manji od pagination, nema više
1204
- if (procedures.length < (filters.pagination || 10)) {
1205
- return { procedures, lastDoc: null };
1206
- }
1207
- return { procedures, lastDoc };
1208
- } catch (error) {
1209
- console.log('[PROCEDURE_SERVICE] Strategy 3 failed:', error);
1210
- }
1211
-
1212
- // Strategy 4: Minimal query fallback
1213
- try {
1214
- console.log('[PROCEDURE_SERVICE] Strategy 4: Minimal query fallback');
1215
- const constraints: QueryConstraint[] = [
1216
- where('isActive', '==', filters.isActive !== undefined ? filters.isActive : true),
1217
- orderBy('createdAt', 'desc'),
1218
- ];
1219
- if (filters.practitionerId) {
1220
- constraints.push(where('practitionerId', '==', filters.practitionerId));
1221
- }
1222
- if (filters.clinicId) {
1223
- constraints.push(where('clinicBranchId', '==', filters.clinicId));
1224
- }
1225
- constraints.push(limit(filters.pagination || 10));
1226
-
1227
- const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1228
- const querySnapshot = await getDocs(q);
1229
- let procedures = querySnapshot.docs.map(
1230
- doc => ({ ...doc.data(), id: doc.id } as Procedure),
1231
- );
1232
-
1233
- // Apply all client-side filters using centralized function
1234
- procedures = this.applyInMemoryFilters(procedures, filters);
1235
-
1236
- const lastDoc =
1237
- querySnapshot.docs.length > 0 ? querySnapshot.docs[querySnapshot.docs.length - 1] : null;
1238
- console.log(`[PROCEDURE_SERVICE] Strategy 4 success: ${procedures.length} procedures`);
1239
-
1240
- // Fix Load More - ako je broj rezultata manji od pagination, nema više
1241
- if (procedures.length < (filters.pagination || 10)) {
1242
- return { procedures, lastDoc: null };
1243
- }
1244
- return { procedures, lastDoc };
1245
- } catch (error) {
1246
- console.log('[PROCEDURE_SERVICE] Strategy 4 failed:', error);
1247
- }
1248
-
1249
- // All strategies failed
1250
- console.log('[PROCEDURE_SERVICE] All strategies failed, returning empty result');
1251
- return { procedures: [], lastDoc: null };
1252
- } catch (error) {
1253
- console.error('[PROCEDURE_SERVICE] Error filtering procedures:', error);
1254
- return { procedures: [], lastDoc: null };
1255
- }
1256
- }
1257
-
1258
- /**
1259
- * Applies in-memory filters to procedures array
1260
- * Used when Firestore queries fail or for complex filtering
1261
- */
1262
- private applyInMemoryFilters(
1263
- procedures: Procedure[],
1264
- filters: any,
1265
- ): (Procedure & { distance?: number })[] {
1266
- let filteredProcedures = [...procedures]; // Create copy to avoid mutating original
1267
-
1268
- // Name search filter
1269
- if (filters.nameSearch && filters.nameSearch.trim()) {
1270
- const searchTerm = filters.nameSearch.trim().toLowerCase();
1271
- filteredProcedures = filteredProcedures.filter(procedure => {
1272
- const name = (procedure.name || '').toLowerCase();
1273
- const nameLower = procedure.nameLower || '';
1274
- return name.includes(searchTerm) || nameLower.includes(searchTerm);
1275
- });
1276
- console.log(`[PROCEDURE_SERVICE] Applied name filter, results: ${filteredProcedures.length}`);
1277
- }
1278
-
1279
- // Price filtering
1280
- if (filters.minPrice !== undefined || filters.maxPrice !== undefined) {
1281
- filteredProcedures = filteredProcedures.filter(procedure => {
1282
- const price = procedure.price || 0;
1283
- if (filters.minPrice !== undefined && price < filters.minPrice) return false;
1284
- if (filters.maxPrice !== undefined && price > filters.maxPrice) return false;
1285
- return true;
1286
- });
1287
- console.log(
1288
- `[PROCEDURE_SERVICE] Applied price filter (${filters.minPrice}-${filters.maxPrice}), results: ${filteredProcedures.length}`,
1289
- );
1290
- }
1291
-
1292
- // Rating filtering
1293
- if (filters.minRating !== undefined || filters.maxRating !== undefined) {
1294
- filteredProcedures = filteredProcedures.filter(procedure => {
1295
- const rating = procedure.reviewInfo?.averageRating || 0;
1296
- if (filters.minRating !== undefined && rating < filters.minRating) return false;
1297
- if (filters.maxRating !== undefined && rating > filters.maxRating) return false;
1298
- return true;
1299
- });
1300
- console.log(
1301
- `[PROCEDURE_SERVICE] Applied rating filter, results: ${filteredProcedures.length}`,
1302
- );
1303
- }
1304
-
1305
- // Treatment benefits filtering
1306
- if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
1307
- const benefitIdsToMatch = filters.treatmentBenefits;
1308
- filteredProcedures = filteredProcedures.filter(procedure => {
1309
- const procedureBenefitIds = procedure.treatmentBenefitIds || [];
1310
- return benefitIdsToMatch.some((benefitId: string) =>
1311
- procedureBenefitIds.includes(benefitId),
1312
- );
1313
- });
1314
- console.log(
1315
- `[PROCEDURE_SERVICE] Applied benefits filter, results: ${filteredProcedures.length}`,
1316
- );
1317
- }
1318
-
1319
- // Procedure family filtering
1320
- if (filters.procedureFamily) {
1321
- filteredProcedures = filteredProcedures.filter(
1322
- procedure => procedure.family === filters.procedureFamily,
1323
- );
1324
- console.log(
1325
- `[PROCEDURE_SERVICE] Applied family filter, results: ${filteredProcedures.length}`,
1326
- );
1327
- }
1328
-
1329
- // Category filtering
1330
- if (filters.procedureCategory) {
1331
- filteredProcedures = filteredProcedures.filter(
1332
- procedure => procedure.category?.id === filters.procedureCategory,
1333
- );
1334
- console.log(
1335
- `[PROCEDURE_SERVICE] Applied category filter, results: ${filteredProcedures.length}`,
1336
- );
1337
- }
1338
-
1339
- // Subcategory filtering
1340
- if (filters.procedureSubcategory) {
1341
- filteredProcedures = filteredProcedures.filter(
1342
- procedure => procedure.subcategory?.id === filters.procedureSubcategory,
1343
- );
1344
- console.log(
1345
- `[PROCEDURE_SERVICE] Applied subcategory filter, results: ${filteredProcedures.length}`,
1346
- );
1347
- }
1348
-
1349
- // Technology filtering
1350
- if (filters.procedureTechnology) {
1351
- filteredProcedures = filteredProcedures.filter(
1352
- procedure => procedure.technology?.id === filters.procedureTechnology,
1353
- );
1354
- console.log(
1355
- `[PROCEDURE_SERVICE] Applied technology filter, results: ${filteredProcedures.length}`,
1356
- );
1357
- }
1358
-
1359
- // Practitioner filtering
1360
- if (filters.practitionerId) {
1361
- filteredProcedures = filteredProcedures.filter(
1362
- procedure => procedure.practitionerId === filters.practitionerId,
1363
- );
1364
- console.log(
1365
- `[PROCEDURE_SERVICE] Applied practitioner filter, results: ${filteredProcedures.length}`,
1366
- );
1367
- }
1368
-
1369
- // Clinic filtering
1370
- if (filters.clinicId) {
1371
- filteredProcedures = filteredProcedures.filter(
1372
- procedure => procedure.clinicBranchId === filters.clinicId,
1373
- );
1374
- console.log(
1375
- `[PROCEDURE_SERVICE] Applied clinic filter, results: ${filteredProcedures.length}`,
1376
- );
1377
- }
1378
-
1379
- // Geo-radius filter
1380
- if (filters.location && filters.radiusInKm && filters.radiusInKm > 0) {
1381
- const location = filters.location;
1382
- const radiusInKm = filters.radiusInKm;
1383
- filteredProcedures = filteredProcedures.filter(procedure => {
1384
- const clinicLocation = procedure.clinicInfo?.location;
1385
- if (!clinicLocation?.latitude || !clinicLocation?.longitude) {
1386
- return false;
1387
- }
1388
-
1389
- const distance =
1390
- distanceBetween(
1391
- [location.latitude, location.longitude],
1392
- [clinicLocation.latitude, clinicLocation.longitude],
1393
- ) / 1000; // Convert to km
1394
-
1395
- // Attach distance for frontend sorting/display
1396
- (procedure as any).distance = distance;
1397
-
1398
- return distance <= radiusInKm;
1399
- });
1400
- console.log(`[PROCEDURE_SERVICE] Applied geo filter, results: ${filteredProcedures.length}`);
1401
-
1402
- // Sort by distance when geo filtering is applied
1403
- filteredProcedures.sort((a, b) => ((a as any).distance || 0) - ((b as any).distance || 0));
1404
- }
1405
-
1406
- return filteredProcedures as (Procedure & { distance?: number })[];
1407
- }
1408
-
1409
- private handleGeoQuery(filters: any): Promise<{
1410
- procedures: (Procedure & { distance?: number })[];
1411
- lastDoc: any;
1412
- }> {
1413
- console.log('[PROCEDURE_SERVICE] Executing geo query with geohash bounds');
1414
- try {
1415
- const location = filters.location;
1416
- const radiusInKm = filters.radiusInKm;
1417
-
1418
- if (!location || !radiusInKm) {
1419
- return Promise.resolve({ procedures: [], lastDoc: null });
1420
- }
1421
-
1422
- const bounds = geohashQueryBounds([location.latitude, location.longitude], radiusInKm * 1000);
1423
-
1424
- const fetches = bounds.map(b => {
1425
- const constraints: QueryConstraint[] = [
1426
- where('clinicInfo.location.geohash', '>=', b[0]),
1427
- where('clinicInfo.location.geohash', '<=', b[1]),
1428
- where('isActive', '==', filters.isActive !== undefined ? filters.isActive : true),
1429
- ];
1430
- if (filters.practitionerId) {
1431
- constraints.push(where('practitionerId', '==', filters.practitionerId));
1432
- }
1433
- if (filters.clinicId) {
1434
- constraints.push(where('clinicBranchId', '==', filters.clinicId));
1435
- }
1436
- return getDocs(query(collection(this.db, PROCEDURES_COLLECTION), ...constraints));
1437
- });
1438
-
1439
- return Promise.all(fetches)
1440
- .then(snaps => {
1441
- const collected: Procedure[] = [];
1442
- snaps.forEach(snap => {
1443
- snap.docs.forEach(d => collected.push({ ...(d.data() as Procedure), id: d.id }));
1444
- });
1445
-
1446
- // Deduplicate by id
1447
- const uniqueMap = new Map<string, Procedure>();
1448
- for (const p of collected) {
1449
- uniqueMap.set(p.id, p);
1450
- }
1451
- let procedures = Array.from(uniqueMap.values());
1452
-
1453
- // Apply remaining filters including precise distance and sorting
1454
- procedures = this.applyInMemoryFilters(procedures, filters);
1455
-
1456
- // Manual pagination
1457
- const pageSize = filters.pagination || 10;
1458
- let startIndex = 0;
1459
- if (
1460
- filters.lastDoc &&
1461
- typeof filters.lastDoc === 'object' &&
1462
- (filters.lastDoc as any).id
1463
- ) {
1464
- const idx = procedures.findIndex(p => p.id === (filters.lastDoc as any).id);
1465
- if (idx >= 0) startIndex = idx + 1;
1466
- }
1467
- const page = procedures.slice(startIndex, startIndex + pageSize);
1468
- const newLastDoc = page.length === pageSize ? page[page.length - 1] : null;
1469
-
1470
- console.log(
1471
- `[PROCEDURE_SERVICE] Geo query success: ${page.length} (of ${procedures.length}) within ${radiusInKm}km`,
1472
- );
1473
- return { procedures: page, lastDoc: newLastDoc };
1474
- })
1475
- .catch(err => {
1476
- console.error('[PROCEDURE_SERVICE] Geo bounds fetch failed:', err);
1477
- return { procedures: [], lastDoc: null };
1478
- });
1479
- } catch (error) {
1480
- console.error('[PROCEDURE_SERVICE] Geo query failed:', error);
1481
- return Promise.resolve({ procedures: [], lastDoc: null });
1482
- }
1483
- }
1484
-
1485
- /**
1486
- * Creates a consultation procedure without requiring a product
1487
- * This is a special method for consultation procedures that don't use products
1488
- * @param data - The data for creating a consultation procedure (without productId)
1489
- * @returns The created procedure
1490
- */
1491
- async createConsultationProcedure(
1492
- data: Omit<CreateProcedureData, 'productId'>,
1493
- ): Promise<Procedure> {
1494
- // Generate procedure ID first so we can use it for media uploads
1495
- const procedureId = this.generateId();
1496
-
1497
- // Get references to related entities (Category, Subcategory, Technology)
1498
- // For consultation, we don't need a product
1499
- const [category, subcategory, technology] = await Promise.all([
1500
- this.categoryService.getById(data.categoryId),
1501
- this.subcategoryService.getById(data.categoryId, data.subcategoryId),
1502
- this.technologyService.getById(data.technologyId),
1503
- ]);
1504
-
1505
- if (!category || !subcategory || !technology) {
1506
- throw new Error('One or more required base entities not found');
1507
- }
1508
-
1509
- // Get clinic and practitioner information for aggregation
1510
- const clinicRef = doc(this.db, CLINICS_COLLECTION, data.clinicBranchId);
1511
- const clinicSnapshot = await getDoc(clinicRef);
1512
- if (!clinicSnapshot.exists()) {
1513
- throw new Error(`Clinic with ID ${data.clinicBranchId} not found`);
1514
- }
1515
- const clinic = clinicSnapshot.data() as Clinic;
1516
-
1517
- const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, data.practitionerId);
1518
- const practitionerSnapshot = await getDoc(practitionerRef);
1519
- if (!practitionerSnapshot.exists()) {
1520
- throw new Error(`Practitioner with ID ${data.practitionerId} not found`);
1521
- }
1522
- const practitioner = practitionerSnapshot.data() as Practitioner;
1523
-
1524
- // Process photos if provided
1525
- let processedPhotos: string[] = [];
1526
- if (data.photos && data.photos.length > 0) {
1527
- processedPhotos = await this.processMediaArray(data.photos, procedureId, 'procedure-photos');
1528
- }
1529
-
1530
- // If no photos provided and technology has a photoTemplate, use it as default photo
1531
- if (processedPhotos.length === 0 && technology.photoTemplate) {
1532
- console.log(`[ProcedureService] Using technology photoTemplate as default photo for consultation: ${technology.photoTemplate}`);
1533
- const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
1534
- if (photoTemplateUrl) {
1535
- processedPhotos.push(photoTemplateUrl);
1536
- } else {
1537
- console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
1538
- }
1539
- }
1540
-
1541
- // Transform productsMetadata from validation format to ProcedureProduct format
1542
- // For consultations, this will return empty array since no products are provided
1543
- const transformedProductsMetadata = await this.transformProductsMetadata(
1544
- data.productsMetadata,
1545
- data.technologyId,
1546
- );
1547
-
1548
- // Create aggregated clinic info for the procedure document
1549
- const clinicInfo = {
1550
- id: clinicSnapshot.id,
1551
- name: clinic.name,
1552
- description: clinic.description || '',
1553
- featuredPhoto:
1554
- clinic.featuredPhotos && clinic.featuredPhotos.length > 0
1555
- ? typeof clinic.featuredPhotos[0] === 'string'
1556
- ? clinic.featuredPhotos[0]
1557
- : ''
1558
- : typeof clinic.coverPhoto === 'string'
1559
- ? clinic.coverPhoto
1560
- : '',
1561
- location: clinic.location,
1562
- contactInfo: clinic.contactInfo,
1563
- };
1564
-
1565
- // Create aggregated doctor info for the procedure document
1566
- const doctorInfo = {
1567
- id: practitionerSnapshot.id,
1568
- name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
1569
- description: practitioner.basicInfo.bio || '',
1570
- photo:
1571
- typeof practitioner.basicInfo.profileImageUrl === 'string'
1572
- ? practitioner.basicInfo.profileImageUrl
1573
- : '',
1574
- rating: practitioner.reviewInfo?.averageRating || 0,
1575
- services: practitioner.procedures || [],
1576
- };
1577
-
1578
- // Create the procedure object
1579
- const { productsMetadata: _, ...dataWithoutProductsMetadata } = data;
1580
- const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
1581
- id: procedureId,
1582
- ...dataWithoutProductsMetadata,
1583
- nameLower: (data as any).nameLower || data.name.toLowerCase(),
1584
- photos: processedPhotos,
1585
- category,
1586
- subcategory,
1587
- technology,
1588
- // No product field for consultations (Firestore doesn't allow undefined, so we omit it entirely)
1589
- productsMetadata: transformedProductsMetadata, // Empty array for consultations
1590
- blockingConditions: technology.blockingConditions,
1591
- contraindications: technology.contraindications || [],
1592
- contraindicationIds: technology.contraindications?.map(c => c.id) || [],
1593
- treatmentBenefits: technology.benefits,
1594
- treatmentBenefitIds: Array.isArray(technology.benefits)
1595
- ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
1596
- : [],
1597
- preRequirements: technology.requirements.pre,
1598
- postRequirements: technology.requirements.post,
1599
- certificationRequirement: technology.certificationRequirement,
1600
- documentationTemplates: technology?.documentationTemplates || [],
1601
- clinicInfo,
1602
- doctorInfo,
1603
- reviewInfo: {
1604
- totalReviews: 0,
1605
- averageRating: 0,
1606
- effectivenessOfTreatment: 0,
1607
- outcomeExplanation: 0,
1608
- painManagement: 0,
1609
- followUpCare: 0,
1610
- valueForMoney: 0,
1611
- recommendationPercentage: 0,
1612
- },
1613
- isActive: true,
1614
- };
1615
-
1616
- // Create the procedure document
1617
- const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
1618
- await setDoc(procedureRef, {
1619
- ...newProcedure,
1620
- createdAt: serverTimestamp(),
1621
- updatedAt: serverTimestamp(),
1622
- });
1623
-
1624
- // Return the created procedure (fetch again to get server timestamps)
1625
- const savedDoc = await getDoc(procedureRef);
1626
- return savedDoc.data() as Procedure;
1627
- }
1628
-
1629
- /**
1630
- * Gets all procedures with minimal info for map display (id, name, clinicId, clinicName, address, latitude, longitude)
1631
- * This is optimized for mobile map usage to reduce payload size.
1632
- * @returns Array of minimal procedure info for map
1633
- */
1634
- async getProceduresForMap(): Promise<
1635
- {
1636
- id: string;
1637
- name: string;
1638
- clinicId: string | undefined;
1639
- clinicName: string | undefined;
1640
- address: string;
1641
- latitude: number | undefined;
1642
- longitude: number | undefined;
1643
- }[]
1644
- > {
1645
- const proceduresRef = collection(this.db, PROCEDURES_COLLECTION);
1646
- const snapshot = await getDocs(proceduresRef);
1647
- const proceduresForMap = snapshot.docs.map(doc => {
1648
- const data = doc.data();
1649
- return {
1650
- id: doc.id,
1651
- name: data.name,
1652
- clinicId: data.clinicInfo?.id,
1653
- clinicName: data.clinicInfo?.name,
1654
- address: data.clinicInfo?.location?.address || '',
1655
- latitude: data.clinicInfo?.location?.latitude,
1656
- longitude: data.clinicInfo?.location?.longitude,
1657
- };
1658
- });
1659
- return proceduresForMap;
1660
- }
1661
-
1662
- /**
1663
- * Gets procedures filtered by clinic and practitioner with optional family filter
1664
- * @param clinicBranchId Clinic branch ID to filter by
1665
- * @param practitionerId Practitioner ID to filter by
1666
- * @param filterByFamily If true, shows only procedures of the same family as the default procedure
1667
- * @param defaultProcedureId Optional default procedure ID to determine the family
1668
- * @returns Array of procedures
1669
- */
1670
- async getProceduresForConsultation(
1671
- clinicBranchId: string,
1672
- practitionerId: string,
1673
- filterByFamily: boolean = true,
1674
- defaultProcedureId?: string
1675
- ): Promise<Procedure[]> {
1676
- let familyToFilter: ProcedureFamily | null = null;
1677
-
1678
- // If family filtering is enabled and we have a default procedure, get its family
1679
- if (filterByFamily && defaultProcedureId) {
1680
- const defaultProcedureRef = doc(this.db, PROCEDURES_COLLECTION, defaultProcedureId);
1681
- const defaultProcedureSnap = await getDoc(defaultProcedureRef);
1682
-
1683
- if (defaultProcedureSnap.exists()) {
1684
- const defaultProcedure = defaultProcedureSnap.data() as Procedure;
1685
- familyToFilter = defaultProcedure.family;
1686
- }
1687
- }
1688
-
1689
- // Build query constraints
1690
- const constraints: QueryConstraint[] = [
1691
- where('clinicBranchId', '==', clinicBranchId),
1692
- where('practitionerId', '==', practitionerId),
1693
- where('isActive', '==', true),
1694
- ];
1695
-
1696
- // Add family filter if applicable
1697
- if (filterByFamily && familyToFilter) {
1698
- constraints.push(where('family', '==', familyToFilter));
1699
- }
1700
-
1701
- // Execute query
1702
- const proceduresQuery = query(
1703
- collection(this.db, PROCEDURES_COLLECTION),
1704
- ...constraints,
1705
- orderBy('name', 'asc')
1706
- );
1707
-
1708
- const querySnapshot = await getDocs(proceduresQuery);
1709
-
1710
- return querySnapshot.docs.map(doc => ({
1711
- id: doc.id,
1712
- ...doc.data(),
1713
- } as Procedure));
1714
- }
1715
- }
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
+ // Process photos if provided
248
+ let processedPhotos: string[] = [];
249
+ if (validatedData.photos && validatedData.photos.length > 0) {
250
+ processedPhotos = await this.processMediaArray(
251
+ validatedData.photos,
252
+ procedureId,
253
+ 'procedure-photos',
254
+ );
255
+ }
256
+
257
+ // If no photos provided and technology has a photoTemplate, use it as default photo
258
+ if (processedPhotos.length === 0 && technology.photoTemplate) {
259
+ console.log(`[ProcedureService] Using technology photoTemplate as default photo: ${technology.photoTemplate}`);
260
+ const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
261
+ if (photoTemplateUrl) {
262
+ processedPhotos.push(photoTemplateUrl);
263
+ } else {
264
+ console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
265
+ }
266
+ }
267
+
268
+ // Transform productsMetadata from validation format to ProcedureProduct format
269
+ const transformedProductsMetadata = await this.transformProductsMetadata(
270
+ validatedData.productsMetadata,
271
+ validatedData.technologyId,
272
+ );
273
+
274
+ // Create aggregated clinic info for the procedure document
275
+ const clinicInfo = {
276
+ id: clinicSnapshot.id,
277
+ name: clinic.name,
278
+ description: clinic.description || '',
279
+ featuredPhoto:
280
+ clinic.featuredPhotos && clinic.featuredPhotos.length > 0
281
+ ? typeof clinic.featuredPhotos[0] === 'string'
282
+ ? clinic.featuredPhotos[0]
283
+ : ''
284
+ : typeof clinic.coverPhoto === 'string'
285
+ ? clinic.coverPhoto
286
+ : '',
287
+ location: clinic.location,
288
+ contactInfo: clinic.contactInfo,
289
+ };
290
+
291
+ // Create aggregated doctor info for the procedure document
292
+ const doctorInfo = {
293
+ id: practitionerSnapshot.id,
294
+ name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
295
+ description: practitioner.basicInfo.bio || '',
296
+ photo:
297
+ typeof practitioner.basicInfo.profileImageUrl === 'string'
298
+ ? practitioner.basicInfo.profileImageUrl
299
+ : '', // Default to empty string if not a processed URL
300
+ rating: practitioner.reviewInfo?.averageRating || 0,
301
+ services: practitioner.procedures || [],
302
+ };
303
+
304
+ // Create the procedure object
305
+ const { productsMetadata: _, productId: __, photos: ___, ...validatedDataWithoutProductsMetadata } = validatedData;
306
+ const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
307
+ id: procedureId,
308
+ ...validatedDataWithoutProductsMetadata,
309
+ // Ensure nameLower is always set even if omitted by client
310
+ nameLower: (validatedData as any).nameLower || validatedData.name.toLowerCase(),
311
+ photos: processedPhotos,
312
+ category, // Embed full objects
313
+ subcategory,
314
+ technology,
315
+ ...(product && { product }), // Only include product field if it exists (Firestore doesn't allow undefined)
316
+ productsMetadata: transformedProductsMetadata, // Use transformed data, not original
317
+ blockingConditions: technology.blockingConditions,
318
+ contraindications: technology.contraindications || [],
319
+ contraindicationIds: technology.contraindications?.map(c => c.id) || [],
320
+ treatmentBenefits: technology.benefits,
321
+ treatmentBenefitIds: Array.isArray(technology.benefits)
322
+ ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
323
+ : [],
324
+ preRequirements: technology.requirements.pre,
325
+ postRequirements: technology.requirements.post,
326
+ certificationRequirement: technology.certificationRequirement,
327
+ documentationTemplates: technology?.documentationTemplates || [],
328
+ clinicInfo, // Embed aggregated info
329
+ doctorInfo, // Embed aggregated info
330
+ reviewInfo: {
331
+ // Default empty reviews
332
+ totalReviews: 0,
333
+ averageRating: 0,
334
+ effectivenessOfTreatment: 0,
335
+ outcomeExplanation: 0,
336
+ painManagement: 0,
337
+ followUpCare: 0,
338
+ valueForMoney: 0,
339
+ recommendationPercentage: 0,
340
+ },
341
+ isActive: true, // Default to active
342
+ };
343
+
344
+ // 🔥 DEBUG: Find undefined fields before writing to Firestore
345
+ console.log('🔥🔥🔥 CREATE PROCEDURE - Processing procedure:', procedureId);
346
+ console.log('🔥🔥🔥 FULL PROCEDURE OBJECT:', JSON.stringify(newProcedure, null, 2));
347
+
348
+ const undefinedFields: string[] = [];
349
+ Object.entries(newProcedure).forEach(([key, value]) => {
350
+ if (value === undefined) {
351
+ undefinedFields.push(key);
352
+ }
353
+ });
354
+ if (undefinedFields.length > 0) {
355
+ console.error('🔥🔥🔥 UNDEFINED FIELDS DETECTED:', undefinedFields);
356
+ throw new Error(`Cannot write procedure with undefined fields: ${undefinedFields.join(', ')}`);
357
+ }
358
+ console.log('🔥🔥🔥 NO UNDEFINED FIELDS - Proceeding with setDoc');
359
+
360
+ // Create the procedure document
361
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
362
+ await setDoc(procedureRef, {
363
+ ...newProcedure,
364
+ createdAt: serverTimestamp(),
365
+ updatedAt: serverTimestamp(),
366
+ });
367
+
368
+ // Return the created procedure (fetch again to get server timestamps)
369
+ const savedDoc = await getDoc(procedureRef);
370
+ return savedDoc.data() as Procedure;
371
+ }
372
+
373
+ /**
374
+ * Creates multiple procedures for a list of practitioners based on common data.
375
+ * This method is optimized for bulk creation to reduce database reads and writes.
376
+ *
377
+ * @param baseData - The base data for the procedures to be created, omitting the practitionerId.
378
+ * @param practitionerIds - An array of practitioner IDs for whom the procedures will be created.
379
+ * @returns A promise that resolves to an array of the newly created procedures.
380
+ */
381
+ async bulkCreateProcedures(
382
+ baseData: Omit<CreateProcedureData, 'practitionerId'>,
383
+ practitionerIds: string[],
384
+ ): Promise<Procedure[]> {
385
+ // 1. Validation
386
+ if (!practitionerIds || practitionerIds.length === 0) {
387
+ throw new Error('Practitioner IDs array cannot be empty.');
388
+ }
389
+
390
+ // Check if this is a product-free procedure
391
+ const isProductFree = !baseData.productId;
392
+
393
+ // Add a dummy practitionerId for the validation schema to pass
394
+ const validationData = { ...baseData, practitionerId: practitionerIds[0] };
395
+ const validatedData = createProcedureSchema.parse(validationData);
396
+
397
+ // 2. Fetch common data once to avoid redundant reads
398
+ const baseEntitiesPromises: Promise<Category | Subcategory | Technology | Product | null>[] = [
399
+ this.categoryService.getById(validatedData.categoryId),
400
+ this.subcategoryService.getById(validatedData.categoryId, validatedData.subcategoryId),
401
+ this.technologyService.getById(validatedData.technologyId),
402
+ ];
403
+
404
+ // Only fetch product if productId is provided
405
+ if (!isProductFree) {
406
+ baseEntitiesPromises.push(
407
+ this.productService.getById(validatedData.technologyId, validatedData.productId!)
408
+ );
409
+ }
410
+
411
+ // Fetch clinic separately to maintain type safety
412
+ const clinicSnapshotPromise = getDoc(doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId));
413
+
414
+ const [baseResults, clinicSnapshot] = await Promise.all([
415
+ Promise.all(baseEntitiesPromises),
416
+ clinicSnapshotPromise
417
+ ]);
418
+
419
+ const category = baseResults[0] as Category | null;
420
+ const subcategory = baseResults[1] as Subcategory | null;
421
+ const technology = baseResults[2] as Technology | null;
422
+ const product = isProductFree ? undefined : ((baseResults[3] as Product | null) || undefined);
423
+
424
+ if (!category || !subcategory || !technology) {
425
+ throw new Error('One or more required base entities not found');
426
+ }
427
+
428
+ // For regular procedures, validate product exists
429
+ if (!isProductFree && !product) {
430
+ throw new Error('Product not found for regular procedure');
431
+ }
432
+
433
+ if (!clinicSnapshot || !clinicSnapshot.exists()) {
434
+ throw new Error(`Clinic with ID ${validatedData.clinicBranchId} not found`);
435
+ }
436
+ const clinic = clinicSnapshot.data() as Clinic;
437
+
438
+ // 3. Handle media uploads once for efficiency
439
+ let processedPhotos: string[] = [];
440
+ if (validatedData.photos && validatedData.photos.length > 0) {
441
+ const batchId = this.generateId(); // Use a single ID for all media in this batch
442
+ processedPhotos = await this.processMediaArray(
443
+ validatedData.photos,
444
+ batchId,
445
+ 'procedure-photos-batch',
446
+ );
447
+ }
448
+
449
+ // If no photos provided and technology has a photoTemplate, use it as default photo
450
+ if (processedPhotos.length === 0 && technology.photoTemplate) {
451
+ console.log(`[ProcedureService] Using technology photoTemplate as default photo for bulk create: ${technology.photoTemplate}`);
452
+ const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
453
+ if (photoTemplateUrl) {
454
+ processedPhotos.push(photoTemplateUrl);
455
+ } else {
456
+ console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
457
+ }
458
+ }
459
+
460
+ // Transform productsMetadata from validation format to ProcedureProduct format
461
+ const transformedProductsMetadata = await this.transformProductsMetadata(
462
+ validatedData.productsMetadata,
463
+ validatedData.technologyId,
464
+ );
465
+
466
+ // 4. Fetch all practitioner data efficiently
467
+ const practitionersMap = new Map<string, Practitioner>();
468
+ // Use 'in' query in chunks of 30, as this is the Firestore limit
469
+ for (let i = 0; i < practitionerIds.length; i += 30) {
470
+ const chunk = practitionerIds.slice(i, i + 30);
471
+ const practitionersQuery = query(
472
+ collection(this.db, PRACTITIONERS_COLLECTION),
473
+ where(documentId(), 'in', chunk),
474
+ );
475
+ const practitionersSnapshot = await getDocs(practitionersQuery);
476
+ practitionersSnapshot.docs.forEach(doc => {
477
+ practitionersMap.set(doc.id, doc.data() as Practitioner);
478
+ });
479
+ }
480
+
481
+ // Verify all practitioners were found
482
+ if (practitionersMap.size !== practitionerIds.length) {
483
+ const foundIds = Array.from(practitionersMap.keys());
484
+ const notFoundIds = practitionerIds.filter(id => !foundIds.includes(id));
485
+ throw new Error(`The following practitioners were not found: ${notFoundIds.join(', ')}`);
486
+ }
487
+
488
+ // 5. Use a Firestore batch for atomic creation
489
+ const batch = writeBatch(this.db);
490
+ const createdProcedureIds: string[] = [];
491
+ const clinicInfo = {
492
+ id: clinicSnapshot.id,
493
+ name: clinic.name,
494
+ description: clinic.description || '',
495
+ featuredPhoto:
496
+ clinic.featuredPhotos && clinic.featuredPhotos.length > 0
497
+ ? typeof clinic.featuredPhotos[0] === 'string'
498
+ ? clinic.featuredPhotos[0]
499
+ : ''
500
+ : typeof clinic.coverPhoto === 'string'
501
+ ? clinic.coverPhoto
502
+ : '',
503
+ location: clinic.location,
504
+ contactInfo: clinic.contactInfo,
505
+ };
506
+
507
+ for (const practitionerId of practitionerIds) {
508
+ const practitioner = practitionersMap.get(practitionerId)!;
509
+
510
+ const doctorInfo = {
511
+ id: practitioner.id,
512
+ name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
513
+ description: practitioner.basicInfo.bio || '',
514
+ photo:
515
+ typeof practitioner.basicInfo.profileImageUrl === 'string'
516
+ ? practitioner.basicInfo.profileImageUrl
517
+ : '',
518
+ rating: practitioner.reviewInfo?.averageRating || 0,
519
+ services: practitioner.procedures || [],
520
+ };
521
+
522
+ const procedureId = this.generateId();
523
+ createdProcedureIds.push(procedureId);
524
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
525
+
526
+ // Construct the new procedure, reusing common data
527
+ const { productsMetadata: _, productId: __, photos: ___, ...validatedDataWithoutProductsMetadata } = validatedData;
528
+ const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
529
+ id: procedureId,
530
+ ...validatedDataWithoutProductsMetadata,
531
+ nameLower: (validatedData as any).nameLower || validatedData.name.toLowerCase(),
532
+ practitionerId: practitionerId, // Override practitionerId with the correct one
533
+ photos: processedPhotos,
534
+ category,
535
+ subcategory,
536
+ technology,
537
+ ...(product && { product }), // Only include product field if it exists (Firestore doesn't allow undefined)
538
+ productsMetadata: transformedProductsMetadata, // Use transformed data, not original
539
+ blockingConditions: technology.blockingConditions,
540
+ contraindications: technology.contraindications || [],
541
+ contraindicationIds: technology.contraindications?.map(c => c.id) || [],
542
+ treatmentBenefits: technology.benefits,
543
+ treatmentBenefitIds: Array.isArray(technology.benefits)
544
+ ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
545
+ : [],
546
+ preRequirements: technology.requirements.pre,
547
+ postRequirements: technology.requirements.post,
548
+ certificationRequirement: technology.certificationRequirement,
549
+ documentationTemplates: technology?.documentationTemplates || [],
550
+ clinicInfo,
551
+ doctorInfo, // Set specific doctor info
552
+ reviewInfo: {
553
+ totalReviews: 0,
554
+ averageRating: 0,
555
+ effectivenessOfTreatment: 0,
556
+ outcomeExplanation: 0,
557
+ painManagement: 0,
558
+ followUpCare: 0,
559
+ valueForMoney: 0,
560
+ recommendationPercentage: 0,
561
+ },
562
+ isActive: true,
563
+ };
564
+
565
+ // 🔥 DEBUG: Find undefined fields before writing to Firestore
566
+ console.log('🔥🔥🔥 BULK CREATE - Processing procedure:', procedureId, 'for practitioner:', practitionerId);
567
+ console.log('🔥🔥🔥 FULL PROCEDURE OBJECT:', JSON.stringify(newProcedure, null, 2));
568
+
569
+ const undefinedFields: string[] = [];
570
+ Object.entries(newProcedure).forEach(([key, value]) => {
571
+ if (value === undefined) {
572
+ undefinedFields.push(key);
573
+ }
574
+ });
575
+ if (undefinedFields.length > 0) {
576
+ console.error('🔥🔥🔥 UNDEFINED FIELDS DETECTED:', undefinedFields);
577
+ throw new Error(`Cannot write procedure with undefined fields: ${undefinedFields.join(', ')}`);
578
+ }
579
+ console.log('🔥🔥🔥 NO UNDEFINED FIELDS - Proceeding with batch.set');
580
+
581
+ batch.set(procedureRef, {
582
+ ...newProcedure,
583
+ createdAt: serverTimestamp(),
584
+ updatedAt: serverTimestamp(),
585
+ });
586
+ }
587
+
588
+ // 6. Commit the atomic batch write
589
+ await batch.commit();
590
+
591
+ // 7. Fetch and return the newly created procedures
592
+ const fetchedProcedures: Procedure[] = [];
593
+ for (let i = 0; i < createdProcedureIds.length; i += 30) {
594
+ const chunk = createdProcedureIds.slice(i, i + 30);
595
+ const q = query(collection(this.db, PROCEDURES_COLLECTION), where(documentId(), 'in', chunk));
596
+ const snapshot = await getDocs(q);
597
+ snapshot.forEach(doc => {
598
+ fetchedProcedures.push(doc.data() as Procedure);
599
+ });
600
+ }
601
+
602
+ return fetchedProcedures;
603
+ }
604
+
605
+ /**
606
+ * Gets a procedure by ID
607
+ * @param id - The ID of the procedure to get
608
+ * @returns The procedure if found, null otherwise
609
+ */
610
+ async getProcedure(id: string): Promise<Procedure | null> {
611
+ const docRef = doc(this.db, PROCEDURES_COLLECTION, id);
612
+ const docSnap = await getDoc(docRef);
613
+
614
+ if (!docSnap.exists()) {
615
+ return null;
616
+ }
617
+
618
+ return docSnap.data() as Procedure;
619
+ }
620
+
621
+ /**
622
+ * Gets all procedures for a clinic branch
623
+ * @param clinicBranchId - The ID of the clinic branch
624
+ * @returns List of procedures
625
+ */
626
+ async getProceduresByClinicBranch(clinicBranchId: string): Promise<Procedure[]> {
627
+ const q = query(
628
+ collection(this.db, PROCEDURES_COLLECTION),
629
+ where('clinicBranchId', '==', clinicBranchId),
630
+ where('isActive', '==', true),
631
+ );
632
+ const snapshot = await getDocs(q);
633
+ return snapshot.docs.map(doc => doc.data() as Procedure);
634
+ }
635
+
636
+ /**
637
+ * Gets all procedures for a practitioner
638
+ * @param practitionerId - The ID of the practitioner
639
+ * @returns List of procedures
640
+ */
641
+ async getProceduresByPractitioner(practitionerId: string): Promise<Procedure[]> {
642
+ const q = query(
643
+ collection(this.db, PROCEDURES_COLLECTION),
644
+ where('practitionerId', '==', practitionerId),
645
+ where('isActive', '==', true),
646
+ );
647
+ const snapshot = await getDocs(q);
648
+ return snapshot.docs.map(doc => doc.data() as Procedure);
649
+ }
650
+
651
+ /**
652
+ * Gets all inactive procedures for a practitioner
653
+ * @param practitionerId - The ID of the practitioner
654
+ * @returns List of inactive procedures
655
+ */
656
+ async getInactiveProceduresByPractitioner(practitionerId: string): Promise<Procedure[]> {
657
+ const q = query(
658
+ collection(this.db, PROCEDURES_COLLECTION),
659
+ where('practitionerId', '==', practitionerId),
660
+ where('isActive', '==', false),
661
+ );
662
+ const snapshot = await getDocs(q);
663
+ return snapshot.docs.map(doc => doc.data() as Procedure);
664
+ }
665
+
666
+ /**
667
+ * Updates a procedure
668
+ * @param id - The ID of the procedure to update
669
+ * @param data - The data to update the procedure with
670
+ * @returns The updated procedure
671
+ */
672
+ async updateProcedure(id: string, data: UpdateProcedureData): Promise<Procedure> {
673
+ const validatedData = updateProcedureSchema.parse(data);
674
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
675
+ const procedureSnapshot = await getDoc(procedureRef);
676
+
677
+ if (!procedureSnapshot.exists()) {
678
+ throw new Error(`Procedure with ID ${id} not found`);
679
+ }
680
+
681
+ const existingProcedure = procedureSnapshot.data() as Procedure;
682
+ let updatedProcedureData: Partial<Procedure> = {};
683
+
684
+ // Copy validated simple fields
685
+ if (validatedData.name !== undefined) updatedProcedureData.name = validatedData.name;
686
+ if (validatedData.description !== undefined)
687
+ updatedProcedureData.description = validatedData.description;
688
+ if (validatedData.price !== undefined) updatedProcedureData.price = validatedData.price;
689
+ if (validatedData.currency !== undefined)
690
+ updatedProcedureData.currency = validatedData.currency;
691
+ if (validatedData.pricingMeasure !== undefined)
692
+ updatedProcedureData.pricingMeasure = validatedData.pricingMeasure;
693
+ if (validatedData.duration !== undefined)
694
+ updatedProcedureData.duration = validatedData.duration;
695
+ if (validatedData.isActive !== undefined)
696
+ updatedProcedureData.isActive = validatedData.isActive;
697
+
698
+ let practitionerChanged = false;
699
+ let clinicChanged = false;
700
+ const oldPractitionerId = existingProcedure.practitionerId;
701
+ const oldClinicId = existingProcedure.clinicBranchId;
702
+ let newPractitioner: Practitioner | null = null;
703
+ let newClinic: Clinic | null = null;
704
+
705
+ // Process photos if provided
706
+ if (validatedData.photos !== undefined) {
707
+ updatedProcedureData.photos = await this.processMediaArray(
708
+ validatedData.photos,
709
+ id,
710
+ 'procedure-photos',
711
+ );
712
+ }
713
+
714
+ // Transform productsMetadata if provided
715
+ if (validatedData.productsMetadata !== undefined) {
716
+ const technologyId = validatedData.technologyId ?? existingProcedure.technology.id;
717
+ if (!technologyId) {
718
+ throw new Error('Technology ID is required for updating products metadata');
719
+ }
720
+ updatedProcedureData.productsMetadata = await this.transformProductsMetadata(
721
+ validatedData.productsMetadata,
722
+ technologyId,
723
+ );
724
+ }
725
+
726
+ // --- Prepare updates and fetch new related data if IDs change ---
727
+
728
+ // Handle Practitioner Change
729
+ if (validatedData.practitionerId && validatedData.practitionerId !== oldPractitionerId) {
730
+ practitionerChanged = true;
731
+ const newPractitionerRef = doc(
732
+ this.db,
733
+ PRACTITIONERS_COLLECTION,
734
+ validatedData.practitionerId,
735
+ );
736
+ const newPractitionerSnap = await getDoc(newPractitionerRef);
737
+ if (!newPractitionerSnap.exists())
738
+ throw new Error(`New Practitioner ${validatedData.practitionerId} not found`);
739
+ newPractitioner = newPractitionerSnap.data() as Practitioner;
740
+ // Update doctorInfo within the procedure document
741
+ updatedProcedureData.doctorInfo = {
742
+ id: newPractitioner.id,
743
+ name: `${newPractitioner.basicInfo.firstName} ${newPractitioner.basicInfo.lastName}`,
744
+ description: newPractitioner.basicInfo.bio || '',
745
+ photo:
746
+ typeof newPractitioner.basicInfo.profileImageUrl === 'string'
747
+ ? newPractitioner.basicInfo.profileImageUrl
748
+ : '', // Default to empty string if not a processed URL
749
+ rating: newPractitioner.reviewInfo?.averageRating || 0,
750
+ services: newPractitioner.procedures || [],
751
+ };
752
+ }
753
+
754
+ // Handle Clinic Change
755
+ if (validatedData.clinicBranchId && validatedData.clinicBranchId !== oldClinicId) {
756
+ clinicChanged = true;
757
+ const newClinicRef = doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId);
758
+ const newClinicSnap = await getDoc(newClinicRef);
759
+ if (!newClinicSnap.exists())
760
+ throw new Error(`New Clinic ${validatedData.clinicBranchId} not found`);
761
+ newClinic = newClinicSnap.data() as Clinic;
762
+ // Update clinicInfo within the procedure document
763
+ updatedProcedureData.clinicInfo = {
764
+ id: newClinic.id,
765
+ name: newClinic.name,
766
+ description: newClinic.description || '',
767
+ featuredPhoto:
768
+ newClinic.featuredPhotos && newClinic.featuredPhotos.length > 0
769
+ ? typeof newClinic.featuredPhotos[0] === 'string'
770
+ ? newClinic.featuredPhotos[0]
771
+ : ''
772
+ : typeof newClinic.coverPhoto === 'string'
773
+ ? newClinic.coverPhoto
774
+ : '',
775
+ location: newClinic.location,
776
+ contactInfo: newClinic.contactInfo,
777
+ };
778
+ }
779
+
780
+ // Handle Category/Subcategory/Technology/Product Changes
781
+ let finalCategoryId = existingProcedure.category.id;
782
+ if (validatedData.name) {
783
+ updatedProcedureData.nameLower = validatedData.name.toLowerCase();
784
+ }
785
+ if (validatedData.categoryId) {
786
+ const category = await this.categoryService.getById(validatedData.categoryId);
787
+ if (!category) throw new Error(`Category ${validatedData.categoryId} not found`);
788
+ updatedProcedureData.category = category;
789
+ finalCategoryId = category.id; // Update finalCategoryId if category changed
790
+ }
791
+
792
+ // Only fetch subcategory if its ID is provided AND we have a valid finalCategoryId
793
+ if (validatedData.subcategoryId && finalCategoryId) {
794
+ const subcategory = await this.subcategoryService.getById(
795
+ finalCategoryId,
796
+ validatedData.subcategoryId,
797
+ );
798
+ if (!subcategory)
799
+ throw new Error(
800
+ `Subcategory ${validatedData.subcategoryId} not found for category ${finalCategoryId}`,
801
+ );
802
+ updatedProcedureData.subcategory = subcategory;
803
+ } else if (validatedData.subcategoryId) {
804
+ console.warn('Attempted to update subcategory without a valid categoryId');
805
+ }
806
+
807
+ let finalTechnologyId = existingProcedure.technology.id;
808
+ if (validatedData.technologyId) {
809
+ const technology = await this.technologyService.getById(validatedData.technologyId);
810
+ if (!technology) throw new Error(`Technology ${validatedData.technologyId} not found`);
811
+ updatedProcedureData.technology = technology;
812
+ finalTechnologyId = technology.id; // Update finalTechnologyId if technology changed
813
+ // Update related fields derived from technology
814
+ updatedProcedureData.blockingConditions = technology.blockingConditions;
815
+ updatedProcedureData.contraindications = technology.contraindications || [];
816
+ updatedProcedureData.contraindicationIds = technology.contraindications?.map(c => c.id) || [];
817
+ updatedProcedureData.treatmentBenefits = technology.benefits;
818
+ updatedProcedureData.treatmentBenefitIds = Array.isArray(technology.benefits)
819
+ ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
820
+ : [];
821
+ updatedProcedureData.preRequirements = technology.requirements.pre;
822
+ updatedProcedureData.postRequirements = technology.requirements.post;
823
+ updatedProcedureData.certificationRequirement = technology.certificationRequirement;
824
+ updatedProcedureData.documentationTemplates = technology.documentationTemplates || [];
825
+ }
826
+
827
+ // Only fetch product if its ID is provided AND we have a valid finalTechnologyId
828
+ if (validatedData.productId && finalTechnologyId) {
829
+ const product = await this.productService.getById(finalTechnologyId, validatedData.productId);
830
+ if (!product)
831
+ throw new Error(
832
+ `Product ${validatedData.productId} not found for technology ${finalTechnologyId}`,
833
+ );
834
+ updatedProcedureData.product = product;
835
+ } else if (validatedData.productId) {
836
+ console.warn('Attempted to update product without a valid technologyId');
837
+ }
838
+
839
+ // Update the procedure document
840
+ await updateDoc(procedureRef, {
841
+ ...updatedProcedureData,
842
+ updatedAt: serverTimestamp(),
843
+ });
844
+
845
+ // Return the updated procedure
846
+ const updatedSnapshot = await getDoc(procedureRef);
847
+ return updatedSnapshot.data() as Procedure;
848
+ }
849
+
850
+ /**
851
+ * Deactivates a procedure (soft delete)
852
+ * @param id - The ID of the procedure to deactivate
853
+ */
854
+ async deactivateProcedure(id: string): Promise<void> {
855
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
856
+ const procedureSnap = await getDoc(procedureRef);
857
+ if (!procedureSnap.exists()) {
858
+ console.warn(`Procedure ${id} not found for deactivation.`);
859
+ return;
860
+ }
861
+
862
+ // Mark procedure as inactive
863
+ await updateDoc(procedureRef, {
864
+ isActive: false,
865
+ updatedAt: serverTimestamp(),
866
+ });
867
+ }
868
+
869
+ /**
870
+ * Deletes a procedure permanently
871
+ * @param id - The ID of the procedure to delete
872
+ * @returns A boolean indicating if the deletion was successful
873
+ */
874
+ async deleteProcedure(id: string): Promise<boolean> {
875
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
876
+ const procedureSnapshot = await getDoc(procedureRef);
877
+
878
+ if (!procedureSnapshot.exists()) {
879
+ // Already deleted or never existed
880
+ return false;
881
+ }
882
+
883
+ // Delete the procedure document
884
+ await deleteDoc(procedureRef);
885
+ return true;
886
+ }
887
+
888
+ /**
889
+ * Gets all procedures that a practitioner is certified to perform
890
+ * @param practitioner - The practitioner's profile
891
+ * @returns Object containing allowed technologies, families, categories, subcategories
892
+ */
893
+ async getAllowedTechnologies(practitioner: Practitioner): Promise<{
894
+ technologies: Technology[];
895
+ families: ProcedureFamily[];
896
+ categories: string[];
897
+ subcategories: string[];
898
+ }> {
899
+ // This logic depends on TechnologyService and remains valid
900
+ const { technologies, families, categories, subcategories } =
901
+ await this.technologyService.getAllowedTechnologies(practitioner);
902
+
903
+ return {
904
+ technologies,
905
+ families,
906
+ categories,
907
+ subcategories,
908
+ };
909
+ }
910
+
911
+ /**
912
+ * Gets all procedures with optional pagination
913
+ *
914
+ * @param pagination - Optional number of procedures per page (0 or undefined returns all)
915
+ * @param lastDoc - Optional last document for pagination (if continuing from a previous page)
916
+ * @returns Object containing procedures array and the last document for pagination
917
+ */
918
+ async getAllProcedures(
919
+ pagination?: number,
920
+ lastDoc?: any,
921
+ ): Promise<{ procedures: Procedure[]; lastDoc: any }> {
922
+ try {
923
+ const proceduresCollection = collection(this.db, PROCEDURES_COLLECTION);
924
+ let proceduresQuery = query(proceduresCollection);
925
+
926
+ // Apply pagination if specified
927
+ if (pagination && pagination > 0) {
928
+ const { limit, startAfter } = await import('firebase/firestore'); // Use dynamic import if needed top-level
929
+
930
+ if (lastDoc) {
931
+ proceduresQuery = query(
932
+ proceduresCollection,
933
+ orderBy('name'), // Use imported orderBy
934
+ startAfter(lastDoc),
935
+ limit(pagination),
936
+ );
937
+ } else {
938
+ proceduresQuery = query(proceduresCollection, orderBy('name'), limit(pagination)); // Use imported orderBy
939
+ }
940
+ } else {
941
+ proceduresQuery = query(proceduresCollection, orderBy('name')); // Use imported orderBy
942
+ }
943
+
944
+ const proceduresSnapshot = await getDocs(proceduresQuery);
945
+ const lastVisible = proceduresSnapshot.docs[proceduresSnapshot.docs.length - 1];
946
+
947
+ const procedures = proceduresSnapshot.docs.map(doc => {
948
+ const data = doc.data() as Procedure;
949
+ return {
950
+ ...data,
951
+ id: doc.id, // Ensure ID is present
952
+ };
953
+ });
954
+
955
+ return {
956
+ procedures,
957
+ lastDoc: lastVisible,
958
+ };
959
+ } catch (error) {
960
+ console.error('[PROCEDURE_SERVICE] Error getting all procedures:', error);
961
+ throw error;
962
+ }
963
+ }
964
+
965
+ /**
966
+ * Searches and filters procedures based on multiple criteria
967
+ *
968
+ * @note Frontend MORA da šalje ceo snapshot (ili barem sva polja po kojima sortiraš, npr. nameLower) kao lastDoc za paginaciju, a ne samo id!
969
+ *
970
+ * @param filters - Various filters to apply
971
+ * @param filters.nameSearch - Optional search text for procedure name
972
+ * @param filters.treatmentBenefitIds - Optional array of treatment benefits to filter by
973
+ * @param filters.procedureFamily - Optional procedure family to filter by
974
+ * @param filters.procedureCategory - Optional procedure category to filter by
975
+ * @param filters.procedureSubcategory - Optional procedure subcategory to filter by
976
+ * @param filters.procedureTechnology - Optional procedure technology to filter by
977
+ * @param filters.location - Optional location for distance-based search
978
+ * @param filters.radiusInKm - Optional radius in kilometers (required if location is provided)
979
+ * @param filters.minPrice - Optional minimum price
980
+ * @param filters.maxPrice - Optional maximum price
981
+ * @param filters.minRating - Optional minimum rating (0-5)
982
+ * @param filters.maxRating - Optional maximum rating (0-5)
983
+ * @param filters.pagination - Optional number of results per page
984
+ * @param filters.lastDoc - Optional last document for pagination
985
+ * @param filters.isActive - Optional filter for active procedures only
986
+ * @returns Filtered procedures and the last document for pagination
987
+ */
988
+ async getProceduresByFilters(filters: {
989
+ nameSearch?: string;
990
+ treatmentBenefits?: string[];
991
+ procedureFamily?: ProcedureFamily;
992
+ procedureCategory?: string;
993
+ procedureSubcategory?: string;
994
+ procedureTechnology?: string;
995
+ location?: { latitude: number; longitude: number };
996
+ radiusInKm?: number;
997
+ minPrice?: number;
998
+ maxPrice?: number;
999
+ minRating?: number;
1000
+ maxRating?: number;
1001
+ pagination?: number;
1002
+ lastDoc?: any;
1003
+ isActive?: boolean;
1004
+ practitionerId?: string;
1005
+ clinicId?: string;
1006
+ }): Promise<{
1007
+ procedures: (Procedure & { distance?: number })[];
1008
+ lastDoc: any;
1009
+ }> {
1010
+ try {
1011
+ console.log('[PROCEDURE_SERVICE] Starting procedure filtering with multiple strategies');
1012
+
1013
+ // Geo query debug i validacija
1014
+ if (filters.location && filters.radiusInKm) {
1015
+ console.log('[PROCEDURE_SERVICE] Executing geo query:', {
1016
+ location: filters.location,
1017
+ radius: filters.radiusInKm,
1018
+ serviceName: 'ProcedureService',
1019
+ });
1020
+
1021
+ // Validacija location podataka
1022
+ if (!filters.location.latitude || !filters.location.longitude) {
1023
+ console.warn('[PROCEDURE_SERVICE] Invalid location data:', filters.location);
1024
+ filters.location = undefined;
1025
+ filters.radiusInKm = undefined;
1026
+ }
1027
+ }
1028
+
1029
+ // Handle geo queries separately (they work differently)
1030
+ const isGeoQuery = filters.location && filters.radiusInKm && filters.radiusInKm > 0;
1031
+ if (isGeoQuery) {
1032
+ return this.handleGeoQuery(filters);
1033
+ }
1034
+
1035
+ // Base constraints (used in all strategies)
1036
+ const getBaseConstraints = () => {
1037
+ const constraints: QueryConstraint[] = [];
1038
+
1039
+ // Active status filter
1040
+ if (filters.isActive !== undefined) {
1041
+ constraints.push(where('isActive', '==', filters.isActive));
1042
+ } else {
1043
+ constraints.push(where('isActive', '==', true));
1044
+ }
1045
+
1046
+ // Filter constraints
1047
+ if (filters.procedureFamily) {
1048
+ constraints.push(where('family', '==', filters.procedureFamily));
1049
+ }
1050
+ if (filters.procedureCategory) {
1051
+ constraints.push(where('category.id', '==', filters.procedureCategory));
1052
+ }
1053
+ if (filters.procedureSubcategory) {
1054
+ constraints.push(where('subcategory.id', '==', filters.procedureSubcategory));
1055
+ }
1056
+ if (filters.procedureTechnology) {
1057
+ constraints.push(where('technology.id', '==', filters.procedureTechnology));
1058
+ }
1059
+ if (filters.practitionerId) {
1060
+ constraints.push(where('practitionerId', '==', filters.practitionerId));
1061
+ }
1062
+ if (filters.clinicId) {
1063
+ constraints.push(where('clinicBranchId', '==', filters.clinicId));
1064
+ }
1065
+ if (filters.minPrice !== undefined) {
1066
+ constraints.push(where('price', '>=', filters.minPrice));
1067
+ }
1068
+ if (filters.maxPrice !== undefined) {
1069
+ constraints.push(where('price', '<=', filters.maxPrice));
1070
+ }
1071
+ if (filters.minRating !== undefined) {
1072
+ constraints.push(where('reviewInfo.averageRating', '>=', filters.minRating));
1073
+ }
1074
+ if (filters.maxRating !== undefined) {
1075
+ constraints.push(where('reviewInfo.averageRating', '<=', filters.maxRating));
1076
+ }
1077
+ if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
1078
+ const benefitIdsToMatch = filters.treatmentBenefits;
1079
+ constraints.push(where('treatmentBenefitIds', 'array-contains-any', benefitIdsToMatch));
1080
+ }
1081
+
1082
+ return constraints;
1083
+ };
1084
+
1085
+ // Strategy 1: Try nameLower search if nameSearch exists
1086
+ if (filters.nameSearch && filters.nameSearch.trim()) {
1087
+ try {
1088
+ console.log('[PROCEDURE_SERVICE] Strategy 1: Trying nameLower search');
1089
+ const searchTerm = filters.nameSearch.trim().toLowerCase();
1090
+ const constraints = getBaseConstraints();
1091
+ constraints.push(where('nameLower', '>=', searchTerm));
1092
+ constraints.push(where('nameLower', '<=', searchTerm + '\uf8ff'));
1093
+ constraints.push(orderBy('nameLower'));
1094
+
1095
+ if (filters.lastDoc) {
1096
+ if (typeof filters.lastDoc.data === 'function') {
1097
+ constraints.push(startAfter(filters.lastDoc));
1098
+ } else if (Array.isArray(filters.lastDoc)) {
1099
+ constraints.push(startAfter(...filters.lastDoc));
1100
+ } else {
1101
+ constraints.push(startAfter(filters.lastDoc));
1102
+ }
1103
+ }
1104
+ constraints.push(limit(filters.pagination || 10));
1105
+
1106
+ const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1107
+ const querySnapshot = await getDocs(q);
1108
+ const procedures = querySnapshot.docs.map(
1109
+ doc => ({ ...doc.data(), id: doc.id } as Procedure),
1110
+ );
1111
+ const lastDoc =
1112
+ querySnapshot.docs.length > 0
1113
+ ? querySnapshot.docs[querySnapshot.docs.length - 1]
1114
+ : null;
1115
+
1116
+ console.log(`[PROCEDURE_SERVICE] Strategy 1 success: ${procedures.length} procedures`);
1117
+
1118
+ // Fix Load More - ako je broj rezultata manji od pagination, nema više
1119
+ if (procedures.length < (filters.pagination || 10)) {
1120
+ return { procedures, lastDoc: null };
1121
+ }
1122
+ return { procedures, lastDoc };
1123
+ } catch (error) {
1124
+ console.log('[PROCEDURE_SERVICE] Strategy 1 failed:', error);
1125
+ }
1126
+ }
1127
+
1128
+ // Strategy 2: Try name field search as fallback
1129
+ if (filters.nameSearch && filters.nameSearch.trim()) {
1130
+ try {
1131
+ console.log('[PROCEDURE_SERVICE] Strategy 2: Trying name field search');
1132
+ const searchTerm = filters.nameSearch.trim().toLowerCase();
1133
+ const constraints = getBaseConstraints();
1134
+ constraints.push(where('name', '>=', searchTerm));
1135
+ constraints.push(where('name', '<=', searchTerm + '\uf8ff'));
1136
+ constraints.push(orderBy('name'));
1137
+
1138
+ if (filters.lastDoc) {
1139
+ if (typeof filters.lastDoc.data === 'function') {
1140
+ constraints.push(startAfter(filters.lastDoc));
1141
+ } else if (Array.isArray(filters.lastDoc)) {
1142
+ constraints.push(startAfter(...filters.lastDoc));
1143
+ } else {
1144
+ constraints.push(startAfter(filters.lastDoc));
1145
+ }
1146
+ }
1147
+ constraints.push(limit(filters.pagination || 10));
1148
+
1149
+ const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1150
+ const querySnapshot = await getDocs(q);
1151
+ const procedures = querySnapshot.docs.map(
1152
+ doc => ({ ...doc.data(), id: doc.id } as Procedure),
1153
+ );
1154
+ const lastDoc =
1155
+ querySnapshot.docs.length > 0
1156
+ ? querySnapshot.docs[querySnapshot.docs.length - 1]
1157
+ : null;
1158
+
1159
+ console.log(`[PROCEDURE_SERVICE] Strategy 2 success: ${procedures.length} procedures`);
1160
+
1161
+ // Fix Load More - ako je broj rezultata manji od pagination, nema više
1162
+ if (procedures.length < (filters.pagination || 10)) {
1163
+ return { procedures, lastDoc: null };
1164
+ }
1165
+ return { procedures, lastDoc };
1166
+ } catch (error) {
1167
+ console.log('[PROCEDURE_SERVICE] Strategy 2 failed:', error);
1168
+ }
1169
+ }
1170
+
1171
+ // Strategy 3: orderBy createdAt with client-side filtering
1172
+ try {
1173
+ console.log(
1174
+ '[PROCEDURE_SERVICE] Strategy 3: Using createdAt orderBy with client-side filtering',
1175
+ );
1176
+ const constraints = getBaseConstraints();
1177
+ constraints.push(orderBy('createdAt', 'desc'));
1178
+
1179
+ if (filters.lastDoc) {
1180
+ if (typeof filters.lastDoc.data === 'function') {
1181
+ constraints.push(startAfter(filters.lastDoc));
1182
+ } else if (Array.isArray(filters.lastDoc)) {
1183
+ constraints.push(startAfter(...filters.lastDoc));
1184
+ } else {
1185
+ constraints.push(startAfter(filters.lastDoc));
1186
+ }
1187
+ }
1188
+ constraints.push(limit(filters.pagination || 10));
1189
+
1190
+ const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1191
+ const querySnapshot = await getDocs(q);
1192
+ let procedures = querySnapshot.docs.map(
1193
+ doc => ({ ...doc.data(), id: doc.id } as Procedure),
1194
+ );
1195
+
1196
+ // Apply all client-side filters using centralized function
1197
+ procedures = this.applyInMemoryFilters(procedures, filters);
1198
+
1199
+ const lastDoc =
1200
+ querySnapshot.docs.length > 0 ? querySnapshot.docs[querySnapshot.docs.length - 1] : null;
1201
+ console.log(`[PROCEDURE_SERVICE] Strategy 3 success: ${procedures.length} procedures`);
1202
+
1203
+ // Fix Load More - ako je broj rezultata manji od pagination, nema više
1204
+ if (procedures.length < (filters.pagination || 10)) {
1205
+ return { procedures, lastDoc: null };
1206
+ }
1207
+ return { procedures, lastDoc };
1208
+ } catch (error) {
1209
+ console.log('[PROCEDURE_SERVICE] Strategy 3 failed:', error);
1210
+ }
1211
+
1212
+ // Strategy 4: Minimal query fallback
1213
+ try {
1214
+ console.log('[PROCEDURE_SERVICE] Strategy 4: Minimal query fallback');
1215
+ const constraints: QueryConstraint[] = [
1216
+ where('isActive', '==', filters.isActive !== undefined ? filters.isActive : true),
1217
+ orderBy('createdAt', 'desc'),
1218
+ ];
1219
+ if (filters.practitionerId) {
1220
+ constraints.push(where('practitionerId', '==', filters.practitionerId));
1221
+ }
1222
+ if (filters.clinicId) {
1223
+ constraints.push(where('clinicBranchId', '==', filters.clinicId));
1224
+ }
1225
+ constraints.push(limit(filters.pagination || 10));
1226
+
1227
+ const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
1228
+ const querySnapshot = await getDocs(q);
1229
+ let procedures = querySnapshot.docs.map(
1230
+ doc => ({ ...doc.data(), id: doc.id } as Procedure),
1231
+ );
1232
+
1233
+ // Apply all client-side filters using centralized function
1234
+ procedures = this.applyInMemoryFilters(procedures, filters);
1235
+
1236
+ const lastDoc =
1237
+ querySnapshot.docs.length > 0 ? querySnapshot.docs[querySnapshot.docs.length - 1] : null;
1238
+ console.log(`[PROCEDURE_SERVICE] Strategy 4 success: ${procedures.length} procedures`);
1239
+
1240
+ // Fix Load More - ako je broj rezultata manji od pagination, nema više
1241
+ if (procedures.length < (filters.pagination || 10)) {
1242
+ return { procedures, lastDoc: null };
1243
+ }
1244
+ return { procedures, lastDoc };
1245
+ } catch (error) {
1246
+ console.log('[PROCEDURE_SERVICE] Strategy 4 failed:', error);
1247
+ }
1248
+
1249
+ // All strategies failed
1250
+ console.log('[PROCEDURE_SERVICE] All strategies failed, returning empty result');
1251
+ return { procedures: [], lastDoc: null };
1252
+ } catch (error) {
1253
+ console.error('[PROCEDURE_SERVICE] Error filtering procedures:', error);
1254
+ return { procedures: [], lastDoc: null };
1255
+ }
1256
+ }
1257
+
1258
+ /**
1259
+ * Applies in-memory filters to procedures array
1260
+ * Used when Firestore queries fail or for complex filtering
1261
+ */
1262
+ private applyInMemoryFilters(
1263
+ procedures: Procedure[],
1264
+ filters: any,
1265
+ ): (Procedure & { distance?: number })[] {
1266
+ let filteredProcedures = [...procedures]; // Create copy to avoid mutating original
1267
+
1268
+ // Name search filter
1269
+ if (filters.nameSearch && filters.nameSearch.trim()) {
1270
+ const searchTerm = filters.nameSearch.trim().toLowerCase();
1271
+ filteredProcedures = filteredProcedures.filter(procedure => {
1272
+ const name = (procedure.name || '').toLowerCase();
1273
+ const nameLower = procedure.nameLower || '';
1274
+ return name.includes(searchTerm) || nameLower.includes(searchTerm);
1275
+ });
1276
+ console.log(`[PROCEDURE_SERVICE] Applied name filter, results: ${filteredProcedures.length}`);
1277
+ }
1278
+
1279
+ // Price filtering
1280
+ if (filters.minPrice !== undefined || filters.maxPrice !== undefined) {
1281
+ filteredProcedures = filteredProcedures.filter(procedure => {
1282
+ const price = procedure.price || 0;
1283
+ if (filters.minPrice !== undefined && price < filters.minPrice) return false;
1284
+ if (filters.maxPrice !== undefined && price > filters.maxPrice) return false;
1285
+ return true;
1286
+ });
1287
+ console.log(
1288
+ `[PROCEDURE_SERVICE] Applied price filter (${filters.minPrice}-${filters.maxPrice}), results: ${filteredProcedures.length}`,
1289
+ );
1290
+ }
1291
+
1292
+ // Rating filtering
1293
+ if (filters.minRating !== undefined || filters.maxRating !== undefined) {
1294
+ filteredProcedures = filteredProcedures.filter(procedure => {
1295
+ const rating = procedure.reviewInfo?.averageRating || 0;
1296
+ if (filters.minRating !== undefined && rating < filters.minRating) return false;
1297
+ if (filters.maxRating !== undefined && rating > filters.maxRating) return false;
1298
+ return true;
1299
+ });
1300
+ console.log(
1301
+ `[PROCEDURE_SERVICE] Applied rating filter, results: ${filteredProcedures.length}`,
1302
+ );
1303
+ }
1304
+
1305
+ // Treatment benefits filtering
1306
+ if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
1307
+ const benefitIdsToMatch = filters.treatmentBenefits;
1308
+ filteredProcedures = filteredProcedures.filter(procedure => {
1309
+ const procedureBenefitIds = procedure.treatmentBenefitIds || [];
1310
+ return benefitIdsToMatch.some((benefitId: string) =>
1311
+ procedureBenefitIds.includes(benefitId),
1312
+ );
1313
+ });
1314
+ console.log(
1315
+ `[PROCEDURE_SERVICE] Applied benefits filter, results: ${filteredProcedures.length}`,
1316
+ );
1317
+ }
1318
+
1319
+ // Procedure family filtering
1320
+ if (filters.procedureFamily) {
1321
+ filteredProcedures = filteredProcedures.filter(
1322
+ procedure => procedure.family === filters.procedureFamily,
1323
+ );
1324
+ console.log(
1325
+ `[PROCEDURE_SERVICE] Applied family filter, results: ${filteredProcedures.length}`,
1326
+ );
1327
+ }
1328
+
1329
+ // Category filtering
1330
+ if (filters.procedureCategory) {
1331
+ filteredProcedures = filteredProcedures.filter(
1332
+ procedure => procedure.category?.id === filters.procedureCategory,
1333
+ );
1334
+ console.log(
1335
+ `[PROCEDURE_SERVICE] Applied category filter, results: ${filteredProcedures.length}`,
1336
+ );
1337
+ }
1338
+
1339
+ // Subcategory filtering
1340
+ if (filters.procedureSubcategory) {
1341
+ filteredProcedures = filteredProcedures.filter(
1342
+ procedure => procedure.subcategory?.id === filters.procedureSubcategory,
1343
+ );
1344
+ console.log(
1345
+ `[PROCEDURE_SERVICE] Applied subcategory filter, results: ${filteredProcedures.length}`,
1346
+ );
1347
+ }
1348
+
1349
+ // Technology filtering
1350
+ if (filters.procedureTechnology) {
1351
+ filteredProcedures = filteredProcedures.filter(
1352
+ procedure => procedure.technology?.id === filters.procedureTechnology,
1353
+ );
1354
+ console.log(
1355
+ `[PROCEDURE_SERVICE] Applied technology filter, results: ${filteredProcedures.length}`,
1356
+ );
1357
+ }
1358
+
1359
+ // Practitioner filtering
1360
+ if (filters.practitionerId) {
1361
+ filteredProcedures = filteredProcedures.filter(
1362
+ procedure => procedure.practitionerId === filters.practitionerId,
1363
+ );
1364
+ console.log(
1365
+ `[PROCEDURE_SERVICE] Applied practitioner filter, results: ${filteredProcedures.length}`,
1366
+ );
1367
+ }
1368
+
1369
+ // Clinic filtering
1370
+ if (filters.clinicId) {
1371
+ filteredProcedures = filteredProcedures.filter(
1372
+ procedure => procedure.clinicBranchId === filters.clinicId,
1373
+ );
1374
+ console.log(
1375
+ `[PROCEDURE_SERVICE] Applied clinic filter, results: ${filteredProcedures.length}`,
1376
+ );
1377
+ }
1378
+
1379
+ // Geo-radius filter
1380
+ if (filters.location && filters.radiusInKm && filters.radiusInKm > 0) {
1381
+ const location = filters.location;
1382
+ const radiusInKm = filters.radiusInKm;
1383
+ filteredProcedures = filteredProcedures.filter(procedure => {
1384
+ const clinicLocation = procedure.clinicInfo?.location;
1385
+ if (!clinicLocation?.latitude || !clinicLocation?.longitude) {
1386
+ return false;
1387
+ }
1388
+
1389
+ const distance =
1390
+ distanceBetween(
1391
+ [location.latitude, location.longitude],
1392
+ [clinicLocation.latitude, clinicLocation.longitude],
1393
+ ) / 1000; // Convert to km
1394
+
1395
+ // Attach distance for frontend sorting/display
1396
+ (procedure as any).distance = distance;
1397
+
1398
+ return distance <= radiusInKm;
1399
+ });
1400
+ console.log(`[PROCEDURE_SERVICE] Applied geo filter, results: ${filteredProcedures.length}`);
1401
+
1402
+ // Sort by distance when geo filtering is applied
1403
+ filteredProcedures.sort((a, b) => ((a as any).distance || 0) - ((b as any).distance || 0));
1404
+ }
1405
+
1406
+ return filteredProcedures as (Procedure & { distance?: number })[];
1407
+ }
1408
+
1409
+ private handleGeoQuery(filters: any): Promise<{
1410
+ procedures: (Procedure & { distance?: number })[];
1411
+ lastDoc: any;
1412
+ }> {
1413
+ console.log('[PROCEDURE_SERVICE] Executing geo query with geohash bounds');
1414
+ try {
1415
+ const location = filters.location;
1416
+ const radiusInKm = filters.radiusInKm;
1417
+
1418
+ if (!location || !radiusInKm) {
1419
+ return Promise.resolve({ procedures: [], lastDoc: null });
1420
+ }
1421
+
1422
+ const bounds = geohashQueryBounds([location.latitude, location.longitude], radiusInKm * 1000);
1423
+
1424
+ const fetches = bounds.map(b => {
1425
+ const constraints: QueryConstraint[] = [
1426
+ where('clinicInfo.location.geohash', '>=', b[0]),
1427
+ where('clinicInfo.location.geohash', '<=', b[1]),
1428
+ where('isActive', '==', filters.isActive !== undefined ? filters.isActive : true),
1429
+ ];
1430
+ if (filters.practitionerId) {
1431
+ constraints.push(where('practitionerId', '==', filters.practitionerId));
1432
+ }
1433
+ if (filters.clinicId) {
1434
+ constraints.push(where('clinicBranchId', '==', filters.clinicId));
1435
+ }
1436
+ return getDocs(query(collection(this.db, PROCEDURES_COLLECTION), ...constraints));
1437
+ });
1438
+
1439
+ return Promise.all(fetches)
1440
+ .then(snaps => {
1441
+ const collected: Procedure[] = [];
1442
+ snaps.forEach(snap => {
1443
+ snap.docs.forEach(d => collected.push({ ...(d.data() as Procedure), id: d.id }));
1444
+ });
1445
+
1446
+ // Deduplicate by id
1447
+ const uniqueMap = new Map<string, Procedure>();
1448
+ for (const p of collected) {
1449
+ uniqueMap.set(p.id, p);
1450
+ }
1451
+ let procedures = Array.from(uniqueMap.values());
1452
+
1453
+ // Apply remaining filters including precise distance and sorting
1454
+ procedures = this.applyInMemoryFilters(procedures, filters);
1455
+
1456
+ // Manual pagination
1457
+ const pageSize = filters.pagination || 10;
1458
+ let startIndex = 0;
1459
+ if (
1460
+ filters.lastDoc &&
1461
+ typeof filters.lastDoc === 'object' &&
1462
+ (filters.lastDoc as any).id
1463
+ ) {
1464
+ const idx = procedures.findIndex(p => p.id === (filters.lastDoc as any).id);
1465
+ if (idx >= 0) startIndex = idx + 1;
1466
+ }
1467
+ const page = procedures.slice(startIndex, startIndex + pageSize);
1468
+ const newLastDoc = page.length === pageSize ? page[page.length - 1] : null;
1469
+
1470
+ console.log(
1471
+ `[PROCEDURE_SERVICE] Geo query success: ${page.length} (of ${procedures.length}) within ${radiusInKm}km`,
1472
+ );
1473
+ return { procedures: page, lastDoc: newLastDoc };
1474
+ })
1475
+ .catch(err => {
1476
+ console.error('[PROCEDURE_SERVICE] Geo bounds fetch failed:', err);
1477
+ return { procedures: [], lastDoc: null };
1478
+ });
1479
+ } catch (error) {
1480
+ console.error('[PROCEDURE_SERVICE] Geo query failed:', error);
1481
+ return Promise.resolve({ procedures: [], lastDoc: null });
1482
+ }
1483
+ }
1484
+
1485
+ /**
1486
+ * Creates a consultation procedure without requiring a product
1487
+ * This is a special method for consultation procedures that don't use products
1488
+ * @param data - The data for creating a consultation procedure (without productId)
1489
+ * @returns The created procedure
1490
+ */
1491
+ async createConsultationProcedure(
1492
+ data: Omit<CreateProcedureData, 'productId'>,
1493
+ ): Promise<Procedure> {
1494
+ // Generate procedure ID first so we can use it for media uploads
1495
+ const procedureId = this.generateId();
1496
+
1497
+ // Get references to related entities (Category, Subcategory, Technology)
1498
+ // For consultation, we don't need a product
1499
+ const [category, subcategory, technology] = await Promise.all([
1500
+ this.categoryService.getById(data.categoryId),
1501
+ this.subcategoryService.getById(data.categoryId, data.subcategoryId),
1502
+ this.technologyService.getById(data.technologyId),
1503
+ ]);
1504
+
1505
+ if (!category || !subcategory || !technology) {
1506
+ throw new Error('One or more required base entities not found');
1507
+ }
1508
+
1509
+ // Get clinic and practitioner information for aggregation
1510
+ const clinicRef = doc(this.db, CLINICS_COLLECTION, data.clinicBranchId);
1511
+ const clinicSnapshot = await getDoc(clinicRef);
1512
+ if (!clinicSnapshot.exists()) {
1513
+ throw new Error(`Clinic with ID ${data.clinicBranchId} not found`);
1514
+ }
1515
+ const clinic = clinicSnapshot.data() as Clinic;
1516
+
1517
+ const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, data.practitionerId);
1518
+ const practitionerSnapshot = await getDoc(practitionerRef);
1519
+ if (!practitionerSnapshot.exists()) {
1520
+ throw new Error(`Practitioner with ID ${data.practitionerId} not found`);
1521
+ }
1522
+ const practitioner = practitionerSnapshot.data() as Practitioner;
1523
+
1524
+ // Process photos if provided
1525
+ let processedPhotos: string[] = [];
1526
+ if (data.photos && data.photos.length > 0) {
1527
+ processedPhotos = await this.processMediaArray(data.photos, procedureId, 'procedure-photos');
1528
+ }
1529
+
1530
+ // If no photos provided and technology has a photoTemplate, use it as default photo
1531
+ if (processedPhotos.length === 0 && technology.photoTemplate) {
1532
+ console.log(`[ProcedureService] Using technology photoTemplate as default photo for consultation: ${technology.photoTemplate}`);
1533
+ const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
1534
+ if (photoTemplateUrl) {
1535
+ processedPhotos.push(photoTemplateUrl);
1536
+ } else {
1537
+ console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
1538
+ }
1539
+ }
1540
+
1541
+ // Transform productsMetadata from validation format to ProcedureProduct format
1542
+ // For consultations, this will return empty array since no products are provided
1543
+ const transformedProductsMetadata = await this.transformProductsMetadata(
1544
+ data.productsMetadata,
1545
+ data.technologyId,
1546
+ );
1547
+
1548
+ // Create aggregated clinic info for the procedure document
1549
+ const clinicInfo = {
1550
+ id: clinicSnapshot.id,
1551
+ name: clinic.name,
1552
+ description: clinic.description || '',
1553
+ featuredPhoto:
1554
+ clinic.featuredPhotos && clinic.featuredPhotos.length > 0
1555
+ ? typeof clinic.featuredPhotos[0] === 'string'
1556
+ ? clinic.featuredPhotos[0]
1557
+ : ''
1558
+ : typeof clinic.coverPhoto === 'string'
1559
+ ? clinic.coverPhoto
1560
+ : '',
1561
+ location: clinic.location,
1562
+ contactInfo: clinic.contactInfo,
1563
+ };
1564
+
1565
+ // Create aggregated doctor info for the procedure document
1566
+ const doctorInfo = {
1567
+ id: practitionerSnapshot.id,
1568
+ name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
1569
+ description: practitioner.basicInfo.bio || '',
1570
+ photo:
1571
+ typeof practitioner.basicInfo.profileImageUrl === 'string'
1572
+ ? practitioner.basicInfo.profileImageUrl
1573
+ : '',
1574
+ rating: practitioner.reviewInfo?.averageRating || 0,
1575
+ services: practitioner.procedures || [],
1576
+ };
1577
+
1578
+ // Create the procedure object
1579
+ const { productsMetadata: _, ...dataWithoutProductsMetadata } = data;
1580
+ const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
1581
+ id: procedureId,
1582
+ ...dataWithoutProductsMetadata,
1583
+ nameLower: (data as any).nameLower || data.name.toLowerCase(),
1584
+ photos: processedPhotos,
1585
+ category,
1586
+ subcategory,
1587
+ technology,
1588
+ // No product field for consultations (Firestore doesn't allow undefined, so we omit it entirely)
1589
+ productsMetadata: transformedProductsMetadata, // Empty array for consultations
1590
+ blockingConditions: technology.blockingConditions,
1591
+ contraindications: technology.contraindications || [],
1592
+ contraindicationIds: technology.contraindications?.map(c => c.id) || [],
1593
+ treatmentBenefits: technology.benefits,
1594
+ treatmentBenefitIds: Array.isArray(technology.benefits)
1595
+ ? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
1596
+ : [],
1597
+ preRequirements: technology.requirements.pre,
1598
+ postRequirements: technology.requirements.post,
1599
+ certificationRequirement: technology.certificationRequirement,
1600
+ documentationTemplates: technology?.documentationTemplates || [],
1601
+ clinicInfo,
1602
+ doctorInfo,
1603
+ reviewInfo: {
1604
+ totalReviews: 0,
1605
+ averageRating: 0,
1606
+ effectivenessOfTreatment: 0,
1607
+ outcomeExplanation: 0,
1608
+ painManagement: 0,
1609
+ followUpCare: 0,
1610
+ valueForMoney: 0,
1611
+ recommendationPercentage: 0,
1612
+ },
1613
+ isActive: true,
1614
+ };
1615
+
1616
+ // Create the procedure document
1617
+ const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
1618
+ await setDoc(procedureRef, {
1619
+ ...newProcedure,
1620
+ createdAt: serverTimestamp(),
1621
+ updatedAt: serverTimestamp(),
1622
+ });
1623
+
1624
+ // Return the created procedure (fetch again to get server timestamps)
1625
+ const savedDoc = await getDoc(procedureRef);
1626
+ return savedDoc.data() as Procedure;
1627
+ }
1628
+
1629
+ /**
1630
+ * Gets all procedures with minimal info for map display (id, name, clinicId, clinicName, address, latitude, longitude)
1631
+ * This is optimized for mobile map usage to reduce payload size.
1632
+ * @returns Array of minimal procedure info for map
1633
+ */
1634
+ async getProceduresForMap(): Promise<
1635
+ {
1636
+ id: string;
1637
+ name: string;
1638
+ clinicId: string | undefined;
1639
+ clinicName: string | undefined;
1640
+ address: string;
1641
+ latitude: number | undefined;
1642
+ longitude: number | undefined;
1643
+ }[]
1644
+ > {
1645
+ const proceduresRef = collection(this.db, PROCEDURES_COLLECTION);
1646
+ const snapshot = await getDocs(proceduresRef);
1647
+ const proceduresForMap = snapshot.docs.map(doc => {
1648
+ const data = doc.data();
1649
+ return {
1650
+ id: doc.id,
1651
+ name: data.name,
1652
+ clinicId: data.clinicInfo?.id,
1653
+ clinicName: data.clinicInfo?.name,
1654
+ address: data.clinicInfo?.location?.address || '',
1655
+ latitude: data.clinicInfo?.location?.latitude,
1656
+ longitude: data.clinicInfo?.location?.longitude,
1657
+ };
1658
+ });
1659
+ return proceduresForMap;
1660
+ }
1661
+
1662
+ /**
1663
+ * Gets procedures filtered by clinic and practitioner with optional family filter
1664
+ * @param clinicBranchId Clinic branch ID to filter by
1665
+ * @param practitionerId Practitioner ID to filter by
1666
+ * @param filterByFamily If true, shows only procedures of the same family as the default procedure
1667
+ * @param defaultProcedureId Optional default procedure ID to determine the family
1668
+ * @returns Array of procedures
1669
+ */
1670
+ async getProceduresForConsultation(
1671
+ clinicBranchId: string,
1672
+ practitionerId: string,
1673
+ filterByFamily: boolean = true,
1674
+ defaultProcedureId?: string
1675
+ ): Promise<Procedure[]> {
1676
+ let familyToFilter: ProcedureFamily | null = null;
1677
+
1678
+ // If family filtering is enabled and we have a default procedure, get its family
1679
+ if (filterByFamily && defaultProcedureId) {
1680
+ const defaultProcedureRef = doc(this.db, PROCEDURES_COLLECTION, defaultProcedureId);
1681
+ const defaultProcedureSnap = await getDoc(defaultProcedureRef);
1682
+
1683
+ if (defaultProcedureSnap.exists()) {
1684
+ const defaultProcedure = defaultProcedureSnap.data() as Procedure;
1685
+ familyToFilter = defaultProcedure.family;
1686
+ }
1687
+ }
1688
+
1689
+ // Build query constraints
1690
+ const constraints: QueryConstraint[] = [
1691
+ where('clinicBranchId', '==', clinicBranchId),
1692
+ where('practitionerId', '==', practitionerId),
1693
+ where('isActive', '==', true),
1694
+ ];
1695
+
1696
+ // Add family filter if applicable
1697
+ if (filterByFamily && familyToFilter) {
1698
+ constraints.push(where('family', '==', familyToFilter));
1699
+ }
1700
+
1701
+ // Execute query
1702
+ const proceduresQuery = query(
1703
+ collection(this.db, PROCEDURES_COLLECTION),
1704
+ ...constraints,
1705
+ orderBy('name', 'asc')
1706
+ );
1707
+
1708
+ const querySnapshot = await getDocs(proceduresQuery);
1709
+
1710
+ return querySnapshot.docs.map(doc => ({
1711
+ id: doc.id,
1712
+ ...doc.data(),
1713
+ } as Procedure));
1714
+ }
1715
+ }