@blackcode_sa/metaestetics-api 1.12.61 → 1.12.62

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