@blackcode_sa/metaestetics-api 1.12.62 → 1.12.64

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