@blackcode_sa/metaestetics-api 1.12.64 → 1.12.66

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