@blackcode_sa/metaestetics-api 1.12.65 → 1.12.67

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