@blackcode_sa/metaestetics-api 1.12.58 → 1.12.61

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 (267) hide show
  1. package/dist/admin/index.d.mts +36 -4
  2. package/dist/admin/index.d.ts +36 -4
  3. package/dist/admin/index.js +156 -28
  4. package/dist/admin/index.mjs +156 -28
  5. package/dist/index.d.mts +9 -1
  6. package/dist/index.d.ts +9 -1
  7. package/package.json +119 -119
  8. package/src/__mocks__/firstore.ts +10 -10
  9. package/src/admin/aggregation/README.md +79 -79
  10. package/src/admin/aggregation/appointment/README.md +128 -128
  11. package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +1844 -1689
  12. package/src/admin/aggregation/appointment/index.ts +1 -1
  13. package/src/admin/aggregation/clinic/README.md +52 -52
  14. package/src/admin/aggregation/clinic/clinic.aggregation.service.ts +703 -703
  15. package/src/admin/aggregation/clinic/index.ts +1 -1
  16. package/src/admin/aggregation/forms/README.md +13 -13
  17. package/src/admin/aggregation/forms/filled-forms.aggregation.service.ts +322 -322
  18. package/src/admin/aggregation/forms/index.ts +1 -1
  19. package/src/admin/aggregation/index.ts +8 -8
  20. package/src/admin/aggregation/patient/README.md +27 -27
  21. package/src/admin/aggregation/patient/index.ts +1 -1
  22. package/src/admin/aggregation/patient/patient.aggregation.service.ts +141 -141
  23. package/src/admin/aggregation/practitioner/README.md +42 -42
  24. package/src/admin/aggregation/practitioner/index.ts +1 -1
  25. package/src/admin/aggregation/practitioner/practitioner.aggregation.service.ts +433 -433
  26. package/src/admin/aggregation/practitioner-invite/index.ts +1 -1
  27. package/src/admin/aggregation/practitioner-invite/practitioner-invite.aggregation.service.ts +961 -961
  28. package/src/admin/aggregation/procedure/README.md +43 -43
  29. package/src/admin/aggregation/procedure/index.ts +1 -1
  30. package/src/admin/aggregation/procedure/procedure.aggregation.service.ts +702 -702
  31. package/src/admin/aggregation/reviews/index.ts +1 -1
  32. package/src/admin/aggregation/reviews/reviews.aggregation.service.ts +641 -641
  33. package/src/admin/booking/README.md +125 -125
  34. package/src/admin/booking/booking.admin.ts +1037 -1037
  35. package/src/admin/booking/booking.calculator.ts +712 -699
  36. package/src/admin/booking/booking.types.ts +59 -59
  37. package/src/admin/booking/index.ts +3 -3
  38. package/src/admin/booking/timezones-problem.md +185 -185
  39. package/src/admin/calendar/README.md +7 -7
  40. package/src/admin/calendar/calendar.admin.service.ts +345 -345
  41. package/src/admin/calendar/index.ts +1 -1
  42. package/src/admin/documentation-templates/document-manager.admin.ts +260 -260
  43. package/src/admin/documentation-templates/index.ts +1 -1
  44. package/src/admin/free-consultation/free-consultation-utils.admin.ts +148 -148
  45. package/src/admin/free-consultation/index.ts +1 -1
  46. package/src/admin/index.ts +75 -75
  47. package/src/admin/logger/index.ts +78 -78
  48. package/src/admin/mailing/README.md +95 -95
  49. package/src/admin/mailing/appointment/appointment.mailing.service.ts +732 -732
  50. package/src/admin/mailing/appointment/index.ts +1 -1
  51. package/src/admin/mailing/appointment/templates/patient/appointment-confirmed.html +40 -40
  52. package/src/admin/mailing/base.mailing.service.ts +208 -208
  53. package/src/admin/mailing/index.ts +3 -3
  54. package/src/admin/mailing/practitionerInvite/existing-practitioner-invite.mailing.ts +611 -611
  55. package/src/admin/mailing/practitionerInvite/index.ts +2 -2
  56. package/src/admin/mailing/practitionerInvite/practitionerInvite.mailing.ts +395 -395
  57. package/src/admin/mailing/practitionerInvite/templates/existing-practitioner-invitation.template.ts +155 -155
  58. package/src/admin/mailing/practitionerInvite/templates/invitation.template.ts +101 -101
  59. package/src/admin/mailing/practitionerInvite/templates/invite-accepted-notification.template.ts +228 -228
  60. package/src/admin/mailing/practitionerInvite/templates/invite-rejected-notification.template.ts +242 -242
  61. package/src/admin/notifications/index.ts +1 -1
  62. package/src/admin/notifications/notifications.admin.ts +710 -710
  63. package/src/admin/requirements/README.md +128 -128
  64. package/src/admin/requirements/index.ts +1 -1
  65. package/src/admin/requirements/patient-requirements.admin.service.ts +475 -475
  66. package/src/admin/users/index.ts +1 -1
  67. package/src/admin/users/user-profile.admin.ts +405 -405
  68. package/src/backoffice/constants/certification.constants.ts +13 -13
  69. package/src/backoffice/constants/index.ts +1 -1
  70. package/src/backoffice/errors/backoffice.errors.ts +181 -181
  71. package/src/backoffice/errors/index.ts +1 -1
  72. package/src/backoffice/expo-safe/README.md +26 -26
  73. package/src/backoffice/expo-safe/index.ts +41 -41
  74. package/src/backoffice/index.ts +5 -5
  75. package/src/backoffice/services/FIXES_README.md +102 -102
  76. package/src/backoffice/services/README.md +40 -40
  77. package/src/backoffice/services/brand.service.ts +256 -256
  78. package/src/backoffice/services/category.service.ts +318 -318
  79. package/src/backoffice/services/constants.service.ts +385 -385
  80. package/src/backoffice/services/documentation-template.service.ts +202 -202
  81. package/src/backoffice/services/index.ts +8 -8
  82. package/src/backoffice/services/migrate-products.ts +116 -116
  83. package/src/backoffice/services/product.service.ts +553 -553
  84. package/src/backoffice/services/requirement.service.ts +235 -235
  85. package/src/backoffice/services/subcategory.service.ts +395 -395
  86. package/src/backoffice/services/technology.service.ts +1070 -1070
  87. package/src/backoffice/types/README.md +12 -12
  88. package/src/backoffice/types/admin-constants.types.ts +69 -69
  89. package/src/backoffice/types/brand.types.ts +29 -29
  90. package/src/backoffice/types/category.types.ts +62 -62
  91. package/src/backoffice/types/documentation-templates.types.ts +28 -28
  92. package/src/backoffice/types/index.ts +10 -10
  93. package/src/backoffice/types/procedure-product.types.ts +38 -38
  94. package/src/backoffice/types/product.types.ts +240 -240
  95. package/src/backoffice/types/requirement.types.ts +63 -63
  96. package/src/backoffice/types/static/README.md +18 -18
  97. package/src/backoffice/types/static/blocking-condition.types.ts +21 -21
  98. package/src/backoffice/types/static/certification.types.ts +37 -37
  99. package/src/backoffice/types/static/contraindication.types.ts +19 -19
  100. package/src/backoffice/types/static/index.ts +6 -6
  101. package/src/backoffice/types/static/pricing.types.ts +16 -16
  102. package/src/backoffice/types/static/procedure-family.types.ts +14 -14
  103. package/src/backoffice/types/static/treatment-benefit.types.ts +22 -22
  104. package/src/backoffice/types/subcategory.types.ts +34 -34
  105. package/src/backoffice/types/technology.types.ts +161 -161
  106. package/src/backoffice/validations/index.ts +1 -1
  107. package/src/backoffice/validations/schemas.ts +163 -163
  108. package/src/config/__mocks__/firebase.ts +99 -99
  109. package/src/config/firebase.ts +78 -78
  110. package/src/config/index.ts +9 -9
  111. package/src/errors/auth.error.ts +6 -6
  112. package/src/errors/auth.errors.ts +200 -200
  113. package/src/errors/clinic.errors.ts +32 -32
  114. package/src/errors/firebase.errors.ts +47 -47
  115. package/src/errors/user.errors.ts +99 -99
  116. package/src/index.backup.ts +407 -407
  117. package/src/index.ts +6 -6
  118. package/src/locales/en.ts +31 -31
  119. package/src/recommender/admin/index.ts +1 -1
  120. package/src/recommender/admin/services/recommender.service.admin.ts +5 -5
  121. package/src/recommender/front/index.ts +1 -1
  122. package/src/recommender/front/services/onboarding.service.ts +5 -5
  123. package/src/recommender/front/services/recommender.service.ts +3 -3
  124. package/src/recommender/index.ts +1 -1
  125. package/src/services/PATIENTAUTH.MD +197 -197
  126. package/src/services/README.md +106 -106
  127. package/src/services/__tests__/auth/auth.mock.test.ts +17 -17
  128. package/src/services/__tests__/auth/auth.setup.ts +293 -293
  129. package/src/services/__tests__/auth.service.test.ts +346 -346
  130. package/src/services/__tests__/base.service.test.ts +77 -77
  131. package/src/services/__tests__/user.service.test.ts +528 -528
  132. package/src/services/appointment/README.md +17 -17
  133. package/src/services/appointment/appointment.service.ts +2082 -2082
  134. package/src/services/appointment/index.ts +1 -1
  135. package/src/services/appointment/utils/appointment.utils.ts +552 -552
  136. package/src/services/appointment/utils/extended-procedure.utils.ts +314 -314
  137. package/src/services/appointment/utils/form-initialization.utils.ts +225 -225
  138. package/src/services/appointment/utils/recommended-procedure.utils.ts +195 -195
  139. package/src/services/appointment/utils/zone-management.utils.ts +353 -353
  140. package/src/services/appointment/utils/zone-photo.utils.ts +152 -152
  141. package/src/services/auth/auth.service.ts +989 -989
  142. package/src/services/auth/auth.v2.service.ts +961 -961
  143. package/src/services/auth/index.ts +7 -7
  144. package/src/services/auth/utils/error.utils.ts +90 -90
  145. package/src/services/auth/utils/firebase.utils.ts +49 -49
  146. package/src/services/auth/utils/index.ts +21 -21
  147. package/src/services/auth/utils/practitioner.utils.ts +125 -125
  148. package/src/services/base.service.ts +41 -41
  149. package/src/services/calendar/calendar.service.ts +1077 -1077
  150. package/src/services/calendar/calendar.v2.service.ts +1683 -1683
  151. package/src/services/calendar/calendar.v3.service.ts +313 -313
  152. package/src/services/calendar/externalCalendar.service.ts +178 -178
  153. package/src/services/calendar/index.ts +5 -5
  154. package/src/services/calendar/synced-calendars.service.ts +743 -743
  155. package/src/services/calendar/utils/appointment.utils.ts +265 -265
  156. package/src/services/calendar/utils/calendar-event.utils.ts +646 -646
  157. package/src/services/calendar/utils/clinic.utils.ts +237 -237
  158. package/src/services/calendar/utils/docs.utils.ts +157 -157
  159. package/src/services/calendar/utils/google-calendar.utils.ts +697 -697
  160. package/src/services/calendar/utils/index.ts +8 -8
  161. package/src/services/calendar/utils/patient.utils.ts +198 -198
  162. package/src/services/calendar/utils/practitioner.utils.ts +221 -221
  163. package/src/services/calendar/utils/synced-calendar.utils.ts +472 -472
  164. package/src/services/clinic/README.md +204 -204
  165. package/src/services/clinic/__tests__/clinic-admin.service.test.ts +287 -287
  166. package/src/services/clinic/__tests__/clinic-group.service.test.ts +352 -352
  167. package/src/services/clinic/__tests__/clinic.service.test.ts +354 -354
  168. package/src/services/clinic/billing-transactions.service.ts +217 -217
  169. package/src/services/clinic/clinic-admin.service.ts +202 -202
  170. package/src/services/clinic/clinic-group.service.ts +310 -310
  171. package/src/services/clinic/clinic.service.ts +708 -708
  172. package/src/services/clinic/index.ts +5 -5
  173. package/src/services/clinic/practitioner-invite.service.ts +519 -519
  174. package/src/services/clinic/utils/admin.utils.ts +551 -551
  175. package/src/services/clinic/utils/clinic-group.utils.ts +646 -646
  176. package/src/services/clinic/utils/clinic.utils.ts +949 -949
  177. package/src/services/clinic/utils/filter.utils.d.ts +23 -23
  178. package/src/services/clinic/utils/filter.utils.ts +446 -446
  179. package/src/services/clinic/utils/index.ts +11 -11
  180. package/src/services/clinic/utils/photos.utils.ts +188 -188
  181. package/src/services/clinic/utils/search.utils.ts +84 -84
  182. package/src/services/clinic/utils/tag.utils.ts +124 -124
  183. package/src/services/documentation-templates/documentation-template.service.ts +537 -537
  184. package/src/services/documentation-templates/filled-document.service.ts +587 -587
  185. package/src/services/documentation-templates/index.ts +2 -2
  186. package/src/services/index.ts +13 -13
  187. package/src/services/media/index.ts +1 -1
  188. package/src/services/media/media.service.ts +418 -418
  189. package/src/services/notifications/__tests__/notification.service.test.ts +242 -242
  190. package/src/services/notifications/index.ts +1 -1
  191. package/src/services/notifications/notification.service.ts +215 -215
  192. package/src/services/patient/README.md +48 -48
  193. package/src/services/patient/To-Do.md +43 -43
  194. package/src/services/patient/__tests__/patient.service.test.ts +294 -294
  195. package/src/services/patient/index.ts +2 -2
  196. package/src/services/patient/patient.service.ts +883 -883
  197. package/src/services/patient/patientRequirements.service.ts +285 -285
  198. package/src/services/patient/utils/aesthetic-analysis.utils.ts +176 -176
  199. package/src/services/patient/utils/clinic.utils.ts +80 -80
  200. package/src/services/patient/utils/docs.utils.ts +142 -142
  201. package/src/services/patient/utils/index.ts +9 -9
  202. package/src/services/patient/utils/location.utils.ts +126 -126
  203. package/src/services/patient/utils/medical-stuff.utils.ts +143 -143
  204. package/src/services/patient/utils/medical.utils.ts +458 -458
  205. package/src/services/patient/utils/practitioner.utils.ts +260 -260
  206. package/src/services/patient/utils/profile.utils.ts +510 -510
  207. package/src/services/patient/utils/sensitive.utils.ts +260 -260
  208. package/src/services/patient/utils/token.utils.ts +211 -211
  209. package/src/services/practitioner/README.md +145 -145
  210. package/src/services/practitioner/index.ts +1 -1
  211. package/src/services/practitioner/practitioner.service.ts +1742 -1742
  212. package/src/services/procedure/README.md +163 -163
  213. package/src/services/procedure/index.ts +1 -1
  214. package/src/services/procedure/procedure.service.ts +1682 -1682
  215. package/src/services/reviews/index.ts +1 -1
  216. package/src/services/reviews/reviews.service.ts +636 -636
  217. package/src/services/user/index.ts +1 -1
  218. package/src/services/user/user.service.ts +489 -489
  219. package/src/services/user/user.v2.service.ts +466 -466
  220. package/src/types/appointment/index.ts +453 -453
  221. package/src/types/calendar/index.ts +258 -258
  222. package/src/types/calendar/synced-calendar.types.ts +66 -66
  223. package/src/types/clinic/index.ts +489 -489
  224. package/src/types/clinic/practitioner-invite.types.ts +91 -91
  225. package/src/types/clinic/preferences.types.ts +159 -159
  226. package/src/types/clinic/to-do +3 -3
  227. package/src/types/documentation-templates/index.ts +308 -308
  228. package/src/types/index.ts +44 -44
  229. package/src/types/notifications/README.md +77 -77
  230. package/src/types/notifications/index.ts +265 -265
  231. package/src/types/patient/aesthetic-analysis.types.ts +66 -66
  232. package/src/types/patient/allergies.ts +58 -58
  233. package/src/types/patient/index.ts +273 -273
  234. package/src/types/patient/medical-info.types.ts +152 -152
  235. package/src/types/patient/patient-requirements.ts +92 -81
  236. package/src/types/patient/token.types.ts +61 -61
  237. package/src/types/practitioner/index.ts +206 -206
  238. package/src/types/procedure/index.ts +181 -181
  239. package/src/types/profile/index.ts +39 -39
  240. package/src/types/reviews/index.ts +130 -130
  241. package/src/types/tz-lookup.d.ts +4 -4
  242. package/src/types/user/index.ts +38 -38
  243. package/src/utils/TIMESTAMPS.md +176 -176
  244. package/src/utils/TimestampUtils.ts +241 -241
  245. package/src/utils/index.ts +1 -1
  246. package/src/validations/appointment.schema.ts +574 -574
  247. package/src/validations/calendar.schema.ts +225 -225
  248. package/src/validations/clinic.schema.ts +493 -493
  249. package/src/validations/common.schema.ts +25 -25
  250. package/src/validations/documentation-templates/index.ts +1 -1
  251. package/src/validations/documentation-templates/template.schema.ts +220 -220
  252. package/src/validations/documentation-templates.schema.ts +10 -10
  253. package/src/validations/index.ts +20 -20
  254. package/src/validations/media.schema.ts +10 -10
  255. package/src/validations/notification.schema.ts +90 -90
  256. package/src/validations/patient/aesthetic-analysis.schema.ts +55 -55
  257. package/src/validations/patient/medical-info.schema.ts +125 -125
  258. package/src/validations/patient/patient-requirements.schema.ts +84 -75
  259. package/src/validations/patient/token.schema.ts +29 -29
  260. package/src/validations/patient.schema.ts +216 -216
  261. package/src/validations/practitioner.schema.ts +222 -222
  262. package/src/validations/procedure-product.schema.ts +41 -41
  263. package/src/validations/procedure.schema.ts +124 -124
  264. package/src/validations/profile-info.schema.ts +41 -41
  265. package/src/validations/reviews.schema.ts +189 -189
  266. package/src/validations/schemas.ts +104 -104
  267. package/src/validations/shared.schema.ts +78 -78
@@ -1,1070 +1,1070 @@
1
- import {
2
- addDoc,
3
- collection,
4
- doc,
5
- DocumentData,
6
- getCountFromServer,
7
- getDoc,
8
- getDocs,
9
- limit,
10
- orderBy,
11
- query,
12
- startAfter,
13
- updateDoc,
14
- where,
15
- arrayUnion,
16
- arrayRemove,
17
- Firestore,
18
- writeBatch,
19
- QueryConstraint,
20
- } from 'firebase/firestore';
21
- import { Technology, TECHNOLOGIES_COLLECTION, ITechnologyService } from '../types/technology.types';
22
- import { Requirement, RequirementType } from '../types/requirement.types';
23
- import { BlockingCondition } from '../types/static/blocking-condition.types';
24
- import { ContraindicationDynamic } from '../types/admin-constants.types';
25
- import { TreatmentBenefitDynamic } from '../types/admin-constants.types';
26
- import {
27
- CertificationLevel,
28
- CertificationSpecialty,
29
- CertificationRequirement,
30
- } from '../types/static/certification.types';
31
- import { BaseService } from '../../services/base.service';
32
- import { ProcedureFamily } from '../types/static/procedure-family.types';
33
- import { Practitioner, PractitionerCertification } from '../../types/practitioner';
34
- import { Product, PRODUCTS_COLLECTION } from '../types/product.types';
35
-
36
- /**
37
- * Default vrednosti za sertifikaciju
38
- */
39
- const DEFAULT_CERTIFICATION_REQUIREMENT: CertificationRequirement = {
40
- minimumLevel: CertificationLevel.AESTHETICIAN,
41
- requiredSpecialties: [],
42
- };
43
-
44
- /**
45
- * Service for managing technologies.
46
- */
47
- export class TechnologyService extends BaseService implements ITechnologyService {
48
- /**
49
- * Reference to the Firestore collection of technologies.
50
- */
51
- private get technologiesRef() {
52
- return collection(this.db, TECHNOLOGIES_COLLECTION);
53
- }
54
-
55
- /**
56
- * Creates a new technology.
57
- * @param technology - Data for the new technology.
58
- * @returns The created technology with its generated ID.
59
- */
60
- async create(technology: Omit<Technology, 'id' | 'createdAt' | 'updatedAt'>) {
61
- const now = new Date();
62
- // Explicitly construct the object to ensure no undefined values are passed.
63
- const newTechnology: Omit<Technology, 'id'> = {
64
- name: technology.name,
65
- description: technology.description,
66
- family: technology.family,
67
- categoryId: technology.categoryId,
68
- subcategoryId: technology.subcategoryId,
69
- requirements: technology.requirements || { pre: [], post: [] },
70
- blockingConditions: technology.blockingConditions || [],
71
- contraindications: technology.contraindications || [],
72
- benefits: technology.benefits || [],
73
- certificationRequirement:
74
- technology.certificationRequirement || DEFAULT_CERTIFICATION_REQUIREMENT,
75
- documentationTemplates: technology.documentationTemplates || [],
76
- isActive: true,
77
- createdAt: now,
78
- updatedAt: now,
79
- };
80
-
81
- // Add optional fields only if they are not undefined
82
- if (technology.technicalDetails) {
83
- newTechnology.technicalDetails = technology.technicalDetails;
84
- }
85
-
86
- const docRef = await addDoc(this.technologiesRef, newTechnology as any);
87
- return { id: docRef.id, ...newTechnology };
88
- }
89
-
90
- /**
91
- * Returns counts of technologies for each subcategory.
92
- * @param active - Whether to count active or inactive technologies.
93
- * @returns A record mapping subcategory ID to technology count.
94
- */
95
- async getTechnologyCounts(active = true) {
96
- const q = query(this.technologiesRef, where('isActive', '==', active));
97
- const snapshot = await getDocs(q);
98
- const counts: Record<string, number> = {};
99
- snapshot.docs.forEach(doc => {
100
- const tech = doc.data() as Technology;
101
- counts[tech.subcategoryId] = (counts[tech.subcategoryId] || 0) + 1;
102
- });
103
- return counts;
104
- }
105
-
106
- /**
107
- * Returns counts of technologies for each category.
108
- * @param active - Whether to count active or inactive technologies.
109
- * @returns A record mapping category ID to technology count.
110
- */
111
- async getTechnologyCountsByCategory(active = true) {
112
- const q = query(this.technologiesRef, where('isActive', '==', active));
113
- const snapshot = await getDocs(q);
114
- const counts: Record<string, number> = {};
115
- snapshot.docs.forEach(doc => {
116
- const tech = doc.data() as Technology;
117
- counts[tech.categoryId] = (counts[tech.categoryId] || 0) + 1;
118
- });
119
- return counts;
120
- }
121
-
122
- /**
123
- * Returns all technologies with pagination.
124
- * @param options - Pagination and filter options.
125
- * @returns A list of technologies and the last visible document.
126
- */
127
- async getAll(
128
- options: {
129
- active?: boolean;
130
- limit?: number;
131
- lastVisible?: DocumentData;
132
- } = {},
133
- ) {
134
- const { active = true, limit: queryLimit = 10, lastVisible } = options;
135
- const constraints = [
136
- where('isActive', '==', active),
137
- orderBy('name'),
138
- queryLimit ? limit(queryLimit) : undefined,
139
- lastVisible ? startAfter(lastVisible) : undefined,
140
- ].filter((c): c is NonNullable<typeof c> => !!c);
141
-
142
- const q = query(this.technologiesRef, ...constraints);
143
- const snapshot = await getDocs(q);
144
- const technologies = snapshot.docs.map(
145
- doc =>
146
- ({
147
- id: doc.id,
148
- ...doc.data(),
149
- } as Technology),
150
- );
151
- const newLastVisible = snapshot.docs[snapshot.docs.length - 1];
152
- return { technologies, lastVisible: newLastVisible };
153
- }
154
-
155
- /**
156
- * Returns all technologies for a specific category with pagination.
157
- * @param categoryId - The ID of the category.
158
- * @param options - Pagination options.
159
- * @returns A list of technologies for the specified category.
160
- */
161
- async getAllByCategoryId(
162
- categoryId: string,
163
- options: {
164
- active?: boolean;
165
- limit?: number;
166
- lastVisible?: DocumentData;
167
- } = {},
168
- ) {
169
- const { active = true, limit: queryLimit = 10, lastVisible } = options;
170
- const constraints = [
171
- where('categoryId', '==', categoryId),
172
- where('isActive', '==', active),
173
- orderBy('name'),
174
- queryLimit ? limit(queryLimit) : undefined,
175
- lastVisible ? startAfter(lastVisible) : undefined,
176
- ].filter((c): c is NonNullable<typeof c> => !!c);
177
-
178
- const q = query(this.technologiesRef, ...constraints);
179
- const snapshot = await getDocs(q);
180
- const technologies = snapshot.docs.map(
181
- doc =>
182
- ({
183
- id: doc.id,
184
- ...doc.data(),
185
- } as Technology),
186
- );
187
- const newLastVisible = snapshot.docs[snapshot.docs.length - 1];
188
- return { technologies, lastVisible: newLastVisible };
189
- }
190
-
191
- /**
192
- * Returns all technologies for a specific subcategory with pagination.
193
- * @param subcategoryId - The ID of the subcategory.
194
- * @param options - Pagination options.
195
- * @returns A list of technologies for the specified subcategory.
196
- */
197
- async getAllBySubcategoryId(
198
- subcategoryId: string,
199
- options: {
200
- active?: boolean;
201
- limit?: number;
202
- lastVisible?: DocumentData;
203
- } = {},
204
- ) {
205
- const { active = true, limit: queryLimit = 10, lastVisible } = options;
206
- const constraints = [
207
- where('subcategoryId', '==', subcategoryId),
208
- where('isActive', '==', active),
209
- orderBy('name'),
210
- queryLimit ? limit(queryLimit) : undefined,
211
- lastVisible ? startAfter(lastVisible) : undefined,
212
- ].filter((c): c is NonNullable<typeof c> => !!c);
213
-
214
- const q = query(this.technologiesRef, ...constraints);
215
- const snapshot = await getDocs(q);
216
- const technologies = snapshot.docs.map(
217
- doc =>
218
- ({
219
- id: doc.id,
220
- ...doc.data(),
221
- } as Technology),
222
- );
223
- const newLastVisible = snapshot.docs[snapshot.docs.length - 1];
224
- return { technologies, lastVisible: newLastVisible };
225
- }
226
-
227
- /**
228
- * Updates an existing technology.
229
- * @param id - The ID of the technology to update.
230
- * @param technology - New data for the technology.
231
- * @returns The updated technology.
232
- */
233
- async update(id: string, technology: Partial<Omit<Technology, 'id' | 'createdAt'>>) {
234
- const updateData: { [key: string]: any } = { ...technology };
235
-
236
- // Remove undefined fields to prevent Firestore errors
237
- Object.keys(updateData).forEach(key => {
238
- if (updateData[key] === undefined) {
239
- delete updateData[key];
240
- }
241
- });
242
-
243
- updateData.updatedAt = new Date();
244
-
245
- const docRef = doc(this.technologiesRef, id);
246
-
247
- // Get the technology before update to check what changed
248
- const beforeTech = await this.getById(id);
249
-
250
- await updateDoc(docRef, updateData);
251
-
252
- // If categoryId, subcategoryId, or name changed, update all products in subcollection
253
- const categoryChanged = beforeTech && updateData.categoryId && beforeTech.categoryId !== updateData.categoryId;
254
- const subcategoryChanged = beforeTech && updateData.subcategoryId && beforeTech.subcategoryId !== updateData.subcategoryId;
255
- const nameChanged = beforeTech && updateData.name && beforeTech.name !== updateData.name;
256
-
257
- if (categoryChanged || subcategoryChanged || nameChanged) {
258
- await this.updateProductsInSubcollection(id, {
259
- categoryId: updateData.categoryId,
260
- subcategoryId: updateData.subcategoryId,
261
- technologyName: updateData.name,
262
- });
263
- }
264
-
265
- return this.getById(id);
266
- }
267
-
268
- /**
269
- * Soft deletes a technology.
270
- * @param id - The ID of the technology to delete.
271
- */
272
- async delete(id: string) {
273
- await this.update(id, { isActive: false });
274
- }
275
-
276
- /**
277
- * Reactivates a technology.
278
- * @param id - The ID of the technology to reactivate.
279
- */
280
- async reactivate(id: string) {
281
- await this.update(id, { isActive: true });
282
- }
283
-
284
- /**
285
- * Returns a technology by its ID.
286
- * @param id - The ID of the requested technology.
287
- * @returns The technology or null if it doesn't exist.
288
- */
289
- async getById(id: string): Promise<Technology | null> {
290
- const docRef = doc(this.technologiesRef, id);
291
- const docSnap = await getDoc(docRef);
292
- if (!docSnap.exists()) return null;
293
- return {
294
- id: docSnap.id,
295
- ...docSnap.data(),
296
- } as Technology;
297
- }
298
-
299
- /**
300
- * Dodaje novi zahtev tehnologiji
301
- * @param technologyId - ID tehnologije
302
- * @param requirement - Zahtev koji se dodaje
303
- * @returns Ažurirana tehnologija sa novim zahtevom
304
- */
305
- async addRequirement(technologyId: string, requirement: Requirement) {
306
- const docRef = doc(this.technologiesRef, technologyId);
307
-
308
- const requirementType = requirement.type === 'pre' ? 'requirements.pre' : 'requirements.post';
309
-
310
- await updateDoc(docRef, {
311
- [requirementType]: arrayUnion(requirement),
312
- updatedAt: new Date(),
313
- });
314
-
315
- return this.getById(technologyId);
316
- }
317
-
318
- /**
319
- * Uklanja zahtev iz tehnologije
320
- * @param technologyId - ID tehnologije
321
- * @param requirement - Zahtev koji se uklanja
322
- * @returns Ažurirana tehnologija bez uklonjenog zahteva
323
- */
324
- async removeRequirement(technologyId: string, requirement: Requirement) {
325
- const docRef = doc(this.technologiesRef, technologyId);
326
-
327
- const requirementType = requirement.type === 'pre' ? 'requirements.pre' : 'requirements.post';
328
-
329
- await updateDoc(docRef, {
330
- [requirementType]: arrayRemove(requirement),
331
- updatedAt: new Date(),
332
- });
333
-
334
- return this.getById(technologyId);
335
- }
336
-
337
- /**
338
- * Vraća sve zahteve za tehnologiju
339
- * @param technologyId - ID tehnologije
340
- * @param type - Opcioni filter za tip zahteva (pre/post)
341
- * @returns Lista zahteva
342
- */
343
- async getRequirements(technologyId: string, type?: RequirementType) {
344
- const technology = await this.getById(technologyId);
345
- if (!technology || !technology.requirements) return [];
346
-
347
- if (type) {
348
- return technology.requirements[type];
349
- }
350
-
351
- return [...technology.requirements.pre, ...technology.requirements.post];
352
- }
353
-
354
- /**
355
- * Ažurira postojeći zahtev
356
- * @param technologyId - ID tehnologije
357
- * @param oldRequirement - Stari zahtev koji se menja
358
- * @param newRequirement - Novi zahtev koji zamenjuje stari
359
- * @returns Ažurirana tehnologija
360
- */
361
- async updateRequirement(
362
- technologyId: string,
363
- oldRequirement: Requirement,
364
- newRequirement: Requirement,
365
- ) {
366
- await this.removeRequirement(technologyId, oldRequirement);
367
- return this.addRequirement(technologyId, newRequirement);
368
- }
369
-
370
- /**
371
- * Dodaje blokirajući uslov tehnologiji
372
- * @param technologyId - ID tehnologije
373
- * @param condition - Blokirajući uslov koji se dodaje
374
- * @returns Ažurirana tehnologija
375
- */
376
- async addBlockingCondition(technologyId: string, condition: BlockingCondition) {
377
- const docRef = doc(this.technologiesRef, technologyId);
378
-
379
- await updateDoc(docRef, {
380
- blockingConditions: arrayUnion(condition),
381
- updatedAt: new Date(),
382
- });
383
-
384
- return this.getById(technologyId);
385
- }
386
-
387
- /**
388
- * Uklanja blokirajući uslov iz tehnologije
389
- * @param technologyId - ID tehnologije
390
- * @param condition - Blokirajući uslov koji se uklanja
391
- * @returns Ažurirana tehnologija
392
- */
393
- async removeBlockingCondition(technologyId: string, condition: BlockingCondition) {
394
- const docRef = doc(this.technologiesRef, technologyId);
395
-
396
- await updateDoc(docRef, {
397
- blockingConditions: arrayRemove(condition),
398
- updatedAt: new Date(),
399
- });
400
-
401
- return this.getById(technologyId);
402
- }
403
-
404
- /**
405
- * Dodaje kontraindikaciju tehnologiji
406
- * @param technologyId - ID tehnologije
407
- * @param contraindication - Kontraindikacija koja se dodaje
408
- * @returns Ažurirana tehnologija
409
- */
410
- async addContraindication(technologyId: string, contraindication: ContraindicationDynamic) {
411
- const docRef = doc(this.technologiesRef, technologyId);
412
- const technology = await this.getById(technologyId);
413
- if (!technology) {
414
- throw new Error(`Technology with id ${technologyId} not found`);
415
- }
416
-
417
- const existingContraindications = technology.contraindications || [];
418
- if (existingContraindications.some(c => c.id === contraindication.id)) {
419
- return technology; // Already exists, do nothing
420
- }
421
-
422
- await updateDoc(docRef, {
423
- contraindications: [...existingContraindications, contraindication],
424
- updatedAt: new Date(),
425
- });
426
-
427
- return this.getById(technologyId);
428
- }
429
-
430
- /**
431
- * Uklanja kontraindikaciju iz tehnologije
432
- * @param technologyId - ID tehnologije
433
- * @param contraindication - Kontraindikacija koja se uklanja
434
- * @returns Ažurirana tehnologija
435
- */
436
- async removeContraindication(technologyId: string, contraindication: ContraindicationDynamic) {
437
- const docRef = doc(this.technologiesRef, technologyId);
438
- const technology = await this.getById(technologyId);
439
- if (!technology) {
440
- throw new Error(`Technology with id ${technologyId} not found`);
441
- }
442
-
443
- const updatedContraindications = (technology.contraindications || []).filter(
444
- c => c.id !== contraindication.id,
445
- );
446
-
447
- await updateDoc(docRef, {
448
- contraindications: updatedContraindications,
449
- updatedAt: new Date(),
450
- });
451
-
452
- return this.getById(technologyId);
453
- }
454
-
455
- /**
456
- * Updates an existing contraindication in a technology's list.
457
- * If the contraindication does not exist, it will not be added.
458
- * @param technologyId - ID of the technology
459
- * @param contraindication - The updated contraindication object
460
- * @returns The updated technology
461
- */
462
- async updateContraindication(technologyId: string, contraindication: ContraindicationDynamic) {
463
- const docRef = doc(this.technologiesRef, technologyId);
464
- const technology = await this.getById(technologyId);
465
- if (!technology) {
466
- throw new Error(`Technology with id ${technologyId} not found`);
467
- }
468
-
469
- const contraindications = technology.contraindications || [];
470
- const index = contraindications.findIndex(c => c.id === contraindication.id);
471
-
472
- if (index === -1) {
473
- // If contraindication doesn't exist, do not update
474
- // Consider throwing an error if this is an unexpected state
475
- console.warn(
476
- `Contraindication with id ${contraindication.id} not found for technology ${technologyId}. No update performed.`,
477
- );
478
- return technology;
479
- }
480
-
481
- const updatedContraindications = [...contraindications];
482
- updatedContraindications[index] = contraindication;
483
-
484
- await updateDoc(docRef, {
485
- contraindications: updatedContraindications,
486
- updatedAt: new Date(),
487
- });
488
-
489
- return this.getById(technologyId);
490
- }
491
-
492
- /**
493
- * Dodaje benefit tehnologiji
494
- * @param technologyId - ID tehnologije
495
- * @param benefit - Benefit koji se dodaje
496
- * @returns Ažurirana tehnologija
497
- */
498
- async addBenefit(technologyId: string, benefit: TreatmentBenefitDynamic) {
499
- const docRef = doc(this.technologiesRef, technologyId);
500
- const technology = await this.getById(technologyId);
501
- if (!technology) {
502
- throw new Error(`Technology with id ${technologyId} not found`);
503
- }
504
-
505
- const existingBenefits = technology.benefits || [];
506
- if (existingBenefits.some(b => b.id === benefit.id)) {
507
- return technology; // Already exists, do nothing
508
- }
509
-
510
- await updateDoc(docRef, {
511
- benefits: [...existingBenefits, benefit],
512
- updatedAt: new Date(),
513
- });
514
-
515
- return this.getById(technologyId);
516
- }
517
-
518
- /**
519
- * Uklanja benefit iz tehnologije
520
- * @param technologyId - ID tehnologije
521
- * @param benefit - Benefit koji se uklanja
522
- * @returns Ažurirana tehnologija
523
- */
524
- async removeBenefit(technologyId: string, benefit: TreatmentBenefitDynamic) {
525
- const docRef = doc(this.technologiesRef, technologyId);
526
- const technology = await this.getById(technologyId);
527
- if (!technology) {
528
- throw new Error(`Technology with id ${technologyId} not found`);
529
- }
530
-
531
- const updatedBenefits = (technology.benefits || []).filter(b => b.id !== benefit.id);
532
-
533
- await updateDoc(docRef, {
534
- benefits: updatedBenefits,
535
- updatedAt: new Date(),
536
- });
537
-
538
- return this.getById(technologyId);
539
- }
540
-
541
- /**
542
- * Updates an existing benefit in a technology's list.
543
- * If the benefit does not exist, it will not be added.
544
- * @param technologyId - ID of the technology
545
- * @param benefit - The updated benefit object
546
- * @returns The updated technology
547
- */
548
- async updateBenefit(technologyId: string, benefit: TreatmentBenefitDynamic) {
549
- const docRef = doc(this.technologiesRef, technologyId);
550
- const technology = await this.getById(technologyId);
551
- if (!technology) {
552
- throw new Error(`Technology with id ${technologyId} not found`);
553
- }
554
-
555
- const benefits = technology.benefits || [];
556
- const index = benefits.findIndex(b => b.id === benefit.id);
557
-
558
- if (index === -1) {
559
- // If benefit doesn't exist, do not update
560
- console.warn(
561
- `Benefit with id ${benefit.id} not found for technology ${technologyId}. No update performed.`,
562
- );
563
- return technology;
564
- }
565
-
566
- const updatedBenefits = [...benefits];
567
- updatedBenefits[index] = benefit;
568
-
569
- await updateDoc(docRef, {
570
- benefits: updatedBenefits,
571
- updatedAt: new Date(),
572
- });
573
-
574
- return this.getById(technologyId);
575
- }
576
-
577
- /**
578
- * Vraća sve blokirajuće uslove za tehnologiju
579
- * @param technologyId - ID tehnologije
580
- * @returns Lista blokirajućih uslova
581
- */
582
- async getBlockingConditions(technologyId: string) {
583
- const technology = await this.getById(technologyId);
584
- return technology?.blockingConditions || [];
585
- }
586
-
587
- /**
588
- * Vraća sve kontraindikacije za tehnologiju
589
- * @param technologyId - ID tehnologije
590
- * @returns Lista kontraindikacija
591
- */
592
- async getContraindications(technologyId: string) {
593
- const technology = await this.getById(technologyId);
594
- return technology?.contraindications || [];
595
- }
596
-
597
- /**
598
- * Vraća sve benefite za tehnologiju
599
- * @param technologyId - ID tehnologije
600
- * @returns Lista benefita
601
- */
602
- async getBenefits(technologyId: string) {
603
- const technology = await this.getById(technologyId);
604
- return technology?.benefits || [];
605
- }
606
-
607
- /**
608
- * Ažurira zahteve sertifikacije za tehnologiju
609
- * @param technologyId - ID tehnologije
610
- * @param certificationRequirement - Novi zahtevi sertifikacije
611
- * @returns Ažurirana tehnologija
612
- */
613
- async updateCertificationRequirement(
614
- technologyId: string,
615
- certificationRequirement: CertificationRequirement,
616
- ) {
617
- const docRef = doc(this.technologiesRef, technologyId);
618
-
619
- await updateDoc(docRef, {
620
- certificationRequirement,
621
- updatedAt: new Date(),
622
- });
623
-
624
- return this.getById(technologyId);
625
- }
626
-
627
- /**
628
- * Vraća zahteve sertifikacije za tehnologiju
629
- * @param technologyId - ID tehnologije
630
- * @returns Zahtevi sertifikacije ili null ako tehnologija ne postoji
631
- */
632
- async getCertificationRequirement(
633
- technologyId: string,
634
- ): Promise<CertificationRequirement | null> {
635
- const technology = await this.getById(technologyId);
636
- return technology?.certificationRequirement || null;
637
- }
638
-
639
- /**
640
- * Proverava da li doktor ima odgovarajuću sertifikaciju za izvođenje tehnologije
641
- *
642
- * @param requiredCertification - Zahtevana sertifikacija za tehnologiju
643
- * @param practitionerCertification - Sertifikacija zdravstvenog radnika
644
- * @returns true ako zdravstveni radnik ima odgovarajuću sertifikaciju, false ako nema
645
- *
646
- * @example
647
- * const isValid = technologyService.validateCertification(
648
- * {
649
- * minimumLevel: CertificationLevel.DOCTOR,
650
- * requiredSpecialties: [CertificationSpecialty.INJECTABLES]
651
- * },
652
- * {
653
- * level: CertificationLevel.SPECIALIST,
654
- * specialties: [CertificationSpecialty.INJECTABLES, CertificationSpecialty.LASER]
655
- * }
656
- * );
657
- */
658
- validateCertification(
659
- requiredCertification: CertificationRequirement,
660
- practitionerCertification: PractitionerCertification,
661
- ): boolean {
662
- // Provera nivoa sertifikacije
663
- // Enum je definisan od najnižeg ka najvišem, pa možemo porediti brojeve
664
- const doctorLevel = Object.values(CertificationLevel).indexOf(practitionerCertification.level);
665
- const requiredLevel = Object.values(CertificationLevel).indexOf(
666
- requiredCertification.minimumLevel,
667
- );
668
-
669
- // Doktor mora imati nivo koji je jednak ili viši od zahtevanog
670
- if (doctorLevel < requiredLevel) return false;
671
-
672
- // Provera specijalizacija
673
- const requiredSpecialties = requiredCertification.requiredSpecialties || [];
674
- if (requiredSpecialties.length > 0) {
675
- // Doktor mora imati sve zahtevane specijalizacije
676
- const doctorSpecialties = practitionerCertification.specialties;
677
- const hasAllRequiredSpecialties = requiredSpecialties.every(requiredSpecialty =>
678
- doctorSpecialties.includes(requiredSpecialty),
679
- );
680
-
681
- if (!hasAllRequiredSpecialties) return false;
682
- }
683
-
684
- return true;
685
- }
686
-
687
- /**
688
- * Vraća sve tehnologije koje je zdravstveni radnik sertifikovan da izvodi
689
- * zajedno sa listama dozvoljenih familija, kategorija i podkategorija
690
- *
691
- * @param practitioner - Profil zdravstvenog radnika
692
- * @returns Objekat koji sadrži:
693
- * - technologies: Lista tehnologija koje zdravstveni radnik može da izvodi
694
- * - families: Lista familija procedura koje zdravstveni radnik može da izvodi
695
- * - categories: Lista ID-eva kategorija koje zdravstveni radnik može da izvodi
696
- * - subcategories: Lista ID-eva podkategorija koje zdravstveni radnik može da izvodi
697
- *
698
- * @example
699
- * const practitioner = {
700
- * certification: {
701
- * level: CertificationLevel.DOCTOR,
702
- * specialties: [CertificationSpecialty.INJECTABLES]
703
- * }
704
- * };
705
- * const allowedTechnologies = await technologyService.getAllowedTechnologies(practitioner);
706
- * console.log(allowedTechnologies.families); // [ProcedureFamily.AESTHETICS]
707
- * console.log(allowedTechnologies.categories); // ["category1", "category2"]
708
- * console.log(allowedTechnologies.subcategories); // ["subcategory1", "subcategory2"]
709
- */
710
- async getAllowedTechnologies(practitioner: Practitioner): Promise<{
711
- technologies: Technology[];
712
- families: ProcedureFamily[];
713
- categories: string[];
714
- subcategories: string[];
715
- }> {
716
- // Get all active technologies
717
- const allTechnologies = await this.getAllForFilter();
718
-
719
- // Filter technologies based on certification requirements
720
- const allowedTechnologies = allTechnologies.filter(technology =>
721
- this.validateCertification(technology.certificationRequirement, practitioner.certification),
722
- );
723
-
724
- // Extract unique families, categories, and subcategories
725
- const families = [...new Set(allowedTechnologies.map(t => t.family))];
726
- const categories = [...new Set(allowedTechnologies.map(t => t.categoryId))];
727
- const subcategories = [...new Set(allowedTechnologies.map(t => t.subcategoryId))];
728
-
729
- return {
730
- technologies: allowedTechnologies,
731
- families,
732
- categories,
733
- subcategories,
734
- };
735
- }
736
-
737
- /**
738
- * Gets all active technologies for a subcategory for filter dropdowns (by subcategory only).
739
- * @param subcategoryId - The ID of the subcategory.
740
- */
741
- async getAllForFilterBySubcategory(subcategoryId: string): Promise<Technology[]> {
742
- const q = query(
743
- collection(this.db, TECHNOLOGIES_COLLECTION),
744
- where('isActive', '==', true),
745
- where('subcategoryId', '==', subcategoryId),
746
- orderBy('name'),
747
- );
748
- const snapshot = await getDocs(q);
749
- return snapshot.docs.map(
750
- doc =>
751
- ({
752
- id: doc.id,
753
- ...doc.data(),
754
- } as Technology),
755
- );
756
- }
757
-
758
- /**
759
- * Gets all active technologies for a subcategory for filter dropdowns.
760
- * @param categoryId - The ID of the parent category.
761
- * @param subcategoryId - The ID of the subcategory.
762
- */
763
- async getAllForFilterBySubcategoryId(
764
- categoryId: string,
765
- subcategoryId: string,
766
- ): Promise<Technology[]> {
767
- const q = query(
768
- collection(this.db, TECHNOLOGIES_COLLECTION),
769
- where('isActive', '==', true),
770
- where('categoryId', '==', categoryId),
771
- where('subcategoryId', '==', subcategoryId),
772
- orderBy('name'),
773
- );
774
- const snapshot = await getDocs(q);
775
- return snapshot.docs.map(
776
- doc =>
777
- ({
778
- id: doc.id,
779
- ...doc.data(),
780
- } as Technology),
781
- );
782
- }
783
-
784
- /**
785
- * Gets all active technologies for filter dropdowns.
786
- */
787
- async getAllForFilter(): Promise<Technology[]> {
788
- const q = query(
789
- collection(this.db, TECHNOLOGIES_COLLECTION),
790
- where('isActive', '==', true),
791
- orderBy('name'),
792
- );
793
- const snapshot = await getDocs(q);
794
- return snapshot.docs.map(
795
- doc =>
796
- ({
797
- id: doc.id,
798
- ...doc.data(),
799
- } as Technology),
800
- );
801
- }
802
-
803
- // ==========================================
804
- // NEW METHODS: Product assignment management
805
- // ==========================================
806
-
807
- /**
808
- * Assigns multiple products to a technology
809
- * Updates each product's assignedTechnologyIds array
810
- */
811
- async assignProducts(technologyId: string, productIds: string[]): Promise<void> {
812
- const batch = writeBatch(this.db);
813
-
814
- for (const productId of productIds) {
815
- const productRef = doc(this.db, PRODUCTS_COLLECTION, productId);
816
- batch.update(productRef, {
817
- assignedTechnologyIds: arrayUnion(technologyId),
818
- updatedAt: new Date(),
819
- });
820
- }
821
-
822
- await batch.commit();
823
- // Cloud Function will handle syncing to subcollections
824
- }
825
-
826
- /**
827
- * Unassigns multiple products from a technology
828
- * Updates each product's assignedTechnologyIds array
829
- */
830
- async unassignProducts(technologyId: string, productIds: string[]): Promise<void> {
831
- const batch = writeBatch(this.db);
832
-
833
- for (const productId of productIds) {
834
- const productRef = doc(this.db, PRODUCTS_COLLECTION, productId);
835
- batch.update(productRef, {
836
- assignedTechnologyIds: arrayRemove(technologyId),
837
- updatedAt: new Date(),
838
- });
839
- }
840
-
841
- await batch.commit();
842
- // Cloud Function will handle removing from subcollections
843
- }
844
-
845
- /**
846
- * Gets products assigned to a specific technology
847
- * Reads from top-level collection for immediate consistency (Cloud Functions may lag)
848
- */
849
- async getAssignedProducts(technologyId: string): Promise<Product[]> {
850
- const q = query(
851
- collection(this.db, PRODUCTS_COLLECTION),
852
- where('assignedTechnologyIds', 'array-contains', technologyId),
853
- where('isActive', '==', true),
854
- orderBy('name'),
855
- );
856
- const snapshot = await getDocs(q);
857
-
858
- return snapshot.docs.map(
859
- doc =>
860
- ({
861
- id: doc.id,
862
- ...doc.data(),
863
- } as Product),
864
- );
865
- }
866
-
867
- /**
868
- * Gets products NOT assigned to a specific technology
869
- */
870
- async getUnassignedProducts(technologyId: string): Promise<Product[]> {
871
- const q = query(
872
- collection(this.db, PRODUCTS_COLLECTION),
873
- where('isActive', '==', true),
874
- orderBy('name'),
875
- );
876
- const snapshot = await getDocs(q);
877
-
878
- const allProducts = snapshot.docs.map(
879
- doc =>
880
- ({
881
- id: doc.id,
882
- ...doc.data(),
883
- } as Product),
884
- );
885
-
886
- // Filter out products already assigned to this technology
887
- return allProducts.filter(product =>
888
- !product.assignedTechnologyIds?.includes(technologyId)
889
- );
890
- }
891
-
892
- /**
893
- * Gets product assignment statistics for a technology
894
- */
895
- async getProductStats(technologyId: string): Promise<{
896
- totalAssigned: number;
897
- byBrand: Record<string, number>;
898
- }> {
899
- const products = await this.getAssignedProducts(technologyId);
900
-
901
- const byBrand: Record<string, number> = {};
902
- products.forEach(product => {
903
- byBrand[product.brandName] = (byBrand[product.brandName] || 0) + 1;
904
- });
905
-
906
- return {
907
- totalAssigned: products.length,
908
- byBrand,
909
- };
910
- }
911
-
912
- /**
913
- * Updates products in technology subcollection when technology metadata changes
914
- * @param technologyId - ID of the technology
915
- * @param updates - Fields to update (categoryId, subcategoryId, technologyName)
916
- */
917
- private async updateProductsInSubcollection(
918
- technologyId: string,
919
- updates: { categoryId?: string; subcategoryId?: string; technologyName?: string }
920
- ): Promise<void> {
921
- const productsRef = collection(this.db, TECHNOLOGIES_COLLECTION, technologyId, PRODUCTS_COLLECTION);
922
- const productsSnapshot = await getDocs(productsRef);
923
-
924
- if (productsSnapshot.empty) {
925
- return;
926
- }
927
-
928
- const batch = writeBatch(this.db);
929
-
930
- for (const productDoc of productsSnapshot.docs) {
931
- const productRef = productDoc.ref;
932
- const updateFields: any = {};
933
-
934
- if (updates.categoryId !== undefined) {
935
- updateFields.categoryId = updates.categoryId;
936
- }
937
- if (updates.subcategoryId !== undefined) {
938
- updateFields.subcategoryId = updates.subcategoryId;
939
- }
940
- if (updates.technologyName !== undefined) {
941
- updateFields.technologyName = updates.technologyName;
942
- }
943
-
944
- if (Object.keys(updateFields).length > 0) {
945
- batch.update(productRef, updateFields);
946
- }
947
- }
948
-
949
- await batch.commit();
950
- }
951
-
952
- /**
953
- * Exports technologies to CSV string, suitable for Excel/Sheets.
954
- * Includes headers and optional UTF-8 BOM.
955
- * By default exports only active technologies (set includeInactive to true to export all).
956
- * Includes product names from subcollections.
957
- */
958
- async exportToCsv(options?: {
959
- includeInactive?: boolean;
960
- includeBom?: boolean;
961
- }): Promise<string> {
962
- const includeInactive = options?.includeInactive ?? false;
963
- const includeBom = options?.includeBom ?? true;
964
-
965
- const headers = [
966
- "id",
967
- "name",
968
- "description",
969
- "family",
970
- "categoryId",
971
- "subcategoryId",
972
- "technicalDetails",
973
- "requirements_pre",
974
- "requirements_post",
975
- "blockingConditions",
976
- "contraindications",
977
- "benefits",
978
- "certificationMinimumLevel",
979
- "certificationRequiredSpecialties",
980
- "documentationTemplateIds",
981
- "productNames",
982
- "isActive",
983
- ];
984
-
985
- const rows: string[] = [];
986
- rows.push(headers.map((h) => this.formatCsvValue(h)).join(","));
987
-
988
- const PAGE_SIZE = 1000;
989
- let cursor: any | undefined;
990
-
991
- // Build base constraints
992
- const constraints: QueryConstraint[] = [];
993
- if (!includeInactive) {
994
- constraints.push(where("isActive", "==", true));
995
- }
996
- constraints.push(orderBy("name"));
997
-
998
- // Page through all results
999
- // eslint-disable-next-line no-constant-condition
1000
- while (true) {
1001
- const queryConstraints: QueryConstraint[] = [...constraints, limit(PAGE_SIZE)];
1002
- if (cursor) queryConstraints.push(startAfter(cursor));
1003
-
1004
- const q = query(this.technologiesRef, ...queryConstraints);
1005
- const snapshot = await getDocs(q);
1006
- if (snapshot.empty) break;
1007
-
1008
- for (const d of snapshot.docs) {
1009
- const technology = ({ id: d.id, ...d.data() } as unknown) as Technology;
1010
- // Fetch products for this technology
1011
- const productNames = await this.getProductNamesForTechnology(technology.id!);
1012
- rows.push(this.technologyToCsvRow(technology, productNames));
1013
- }
1014
-
1015
- cursor = snapshot.docs[snapshot.docs.length - 1];
1016
- if (snapshot.size < PAGE_SIZE) break;
1017
- }
1018
-
1019
- const csvBody = rows.join("\r\n");
1020
- return includeBom ? "\uFEFF" + csvBody : csvBody;
1021
- }
1022
-
1023
- /**
1024
- * Gets product names from the technology's product subcollection
1025
- */
1026
- private async getProductNamesForTechnology(technologyId: string): Promise<string[]> {
1027
- try {
1028
- const productsRef = collection(this.db, TECHNOLOGIES_COLLECTION, technologyId, PRODUCTS_COLLECTION);
1029
- const q = query(productsRef, where("isActive", "==", true));
1030
- const snapshot = await getDocs(q);
1031
- return snapshot.docs.map(doc => {
1032
- const product = doc.data() as Product;
1033
- return product.name || "";
1034
- }).filter(name => name); // Filter out empty names
1035
- } catch (error) {
1036
- console.error(`Error fetching products for technology ${technologyId}:`, error);
1037
- return [];
1038
- }
1039
- }
1040
-
1041
- private technologyToCsvRow(technology: Technology, productNames: string[] = []): string {
1042
- const values = [
1043
- technology.id ?? "",
1044
- technology.name ?? "",
1045
- technology.description ?? "",
1046
- technology.family ?? "",
1047
- technology.categoryId ?? "",
1048
- technology.subcategoryId ?? "",
1049
- technology.technicalDetails ?? "",
1050
- technology.requirements?.pre?.map(r => r.name).join(";") ?? "",
1051
- technology.requirements?.post?.map(r => r.name).join(";") ?? "",
1052
- technology.blockingConditions?.join(";") ?? "",
1053
- technology.contraindications?.map(c => c.name).join(";") ?? "",
1054
- technology.benefits?.map(b => b.name).join(";") ?? "",
1055
- technology.certificationRequirement?.minimumLevel ?? "",
1056
- technology.certificationRequirement?.requiredSpecialties?.join(";") ?? "",
1057
- technology.documentationTemplates?.map(t => t.templateId).join(";") ?? "",
1058
- productNames.join(";"),
1059
- String(technology.isActive ?? ""),
1060
- ];
1061
- return values.map((v) => this.formatCsvValue(v)).join(",");
1062
- }
1063
-
1064
- private formatCsvValue(value: any): string {
1065
- const str = value === null || value === undefined ? "" : String(value);
1066
- // Escape double quotes by doubling them and wrap in quotes
1067
- const escaped = str.replace(/"/g, '""');
1068
- return `"${escaped}"`;
1069
- }
1070
- }
1
+ import {
2
+ addDoc,
3
+ collection,
4
+ doc,
5
+ DocumentData,
6
+ getCountFromServer,
7
+ getDoc,
8
+ getDocs,
9
+ limit,
10
+ orderBy,
11
+ query,
12
+ startAfter,
13
+ updateDoc,
14
+ where,
15
+ arrayUnion,
16
+ arrayRemove,
17
+ Firestore,
18
+ writeBatch,
19
+ QueryConstraint,
20
+ } from 'firebase/firestore';
21
+ import { Technology, TECHNOLOGIES_COLLECTION, ITechnologyService } from '../types/technology.types';
22
+ import { Requirement, RequirementType } from '../types/requirement.types';
23
+ import { BlockingCondition } from '../types/static/blocking-condition.types';
24
+ import { ContraindicationDynamic } from '../types/admin-constants.types';
25
+ import { TreatmentBenefitDynamic } from '../types/admin-constants.types';
26
+ import {
27
+ CertificationLevel,
28
+ CertificationSpecialty,
29
+ CertificationRequirement,
30
+ } from '../types/static/certification.types';
31
+ import { BaseService } from '../../services/base.service';
32
+ import { ProcedureFamily } from '../types/static/procedure-family.types';
33
+ import { Practitioner, PractitionerCertification } from '../../types/practitioner';
34
+ import { Product, PRODUCTS_COLLECTION } from '../types/product.types';
35
+
36
+ /**
37
+ * Default vrednosti za sertifikaciju
38
+ */
39
+ const DEFAULT_CERTIFICATION_REQUIREMENT: CertificationRequirement = {
40
+ minimumLevel: CertificationLevel.AESTHETICIAN,
41
+ requiredSpecialties: [],
42
+ };
43
+
44
+ /**
45
+ * Service for managing technologies.
46
+ */
47
+ export class TechnologyService extends BaseService implements ITechnologyService {
48
+ /**
49
+ * Reference to the Firestore collection of technologies.
50
+ */
51
+ private get technologiesRef() {
52
+ return collection(this.db, TECHNOLOGIES_COLLECTION);
53
+ }
54
+
55
+ /**
56
+ * Creates a new technology.
57
+ * @param technology - Data for the new technology.
58
+ * @returns The created technology with its generated ID.
59
+ */
60
+ async create(technology: Omit<Technology, 'id' | 'createdAt' | 'updatedAt'>) {
61
+ const now = new Date();
62
+ // Explicitly construct the object to ensure no undefined values are passed.
63
+ const newTechnology: Omit<Technology, 'id'> = {
64
+ name: technology.name,
65
+ description: technology.description,
66
+ family: technology.family,
67
+ categoryId: technology.categoryId,
68
+ subcategoryId: technology.subcategoryId,
69
+ requirements: technology.requirements || { pre: [], post: [] },
70
+ blockingConditions: technology.blockingConditions || [],
71
+ contraindications: technology.contraindications || [],
72
+ benefits: technology.benefits || [],
73
+ certificationRequirement:
74
+ technology.certificationRequirement || DEFAULT_CERTIFICATION_REQUIREMENT,
75
+ documentationTemplates: technology.documentationTemplates || [],
76
+ isActive: true,
77
+ createdAt: now,
78
+ updatedAt: now,
79
+ };
80
+
81
+ // Add optional fields only if they are not undefined
82
+ if (technology.technicalDetails) {
83
+ newTechnology.technicalDetails = technology.technicalDetails;
84
+ }
85
+
86
+ const docRef = await addDoc(this.technologiesRef, newTechnology as any);
87
+ return { id: docRef.id, ...newTechnology };
88
+ }
89
+
90
+ /**
91
+ * Returns counts of technologies for each subcategory.
92
+ * @param active - Whether to count active or inactive technologies.
93
+ * @returns A record mapping subcategory ID to technology count.
94
+ */
95
+ async getTechnologyCounts(active = true) {
96
+ const q = query(this.technologiesRef, where('isActive', '==', active));
97
+ const snapshot = await getDocs(q);
98
+ const counts: Record<string, number> = {};
99
+ snapshot.docs.forEach(doc => {
100
+ const tech = doc.data() as Technology;
101
+ counts[tech.subcategoryId] = (counts[tech.subcategoryId] || 0) + 1;
102
+ });
103
+ return counts;
104
+ }
105
+
106
+ /**
107
+ * Returns counts of technologies for each category.
108
+ * @param active - Whether to count active or inactive technologies.
109
+ * @returns A record mapping category ID to technology count.
110
+ */
111
+ async getTechnologyCountsByCategory(active = true) {
112
+ const q = query(this.technologiesRef, where('isActive', '==', active));
113
+ const snapshot = await getDocs(q);
114
+ const counts: Record<string, number> = {};
115
+ snapshot.docs.forEach(doc => {
116
+ const tech = doc.data() as Technology;
117
+ counts[tech.categoryId] = (counts[tech.categoryId] || 0) + 1;
118
+ });
119
+ return counts;
120
+ }
121
+
122
+ /**
123
+ * Returns all technologies with pagination.
124
+ * @param options - Pagination and filter options.
125
+ * @returns A list of technologies and the last visible document.
126
+ */
127
+ async getAll(
128
+ options: {
129
+ active?: boolean;
130
+ limit?: number;
131
+ lastVisible?: DocumentData;
132
+ } = {},
133
+ ) {
134
+ const { active = true, limit: queryLimit = 10, lastVisible } = options;
135
+ const constraints = [
136
+ where('isActive', '==', active),
137
+ orderBy('name'),
138
+ queryLimit ? limit(queryLimit) : undefined,
139
+ lastVisible ? startAfter(lastVisible) : undefined,
140
+ ].filter((c): c is NonNullable<typeof c> => !!c);
141
+
142
+ const q = query(this.technologiesRef, ...constraints);
143
+ const snapshot = await getDocs(q);
144
+ const technologies = snapshot.docs.map(
145
+ doc =>
146
+ ({
147
+ id: doc.id,
148
+ ...doc.data(),
149
+ } as Technology),
150
+ );
151
+ const newLastVisible = snapshot.docs[snapshot.docs.length - 1];
152
+ return { technologies, lastVisible: newLastVisible };
153
+ }
154
+
155
+ /**
156
+ * Returns all technologies for a specific category with pagination.
157
+ * @param categoryId - The ID of the category.
158
+ * @param options - Pagination options.
159
+ * @returns A list of technologies for the specified category.
160
+ */
161
+ async getAllByCategoryId(
162
+ categoryId: string,
163
+ options: {
164
+ active?: boolean;
165
+ limit?: number;
166
+ lastVisible?: DocumentData;
167
+ } = {},
168
+ ) {
169
+ const { active = true, limit: queryLimit = 10, lastVisible } = options;
170
+ const constraints = [
171
+ where('categoryId', '==', categoryId),
172
+ where('isActive', '==', active),
173
+ orderBy('name'),
174
+ queryLimit ? limit(queryLimit) : undefined,
175
+ lastVisible ? startAfter(lastVisible) : undefined,
176
+ ].filter((c): c is NonNullable<typeof c> => !!c);
177
+
178
+ const q = query(this.technologiesRef, ...constraints);
179
+ const snapshot = await getDocs(q);
180
+ const technologies = snapshot.docs.map(
181
+ doc =>
182
+ ({
183
+ id: doc.id,
184
+ ...doc.data(),
185
+ } as Technology),
186
+ );
187
+ const newLastVisible = snapshot.docs[snapshot.docs.length - 1];
188
+ return { technologies, lastVisible: newLastVisible };
189
+ }
190
+
191
+ /**
192
+ * Returns all technologies for a specific subcategory with pagination.
193
+ * @param subcategoryId - The ID of the subcategory.
194
+ * @param options - Pagination options.
195
+ * @returns A list of technologies for the specified subcategory.
196
+ */
197
+ async getAllBySubcategoryId(
198
+ subcategoryId: string,
199
+ options: {
200
+ active?: boolean;
201
+ limit?: number;
202
+ lastVisible?: DocumentData;
203
+ } = {},
204
+ ) {
205
+ const { active = true, limit: queryLimit = 10, lastVisible } = options;
206
+ const constraints = [
207
+ where('subcategoryId', '==', subcategoryId),
208
+ where('isActive', '==', active),
209
+ orderBy('name'),
210
+ queryLimit ? limit(queryLimit) : undefined,
211
+ lastVisible ? startAfter(lastVisible) : undefined,
212
+ ].filter((c): c is NonNullable<typeof c> => !!c);
213
+
214
+ const q = query(this.technologiesRef, ...constraints);
215
+ const snapshot = await getDocs(q);
216
+ const technologies = snapshot.docs.map(
217
+ doc =>
218
+ ({
219
+ id: doc.id,
220
+ ...doc.data(),
221
+ } as Technology),
222
+ );
223
+ const newLastVisible = snapshot.docs[snapshot.docs.length - 1];
224
+ return { technologies, lastVisible: newLastVisible };
225
+ }
226
+
227
+ /**
228
+ * Updates an existing technology.
229
+ * @param id - The ID of the technology to update.
230
+ * @param technology - New data for the technology.
231
+ * @returns The updated technology.
232
+ */
233
+ async update(id: string, technology: Partial<Omit<Technology, 'id' | 'createdAt'>>) {
234
+ const updateData: { [key: string]: any } = { ...technology };
235
+
236
+ // Remove undefined fields to prevent Firestore errors
237
+ Object.keys(updateData).forEach(key => {
238
+ if (updateData[key] === undefined) {
239
+ delete updateData[key];
240
+ }
241
+ });
242
+
243
+ updateData.updatedAt = new Date();
244
+
245
+ const docRef = doc(this.technologiesRef, id);
246
+
247
+ // Get the technology before update to check what changed
248
+ const beforeTech = await this.getById(id);
249
+
250
+ await updateDoc(docRef, updateData);
251
+
252
+ // If categoryId, subcategoryId, or name changed, update all products in subcollection
253
+ const categoryChanged = beforeTech && updateData.categoryId && beforeTech.categoryId !== updateData.categoryId;
254
+ const subcategoryChanged = beforeTech && updateData.subcategoryId && beforeTech.subcategoryId !== updateData.subcategoryId;
255
+ const nameChanged = beforeTech && updateData.name && beforeTech.name !== updateData.name;
256
+
257
+ if (categoryChanged || subcategoryChanged || nameChanged) {
258
+ await this.updateProductsInSubcollection(id, {
259
+ categoryId: updateData.categoryId,
260
+ subcategoryId: updateData.subcategoryId,
261
+ technologyName: updateData.name,
262
+ });
263
+ }
264
+
265
+ return this.getById(id);
266
+ }
267
+
268
+ /**
269
+ * Soft deletes a technology.
270
+ * @param id - The ID of the technology to delete.
271
+ */
272
+ async delete(id: string) {
273
+ await this.update(id, { isActive: false });
274
+ }
275
+
276
+ /**
277
+ * Reactivates a technology.
278
+ * @param id - The ID of the technology to reactivate.
279
+ */
280
+ async reactivate(id: string) {
281
+ await this.update(id, { isActive: true });
282
+ }
283
+
284
+ /**
285
+ * Returns a technology by its ID.
286
+ * @param id - The ID of the requested technology.
287
+ * @returns The technology or null if it doesn't exist.
288
+ */
289
+ async getById(id: string): Promise<Technology | null> {
290
+ const docRef = doc(this.technologiesRef, id);
291
+ const docSnap = await getDoc(docRef);
292
+ if (!docSnap.exists()) return null;
293
+ return {
294
+ id: docSnap.id,
295
+ ...docSnap.data(),
296
+ } as Technology;
297
+ }
298
+
299
+ /**
300
+ * Dodaje novi zahtev tehnologiji
301
+ * @param technologyId - ID tehnologije
302
+ * @param requirement - Zahtev koji se dodaje
303
+ * @returns Ažurirana tehnologija sa novim zahtevom
304
+ */
305
+ async addRequirement(technologyId: string, requirement: Requirement) {
306
+ const docRef = doc(this.technologiesRef, technologyId);
307
+
308
+ const requirementType = requirement.type === 'pre' ? 'requirements.pre' : 'requirements.post';
309
+
310
+ await updateDoc(docRef, {
311
+ [requirementType]: arrayUnion(requirement),
312
+ updatedAt: new Date(),
313
+ });
314
+
315
+ return this.getById(technologyId);
316
+ }
317
+
318
+ /**
319
+ * Uklanja zahtev iz tehnologije
320
+ * @param technologyId - ID tehnologije
321
+ * @param requirement - Zahtev koji se uklanja
322
+ * @returns Ažurirana tehnologija bez uklonjenog zahteva
323
+ */
324
+ async removeRequirement(technologyId: string, requirement: Requirement) {
325
+ const docRef = doc(this.technologiesRef, technologyId);
326
+
327
+ const requirementType = requirement.type === 'pre' ? 'requirements.pre' : 'requirements.post';
328
+
329
+ await updateDoc(docRef, {
330
+ [requirementType]: arrayRemove(requirement),
331
+ updatedAt: new Date(),
332
+ });
333
+
334
+ return this.getById(technologyId);
335
+ }
336
+
337
+ /**
338
+ * Vraća sve zahteve za tehnologiju
339
+ * @param technologyId - ID tehnologije
340
+ * @param type - Opcioni filter za tip zahteva (pre/post)
341
+ * @returns Lista zahteva
342
+ */
343
+ async getRequirements(technologyId: string, type?: RequirementType) {
344
+ const technology = await this.getById(technologyId);
345
+ if (!technology || !technology.requirements) return [];
346
+
347
+ if (type) {
348
+ return technology.requirements[type];
349
+ }
350
+
351
+ return [...technology.requirements.pre, ...technology.requirements.post];
352
+ }
353
+
354
+ /**
355
+ * Ažurira postojeći zahtev
356
+ * @param technologyId - ID tehnologije
357
+ * @param oldRequirement - Stari zahtev koji se menja
358
+ * @param newRequirement - Novi zahtev koji zamenjuje stari
359
+ * @returns Ažurirana tehnologija
360
+ */
361
+ async updateRequirement(
362
+ technologyId: string,
363
+ oldRequirement: Requirement,
364
+ newRequirement: Requirement,
365
+ ) {
366
+ await this.removeRequirement(technologyId, oldRequirement);
367
+ return this.addRequirement(technologyId, newRequirement);
368
+ }
369
+
370
+ /**
371
+ * Dodaje blokirajući uslov tehnologiji
372
+ * @param technologyId - ID tehnologije
373
+ * @param condition - Blokirajući uslov koji se dodaje
374
+ * @returns Ažurirana tehnologija
375
+ */
376
+ async addBlockingCondition(technologyId: string, condition: BlockingCondition) {
377
+ const docRef = doc(this.technologiesRef, technologyId);
378
+
379
+ await updateDoc(docRef, {
380
+ blockingConditions: arrayUnion(condition),
381
+ updatedAt: new Date(),
382
+ });
383
+
384
+ return this.getById(technologyId);
385
+ }
386
+
387
+ /**
388
+ * Uklanja blokirajući uslov iz tehnologije
389
+ * @param technologyId - ID tehnologije
390
+ * @param condition - Blokirajući uslov koji se uklanja
391
+ * @returns Ažurirana tehnologija
392
+ */
393
+ async removeBlockingCondition(technologyId: string, condition: BlockingCondition) {
394
+ const docRef = doc(this.technologiesRef, technologyId);
395
+
396
+ await updateDoc(docRef, {
397
+ blockingConditions: arrayRemove(condition),
398
+ updatedAt: new Date(),
399
+ });
400
+
401
+ return this.getById(technologyId);
402
+ }
403
+
404
+ /**
405
+ * Dodaje kontraindikaciju tehnologiji
406
+ * @param technologyId - ID tehnologije
407
+ * @param contraindication - Kontraindikacija koja se dodaje
408
+ * @returns Ažurirana tehnologija
409
+ */
410
+ async addContraindication(technologyId: string, contraindication: ContraindicationDynamic) {
411
+ const docRef = doc(this.technologiesRef, technologyId);
412
+ const technology = await this.getById(technologyId);
413
+ if (!technology) {
414
+ throw new Error(`Technology with id ${technologyId} not found`);
415
+ }
416
+
417
+ const existingContraindications = technology.contraindications || [];
418
+ if (existingContraindications.some(c => c.id === contraindication.id)) {
419
+ return technology; // Already exists, do nothing
420
+ }
421
+
422
+ await updateDoc(docRef, {
423
+ contraindications: [...existingContraindications, contraindication],
424
+ updatedAt: new Date(),
425
+ });
426
+
427
+ return this.getById(technologyId);
428
+ }
429
+
430
+ /**
431
+ * Uklanja kontraindikaciju iz tehnologije
432
+ * @param technologyId - ID tehnologije
433
+ * @param contraindication - Kontraindikacija koja se uklanja
434
+ * @returns Ažurirana tehnologija
435
+ */
436
+ async removeContraindication(technologyId: string, contraindication: ContraindicationDynamic) {
437
+ const docRef = doc(this.technologiesRef, technologyId);
438
+ const technology = await this.getById(technologyId);
439
+ if (!technology) {
440
+ throw new Error(`Technology with id ${technologyId} not found`);
441
+ }
442
+
443
+ const updatedContraindications = (technology.contraindications || []).filter(
444
+ c => c.id !== contraindication.id,
445
+ );
446
+
447
+ await updateDoc(docRef, {
448
+ contraindications: updatedContraindications,
449
+ updatedAt: new Date(),
450
+ });
451
+
452
+ return this.getById(technologyId);
453
+ }
454
+
455
+ /**
456
+ * Updates an existing contraindication in a technology's list.
457
+ * If the contraindication does not exist, it will not be added.
458
+ * @param technologyId - ID of the technology
459
+ * @param contraindication - The updated contraindication object
460
+ * @returns The updated technology
461
+ */
462
+ async updateContraindication(technologyId: string, contraindication: ContraindicationDynamic) {
463
+ const docRef = doc(this.technologiesRef, technologyId);
464
+ const technology = await this.getById(technologyId);
465
+ if (!technology) {
466
+ throw new Error(`Technology with id ${technologyId} not found`);
467
+ }
468
+
469
+ const contraindications = technology.contraindications || [];
470
+ const index = contraindications.findIndex(c => c.id === contraindication.id);
471
+
472
+ if (index === -1) {
473
+ // If contraindication doesn't exist, do not update
474
+ // Consider throwing an error if this is an unexpected state
475
+ console.warn(
476
+ `Contraindication with id ${contraindication.id} not found for technology ${technologyId}. No update performed.`,
477
+ );
478
+ return technology;
479
+ }
480
+
481
+ const updatedContraindications = [...contraindications];
482
+ updatedContraindications[index] = contraindication;
483
+
484
+ await updateDoc(docRef, {
485
+ contraindications: updatedContraindications,
486
+ updatedAt: new Date(),
487
+ });
488
+
489
+ return this.getById(technologyId);
490
+ }
491
+
492
+ /**
493
+ * Dodaje benefit tehnologiji
494
+ * @param technologyId - ID tehnologije
495
+ * @param benefit - Benefit koji se dodaje
496
+ * @returns Ažurirana tehnologija
497
+ */
498
+ async addBenefit(technologyId: string, benefit: TreatmentBenefitDynamic) {
499
+ const docRef = doc(this.technologiesRef, technologyId);
500
+ const technology = await this.getById(technologyId);
501
+ if (!technology) {
502
+ throw new Error(`Technology with id ${technologyId} not found`);
503
+ }
504
+
505
+ const existingBenefits = technology.benefits || [];
506
+ if (existingBenefits.some(b => b.id === benefit.id)) {
507
+ return technology; // Already exists, do nothing
508
+ }
509
+
510
+ await updateDoc(docRef, {
511
+ benefits: [...existingBenefits, benefit],
512
+ updatedAt: new Date(),
513
+ });
514
+
515
+ return this.getById(technologyId);
516
+ }
517
+
518
+ /**
519
+ * Uklanja benefit iz tehnologije
520
+ * @param technologyId - ID tehnologije
521
+ * @param benefit - Benefit koji se uklanja
522
+ * @returns Ažurirana tehnologija
523
+ */
524
+ async removeBenefit(technologyId: string, benefit: TreatmentBenefitDynamic) {
525
+ const docRef = doc(this.technologiesRef, technologyId);
526
+ const technology = await this.getById(technologyId);
527
+ if (!technology) {
528
+ throw new Error(`Technology with id ${technologyId} not found`);
529
+ }
530
+
531
+ const updatedBenefits = (technology.benefits || []).filter(b => b.id !== benefit.id);
532
+
533
+ await updateDoc(docRef, {
534
+ benefits: updatedBenefits,
535
+ updatedAt: new Date(),
536
+ });
537
+
538
+ return this.getById(technologyId);
539
+ }
540
+
541
+ /**
542
+ * Updates an existing benefit in a technology's list.
543
+ * If the benefit does not exist, it will not be added.
544
+ * @param technologyId - ID of the technology
545
+ * @param benefit - The updated benefit object
546
+ * @returns The updated technology
547
+ */
548
+ async updateBenefit(technologyId: string, benefit: TreatmentBenefitDynamic) {
549
+ const docRef = doc(this.technologiesRef, technologyId);
550
+ const technology = await this.getById(technologyId);
551
+ if (!technology) {
552
+ throw new Error(`Technology with id ${technologyId} not found`);
553
+ }
554
+
555
+ const benefits = technology.benefits || [];
556
+ const index = benefits.findIndex(b => b.id === benefit.id);
557
+
558
+ if (index === -1) {
559
+ // If benefit doesn't exist, do not update
560
+ console.warn(
561
+ `Benefit with id ${benefit.id} not found for technology ${technologyId}. No update performed.`,
562
+ );
563
+ return technology;
564
+ }
565
+
566
+ const updatedBenefits = [...benefits];
567
+ updatedBenefits[index] = benefit;
568
+
569
+ await updateDoc(docRef, {
570
+ benefits: updatedBenefits,
571
+ updatedAt: new Date(),
572
+ });
573
+
574
+ return this.getById(technologyId);
575
+ }
576
+
577
+ /**
578
+ * Vraća sve blokirajuće uslove za tehnologiju
579
+ * @param technologyId - ID tehnologije
580
+ * @returns Lista blokirajućih uslova
581
+ */
582
+ async getBlockingConditions(technologyId: string) {
583
+ const technology = await this.getById(technologyId);
584
+ return technology?.blockingConditions || [];
585
+ }
586
+
587
+ /**
588
+ * Vraća sve kontraindikacije za tehnologiju
589
+ * @param technologyId - ID tehnologije
590
+ * @returns Lista kontraindikacija
591
+ */
592
+ async getContraindications(technologyId: string) {
593
+ const technology = await this.getById(technologyId);
594
+ return technology?.contraindications || [];
595
+ }
596
+
597
+ /**
598
+ * Vraća sve benefite za tehnologiju
599
+ * @param technologyId - ID tehnologije
600
+ * @returns Lista benefita
601
+ */
602
+ async getBenefits(technologyId: string) {
603
+ const technology = await this.getById(technologyId);
604
+ return technology?.benefits || [];
605
+ }
606
+
607
+ /**
608
+ * Ažurira zahteve sertifikacije za tehnologiju
609
+ * @param technologyId - ID tehnologije
610
+ * @param certificationRequirement - Novi zahtevi sertifikacije
611
+ * @returns Ažurirana tehnologija
612
+ */
613
+ async updateCertificationRequirement(
614
+ technologyId: string,
615
+ certificationRequirement: CertificationRequirement,
616
+ ) {
617
+ const docRef = doc(this.technologiesRef, technologyId);
618
+
619
+ await updateDoc(docRef, {
620
+ certificationRequirement,
621
+ updatedAt: new Date(),
622
+ });
623
+
624
+ return this.getById(technologyId);
625
+ }
626
+
627
+ /**
628
+ * Vraća zahteve sertifikacije za tehnologiju
629
+ * @param technologyId - ID tehnologije
630
+ * @returns Zahtevi sertifikacije ili null ako tehnologija ne postoji
631
+ */
632
+ async getCertificationRequirement(
633
+ technologyId: string,
634
+ ): Promise<CertificationRequirement | null> {
635
+ const technology = await this.getById(technologyId);
636
+ return technology?.certificationRequirement || null;
637
+ }
638
+
639
+ /**
640
+ * Proverava da li doktor ima odgovarajuću sertifikaciju za izvođenje tehnologije
641
+ *
642
+ * @param requiredCertification - Zahtevana sertifikacija za tehnologiju
643
+ * @param practitionerCertification - Sertifikacija zdravstvenog radnika
644
+ * @returns true ako zdravstveni radnik ima odgovarajuću sertifikaciju, false ako nema
645
+ *
646
+ * @example
647
+ * const isValid = technologyService.validateCertification(
648
+ * {
649
+ * minimumLevel: CertificationLevel.DOCTOR,
650
+ * requiredSpecialties: [CertificationSpecialty.INJECTABLES]
651
+ * },
652
+ * {
653
+ * level: CertificationLevel.SPECIALIST,
654
+ * specialties: [CertificationSpecialty.INJECTABLES, CertificationSpecialty.LASER]
655
+ * }
656
+ * );
657
+ */
658
+ validateCertification(
659
+ requiredCertification: CertificationRequirement,
660
+ practitionerCertification: PractitionerCertification,
661
+ ): boolean {
662
+ // Provera nivoa sertifikacije
663
+ // Enum je definisan od najnižeg ka najvišem, pa možemo porediti brojeve
664
+ const doctorLevel = Object.values(CertificationLevel).indexOf(practitionerCertification.level);
665
+ const requiredLevel = Object.values(CertificationLevel).indexOf(
666
+ requiredCertification.minimumLevel,
667
+ );
668
+
669
+ // Doktor mora imati nivo koji je jednak ili viši od zahtevanog
670
+ if (doctorLevel < requiredLevel) return false;
671
+
672
+ // Provera specijalizacija
673
+ const requiredSpecialties = requiredCertification.requiredSpecialties || [];
674
+ if (requiredSpecialties.length > 0) {
675
+ // Doktor mora imati sve zahtevane specijalizacije
676
+ const doctorSpecialties = practitionerCertification.specialties;
677
+ const hasAllRequiredSpecialties = requiredSpecialties.every(requiredSpecialty =>
678
+ doctorSpecialties.includes(requiredSpecialty),
679
+ );
680
+
681
+ if (!hasAllRequiredSpecialties) return false;
682
+ }
683
+
684
+ return true;
685
+ }
686
+
687
+ /**
688
+ * Vraća sve tehnologije koje je zdravstveni radnik sertifikovan da izvodi
689
+ * zajedno sa listama dozvoljenih familija, kategorija i podkategorija
690
+ *
691
+ * @param practitioner - Profil zdravstvenog radnika
692
+ * @returns Objekat koji sadrži:
693
+ * - technologies: Lista tehnologija koje zdravstveni radnik može da izvodi
694
+ * - families: Lista familija procedura koje zdravstveni radnik može da izvodi
695
+ * - categories: Lista ID-eva kategorija koje zdravstveni radnik može da izvodi
696
+ * - subcategories: Lista ID-eva podkategorija koje zdravstveni radnik može da izvodi
697
+ *
698
+ * @example
699
+ * const practitioner = {
700
+ * certification: {
701
+ * level: CertificationLevel.DOCTOR,
702
+ * specialties: [CertificationSpecialty.INJECTABLES]
703
+ * }
704
+ * };
705
+ * const allowedTechnologies = await technologyService.getAllowedTechnologies(practitioner);
706
+ * console.log(allowedTechnologies.families); // [ProcedureFamily.AESTHETICS]
707
+ * console.log(allowedTechnologies.categories); // ["category1", "category2"]
708
+ * console.log(allowedTechnologies.subcategories); // ["subcategory1", "subcategory2"]
709
+ */
710
+ async getAllowedTechnologies(practitioner: Practitioner): Promise<{
711
+ technologies: Technology[];
712
+ families: ProcedureFamily[];
713
+ categories: string[];
714
+ subcategories: string[];
715
+ }> {
716
+ // Get all active technologies
717
+ const allTechnologies = await this.getAllForFilter();
718
+
719
+ // Filter technologies based on certification requirements
720
+ const allowedTechnologies = allTechnologies.filter(technology =>
721
+ this.validateCertification(technology.certificationRequirement, practitioner.certification),
722
+ );
723
+
724
+ // Extract unique families, categories, and subcategories
725
+ const families = [...new Set(allowedTechnologies.map(t => t.family))];
726
+ const categories = [...new Set(allowedTechnologies.map(t => t.categoryId))];
727
+ const subcategories = [...new Set(allowedTechnologies.map(t => t.subcategoryId))];
728
+
729
+ return {
730
+ technologies: allowedTechnologies,
731
+ families,
732
+ categories,
733
+ subcategories,
734
+ };
735
+ }
736
+
737
+ /**
738
+ * Gets all active technologies for a subcategory for filter dropdowns (by subcategory only).
739
+ * @param subcategoryId - The ID of the subcategory.
740
+ */
741
+ async getAllForFilterBySubcategory(subcategoryId: string): Promise<Technology[]> {
742
+ const q = query(
743
+ collection(this.db, TECHNOLOGIES_COLLECTION),
744
+ where('isActive', '==', true),
745
+ where('subcategoryId', '==', subcategoryId),
746
+ orderBy('name'),
747
+ );
748
+ const snapshot = await getDocs(q);
749
+ return snapshot.docs.map(
750
+ doc =>
751
+ ({
752
+ id: doc.id,
753
+ ...doc.data(),
754
+ } as Technology),
755
+ );
756
+ }
757
+
758
+ /**
759
+ * Gets all active technologies for a subcategory for filter dropdowns.
760
+ * @param categoryId - The ID of the parent category.
761
+ * @param subcategoryId - The ID of the subcategory.
762
+ */
763
+ async getAllForFilterBySubcategoryId(
764
+ categoryId: string,
765
+ subcategoryId: string,
766
+ ): Promise<Technology[]> {
767
+ const q = query(
768
+ collection(this.db, TECHNOLOGIES_COLLECTION),
769
+ where('isActive', '==', true),
770
+ where('categoryId', '==', categoryId),
771
+ where('subcategoryId', '==', subcategoryId),
772
+ orderBy('name'),
773
+ );
774
+ const snapshot = await getDocs(q);
775
+ return snapshot.docs.map(
776
+ doc =>
777
+ ({
778
+ id: doc.id,
779
+ ...doc.data(),
780
+ } as Technology),
781
+ );
782
+ }
783
+
784
+ /**
785
+ * Gets all active technologies for filter dropdowns.
786
+ */
787
+ async getAllForFilter(): Promise<Technology[]> {
788
+ const q = query(
789
+ collection(this.db, TECHNOLOGIES_COLLECTION),
790
+ where('isActive', '==', true),
791
+ orderBy('name'),
792
+ );
793
+ const snapshot = await getDocs(q);
794
+ return snapshot.docs.map(
795
+ doc =>
796
+ ({
797
+ id: doc.id,
798
+ ...doc.data(),
799
+ } as Technology),
800
+ );
801
+ }
802
+
803
+ // ==========================================
804
+ // NEW METHODS: Product assignment management
805
+ // ==========================================
806
+
807
+ /**
808
+ * Assigns multiple products to a technology
809
+ * Updates each product's assignedTechnologyIds array
810
+ */
811
+ async assignProducts(technologyId: string, productIds: string[]): Promise<void> {
812
+ const batch = writeBatch(this.db);
813
+
814
+ for (const productId of productIds) {
815
+ const productRef = doc(this.db, PRODUCTS_COLLECTION, productId);
816
+ batch.update(productRef, {
817
+ assignedTechnologyIds: arrayUnion(technologyId),
818
+ updatedAt: new Date(),
819
+ });
820
+ }
821
+
822
+ await batch.commit();
823
+ // Cloud Function will handle syncing to subcollections
824
+ }
825
+
826
+ /**
827
+ * Unassigns multiple products from a technology
828
+ * Updates each product's assignedTechnologyIds array
829
+ */
830
+ async unassignProducts(technologyId: string, productIds: string[]): Promise<void> {
831
+ const batch = writeBatch(this.db);
832
+
833
+ for (const productId of productIds) {
834
+ const productRef = doc(this.db, PRODUCTS_COLLECTION, productId);
835
+ batch.update(productRef, {
836
+ assignedTechnologyIds: arrayRemove(technologyId),
837
+ updatedAt: new Date(),
838
+ });
839
+ }
840
+
841
+ await batch.commit();
842
+ // Cloud Function will handle removing from subcollections
843
+ }
844
+
845
+ /**
846
+ * Gets products assigned to a specific technology
847
+ * Reads from top-level collection for immediate consistency (Cloud Functions may lag)
848
+ */
849
+ async getAssignedProducts(technologyId: string): Promise<Product[]> {
850
+ const q = query(
851
+ collection(this.db, PRODUCTS_COLLECTION),
852
+ where('assignedTechnologyIds', 'array-contains', technologyId),
853
+ where('isActive', '==', true),
854
+ orderBy('name'),
855
+ );
856
+ const snapshot = await getDocs(q);
857
+
858
+ return snapshot.docs.map(
859
+ doc =>
860
+ ({
861
+ id: doc.id,
862
+ ...doc.data(),
863
+ } as Product),
864
+ );
865
+ }
866
+
867
+ /**
868
+ * Gets products NOT assigned to a specific technology
869
+ */
870
+ async getUnassignedProducts(technologyId: string): Promise<Product[]> {
871
+ const q = query(
872
+ collection(this.db, PRODUCTS_COLLECTION),
873
+ where('isActive', '==', true),
874
+ orderBy('name'),
875
+ );
876
+ const snapshot = await getDocs(q);
877
+
878
+ const allProducts = snapshot.docs.map(
879
+ doc =>
880
+ ({
881
+ id: doc.id,
882
+ ...doc.data(),
883
+ } as Product),
884
+ );
885
+
886
+ // Filter out products already assigned to this technology
887
+ return allProducts.filter(product =>
888
+ !product.assignedTechnologyIds?.includes(technologyId)
889
+ );
890
+ }
891
+
892
+ /**
893
+ * Gets product assignment statistics for a technology
894
+ */
895
+ async getProductStats(technologyId: string): Promise<{
896
+ totalAssigned: number;
897
+ byBrand: Record<string, number>;
898
+ }> {
899
+ const products = await this.getAssignedProducts(technologyId);
900
+
901
+ const byBrand: Record<string, number> = {};
902
+ products.forEach(product => {
903
+ byBrand[product.brandName] = (byBrand[product.brandName] || 0) + 1;
904
+ });
905
+
906
+ return {
907
+ totalAssigned: products.length,
908
+ byBrand,
909
+ };
910
+ }
911
+
912
+ /**
913
+ * Updates products in technology subcollection when technology metadata changes
914
+ * @param technologyId - ID of the technology
915
+ * @param updates - Fields to update (categoryId, subcategoryId, technologyName)
916
+ */
917
+ private async updateProductsInSubcollection(
918
+ technologyId: string,
919
+ updates: { categoryId?: string; subcategoryId?: string; technologyName?: string }
920
+ ): Promise<void> {
921
+ const productsRef = collection(this.db, TECHNOLOGIES_COLLECTION, technologyId, PRODUCTS_COLLECTION);
922
+ const productsSnapshot = await getDocs(productsRef);
923
+
924
+ if (productsSnapshot.empty) {
925
+ return;
926
+ }
927
+
928
+ const batch = writeBatch(this.db);
929
+
930
+ for (const productDoc of productsSnapshot.docs) {
931
+ const productRef = productDoc.ref;
932
+ const updateFields: any = {};
933
+
934
+ if (updates.categoryId !== undefined) {
935
+ updateFields.categoryId = updates.categoryId;
936
+ }
937
+ if (updates.subcategoryId !== undefined) {
938
+ updateFields.subcategoryId = updates.subcategoryId;
939
+ }
940
+ if (updates.technologyName !== undefined) {
941
+ updateFields.technologyName = updates.technologyName;
942
+ }
943
+
944
+ if (Object.keys(updateFields).length > 0) {
945
+ batch.update(productRef, updateFields);
946
+ }
947
+ }
948
+
949
+ await batch.commit();
950
+ }
951
+
952
+ /**
953
+ * Exports technologies to CSV string, suitable for Excel/Sheets.
954
+ * Includes headers and optional UTF-8 BOM.
955
+ * By default exports only active technologies (set includeInactive to true to export all).
956
+ * Includes product names from subcollections.
957
+ */
958
+ async exportToCsv(options?: {
959
+ includeInactive?: boolean;
960
+ includeBom?: boolean;
961
+ }): Promise<string> {
962
+ const includeInactive = options?.includeInactive ?? false;
963
+ const includeBom = options?.includeBom ?? true;
964
+
965
+ const headers = [
966
+ "id",
967
+ "name",
968
+ "description",
969
+ "family",
970
+ "categoryId",
971
+ "subcategoryId",
972
+ "technicalDetails",
973
+ "requirements_pre",
974
+ "requirements_post",
975
+ "blockingConditions",
976
+ "contraindications",
977
+ "benefits",
978
+ "certificationMinimumLevel",
979
+ "certificationRequiredSpecialties",
980
+ "documentationTemplateIds",
981
+ "productNames",
982
+ "isActive",
983
+ ];
984
+
985
+ const rows: string[] = [];
986
+ rows.push(headers.map((h) => this.formatCsvValue(h)).join(","));
987
+
988
+ const PAGE_SIZE = 1000;
989
+ let cursor: any | undefined;
990
+
991
+ // Build base constraints
992
+ const constraints: QueryConstraint[] = [];
993
+ if (!includeInactive) {
994
+ constraints.push(where("isActive", "==", true));
995
+ }
996
+ constraints.push(orderBy("name"));
997
+
998
+ // Page through all results
999
+ // eslint-disable-next-line no-constant-condition
1000
+ while (true) {
1001
+ const queryConstraints: QueryConstraint[] = [...constraints, limit(PAGE_SIZE)];
1002
+ if (cursor) queryConstraints.push(startAfter(cursor));
1003
+
1004
+ const q = query(this.technologiesRef, ...queryConstraints);
1005
+ const snapshot = await getDocs(q);
1006
+ if (snapshot.empty) break;
1007
+
1008
+ for (const d of snapshot.docs) {
1009
+ const technology = ({ id: d.id, ...d.data() } as unknown) as Technology;
1010
+ // Fetch products for this technology
1011
+ const productNames = await this.getProductNamesForTechnology(technology.id!);
1012
+ rows.push(this.technologyToCsvRow(technology, productNames));
1013
+ }
1014
+
1015
+ cursor = snapshot.docs[snapshot.docs.length - 1];
1016
+ if (snapshot.size < PAGE_SIZE) break;
1017
+ }
1018
+
1019
+ const csvBody = rows.join("\r\n");
1020
+ return includeBom ? "\uFEFF" + csvBody : csvBody;
1021
+ }
1022
+
1023
+ /**
1024
+ * Gets product names from the technology's product subcollection
1025
+ */
1026
+ private async getProductNamesForTechnology(technologyId: string): Promise<string[]> {
1027
+ try {
1028
+ const productsRef = collection(this.db, TECHNOLOGIES_COLLECTION, technologyId, PRODUCTS_COLLECTION);
1029
+ const q = query(productsRef, where("isActive", "==", true));
1030
+ const snapshot = await getDocs(q);
1031
+ return snapshot.docs.map(doc => {
1032
+ const product = doc.data() as Product;
1033
+ return product.name || "";
1034
+ }).filter(name => name); // Filter out empty names
1035
+ } catch (error) {
1036
+ console.error(`Error fetching products for technology ${technologyId}:`, error);
1037
+ return [];
1038
+ }
1039
+ }
1040
+
1041
+ private technologyToCsvRow(technology: Technology, productNames: string[] = []): string {
1042
+ const values = [
1043
+ technology.id ?? "",
1044
+ technology.name ?? "",
1045
+ technology.description ?? "",
1046
+ technology.family ?? "",
1047
+ technology.categoryId ?? "",
1048
+ technology.subcategoryId ?? "",
1049
+ technology.technicalDetails ?? "",
1050
+ technology.requirements?.pre?.map(r => r.name).join(";") ?? "",
1051
+ technology.requirements?.post?.map(r => r.name).join(";") ?? "",
1052
+ technology.blockingConditions?.join(";") ?? "",
1053
+ technology.contraindications?.map(c => c.name).join(";") ?? "",
1054
+ technology.benefits?.map(b => b.name).join(";") ?? "",
1055
+ technology.certificationRequirement?.minimumLevel ?? "",
1056
+ technology.certificationRequirement?.requiredSpecialties?.join(";") ?? "",
1057
+ technology.documentationTemplates?.map(t => t.templateId).join(";") ?? "",
1058
+ productNames.join(";"),
1059
+ String(technology.isActive ?? ""),
1060
+ ];
1061
+ return values.map((v) => this.formatCsvValue(v)).join(",");
1062
+ }
1063
+
1064
+ private formatCsvValue(value: any): string {
1065
+ const str = value === null || value === undefined ? "" : String(value);
1066
+ // Escape double quotes by doubling them and wrap in quotes
1067
+ const escaped = str.replace(/"/g, '""');
1068
+ return `"${escaped}"`;
1069
+ }
1070
+ }