@blackcode_sa/metaestetics-api 1.12.58 → 1.12.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. package/dist/admin/index.d.mts +36 -4
  2. package/dist/admin/index.d.ts +36 -4
  3. package/dist/admin/index.js +156 -28
  4. package/dist/admin/index.mjs +156 -28
  5. package/dist/index.d.mts +9 -1
  6. package/dist/index.d.ts +9 -1
  7. package/package.json +119 -119
  8. package/src/__mocks__/firstore.ts +10 -10
  9. package/src/admin/aggregation/README.md +79 -79
  10. package/src/admin/aggregation/appointment/README.md +128 -128
  11. package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +1844 -1689
  12. package/src/admin/aggregation/appointment/index.ts +1 -1
  13. package/src/admin/aggregation/clinic/README.md +52 -52
  14. package/src/admin/aggregation/clinic/clinic.aggregation.service.ts +703 -703
  15. package/src/admin/aggregation/clinic/index.ts +1 -1
  16. package/src/admin/aggregation/forms/README.md +13 -13
  17. package/src/admin/aggregation/forms/filled-forms.aggregation.service.ts +322 -322
  18. package/src/admin/aggregation/forms/index.ts +1 -1
  19. package/src/admin/aggregation/index.ts +8 -8
  20. package/src/admin/aggregation/patient/README.md +27 -27
  21. package/src/admin/aggregation/patient/index.ts +1 -1
  22. package/src/admin/aggregation/patient/patient.aggregation.service.ts +141 -141
  23. package/src/admin/aggregation/practitioner/README.md +42 -42
  24. package/src/admin/aggregation/practitioner/index.ts +1 -1
  25. package/src/admin/aggregation/practitioner/practitioner.aggregation.service.ts +433 -433
  26. package/src/admin/aggregation/practitioner-invite/index.ts +1 -1
  27. package/src/admin/aggregation/practitioner-invite/practitioner-invite.aggregation.service.ts +961 -961
  28. package/src/admin/aggregation/procedure/README.md +43 -43
  29. package/src/admin/aggregation/procedure/index.ts +1 -1
  30. package/src/admin/aggregation/procedure/procedure.aggregation.service.ts +702 -702
  31. package/src/admin/aggregation/reviews/index.ts +1 -1
  32. package/src/admin/aggregation/reviews/reviews.aggregation.service.ts +641 -641
  33. package/src/admin/booking/README.md +125 -125
  34. package/src/admin/booking/booking.admin.ts +1037 -1037
  35. package/src/admin/booking/booking.calculator.ts +712 -699
  36. package/src/admin/booking/booking.types.ts +59 -59
  37. package/src/admin/booking/index.ts +3 -3
  38. package/src/admin/booking/timezones-problem.md +185 -185
  39. package/src/admin/calendar/README.md +7 -7
  40. package/src/admin/calendar/calendar.admin.service.ts +345 -345
  41. package/src/admin/calendar/index.ts +1 -1
  42. package/src/admin/documentation-templates/document-manager.admin.ts +260 -260
  43. package/src/admin/documentation-templates/index.ts +1 -1
  44. package/src/admin/free-consultation/free-consultation-utils.admin.ts +148 -148
  45. package/src/admin/free-consultation/index.ts +1 -1
  46. package/src/admin/index.ts +75 -75
  47. package/src/admin/logger/index.ts +78 -78
  48. package/src/admin/mailing/README.md +95 -95
  49. package/src/admin/mailing/appointment/appointment.mailing.service.ts +732 -732
  50. package/src/admin/mailing/appointment/index.ts +1 -1
  51. package/src/admin/mailing/appointment/templates/patient/appointment-confirmed.html +40 -40
  52. package/src/admin/mailing/base.mailing.service.ts +208 -208
  53. package/src/admin/mailing/index.ts +3 -3
  54. package/src/admin/mailing/practitionerInvite/existing-practitioner-invite.mailing.ts +611 -611
  55. package/src/admin/mailing/practitionerInvite/index.ts +2 -2
  56. package/src/admin/mailing/practitionerInvite/practitionerInvite.mailing.ts +395 -395
  57. package/src/admin/mailing/practitionerInvite/templates/existing-practitioner-invitation.template.ts +155 -155
  58. package/src/admin/mailing/practitionerInvite/templates/invitation.template.ts +101 -101
  59. package/src/admin/mailing/practitionerInvite/templates/invite-accepted-notification.template.ts +228 -228
  60. package/src/admin/mailing/practitionerInvite/templates/invite-rejected-notification.template.ts +242 -242
  61. package/src/admin/notifications/index.ts +1 -1
  62. package/src/admin/notifications/notifications.admin.ts +710 -710
  63. package/src/admin/requirements/README.md +128 -128
  64. package/src/admin/requirements/index.ts +1 -1
  65. package/src/admin/requirements/patient-requirements.admin.service.ts +475 -475
  66. package/src/admin/users/index.ts +1 -1
  67. package/src/admin/users/user-profile.admin.ts +405 -405
  68. package/src/backoffice/constants/certification.constants.ts +13 -13
  69. package/src/backoffice/constants/index.ts +1 -1
  70. package/src/backoffice/errors/backoffice.errors.ts +181 -181
  71. package/src/backoffice/errors/index.ts +1 -1
  72. package/src/backoffice/expo-safe/README.md +26 -26
  73. package/src/backoffice/expo-safe/index.ts +41 -41
  74. package/src/backoffice/index.ts +5 -5
  75. package/src/backoffice/services/FIXES_README.md +102 -102
  76. package/src/backoffice/services/README.md +40 -40
  77. package/src/backoffice/services/brand.service.ts +256 -256
  78. package/src/backoffice/services/category.service.ts +318 -318
  79. package/src/backoffice/services/constants.service.ts +385 -385
  80. package/src/backoffice/services/documentation-template.service.ts +202 -202
  81. package/src/backoffice/services/index.ts +8 -8
  82. package/src/backoffice/services/migrate-products.ts +116 -116
  83. package/src/backoffice/services/product.service.ts +553 -553
  84. package/src/backoffice/services/requirement.service.ts +235 -235
  85. package/src/backoffice/services/subcategory.service.ts +395 -395
  86. package/src/backoffice/services/technology.service.ts +1070 -1070
  87. package/src/backoffice/types/README.md +12 -12
  88. package/src/backoffice/types/admin-constants.types.ts +69 -69
  89. package/src/backoffice/types/brand.types.ts +29 -29
  90. package/src/backoffice/types/category.types.ts +62 -62
  91. package/src/backoffice/types/documentation-templates.types.ts +28 -28
  92. package/src/backoffice/types/index.ts +10 -10
  93. package/src/backoffice/types/procedure-product.types.ts +38 -38
  94. package/src/backoffice/types/product.types.ts +240 -240
  95. package/src/backoffice/types/requirement.types.ts +63 -63
  96. package/src/backoffice/types/static/README.md +18 -18
  97. package/src/backoffice/types/static/blocking-condition.types.ts +21 -21
  98. package/src/backoffice/types/static/certification.types.ts +37 -37
  99. package/src/backoffice/types/static/contraindication.types.ts +19 -19
  100. package/src/backoffice/types/static/index.ts +6 -6
  101. package/src/backoffice/types/static/pricing.types.ts +16 -16
  102. package/src/backoffice/types/static/procedure-family.types.ts +14 -14
  103. package/src/backoffice/types/static/treatment-benefit.types.ts +22 -22
  104. package/src/backoffice/types/subcategory.types.ts +34 -34
  105. package/src/backoffice/types/technology.types.ts +161 -161
  106. package/src/backoffice/validations/index.ts +1 -1
  107. package/src/backoffice/validations/schemas.ts +163 -163
  108. package/src/config/__mocks__/firebase.ts +99 -99
  109. package/src/config/firebase.ts +78 -78
  110. package/src/config/index.ts +9 -9
  111. package/src/errors/auth.error.ts +6 -6
  112. package/src/errors/auth.errors.ts +200 -200
  113. package/src/errors/clinic.errors.ts +32 -32
  114. package/src/errors/firebase.errors.ts +47 -47
  115. package/src/errors/user.errors.ts +99 -99
  116. package/src/index.backup.ts +407 -407
  117. package/src/index.ts +6 -6
  118. package/src/locales/en.ts +31 -31
  119. package/src/recommender/admin/index.ts +1 -1
  120. package/src/recommender/admin/services/recommender.service.admin.ts +5 -5
  121. package/src/recommender/front/index.ts +1 -1
  122. package/src/recommender/front/services/onboarding.service.ts +5 -5
  123. package/src/recommender/front/services/recommender.service.ts +3 -3
  124. package/src/recommender/index.ts +1 -1
  125. package/src/services/PATIENTAUTH.MD +197 -197
  126. package/src/services/README.md +106 -106
  127. package/src/services/__tests__/auth/auth.mock.test.ts +17 -17
  128. package/src/services/__tests__/auth/auth.setup.ts +293 -293
  129. package/src/services/__tests__/auth.service.test.ts +346 -346
  130. package/src/services/__tests__/base.service.test.ts +77 -77
  131. package/src/services/__tests__/user.service.test.ts +528 -528
  132. package/src/services/appointment/README.md +17 -17
  133. package/src/services/appointment/appointment.service.ts +2082 -2082
  134. package/src/services/appointment/index.ts +1 -1
  135. package/src/services/appointment/utils/appointment.utils.ts +552 -552
  136. package/src/services/appointment/utils/extended-procedure.utils.ts +314 -314
  137. package/src/services/appointment/utils/form-initialization.utils.ts +225 -225
  138. package/src/services/appointment/utils/recommended-procedure.utils.ts +195 -195
  139. package/src/services/appointment/utils/zone-management.utils.ts +353 -353
  140. package/src/services/appointment/utils/zone-photo.utils.ts +152 -152
  141. package/src/services/auth/auth.service.ts +989 -989
  142. package/src/services/auth/auth.v2.service.ts +961 -961
  143. package/src/services/auth/index.ts +7 -7
  144. package/src/services/auth/utils/error.utils.ts +90 -90
  145. package/src/services/auth/utils/firebase.utils.ts +49 -49
  146. package/src/services/auth/utils/index.ts +21 -21
  147. package/src/services/auth/utils/practitioner.utils.ts +125 -125
  148. package/src/services/base.service.ts +41 -41
  149. package/src/services/calendar/calendar.service.ts +1077 -1077
  150. package/src/services/calendar/calendar.v2.service.ts +1683 -1683
  151. package/src/services/calendar/calendar.v3.service.ts +313 -313
  152. package/src/services/calendar/externalCalendar.service.ts +178 -178
  153. package/src/services/calendar/index.ts +5 -5
  154. package/src/services/calendar/synced-calendars.service.ts +743 -743
  155. package/src/services/calendar/utils/appointment.utils.ts +265 -265
  156. package/src/services/calendar/utils/calendar-event.utils.ts +646 -646
  157. package/src/services/calendar/utils/clinic.utils.ts +237 -237
  158. package/src/services/calendar/utils/docs.utils.ts +157 -157
  159. package/src/services/calendar/utils/google-calendar.utils.ts +697 -697
  160. package/src/services/calendar/utils/index.ts +8 -8
  161. package/src/services/calendar/utils/patient.utils.ts +198 -198
  162. package/src/services/calendar/utils/practitioner.utils.ts +221 -221
  163. package/src/services/calendar/utils/synced-calendar.utils.ts +472 -472
  164. package/src/services/clinic/README.md +204 -204
  165. package/src/services/clinic/__tests__/clinic-admin.service.test.ts +287 -287
  166. package/src/services/clinic/__tests__/clinic-group.service.test.ts +352 -352
  167. package/src/services/clinic/__tests__/clinic.service.test.ts +354 -354
  168. package/src/services/clinic/billing-transactions.service.ts +217 -217
  169. package/src/services/clinic/clinic-admin.service.ts +202 -202
  170. package/src/services/clinic/clinic-group.service.ts +310 -310
  171. package/src/services/clinic/clinic.service.ts +708 -708
  172. package/src/services/clinic/index.ts +5 -5
  173. package/src/services/clinic/practitioner-invite.service.ts +519 -519
  174. package/src/services/clinic/utils/admin.utils.ts +551 -551
  175. package/src/services/clinic/utils/clinic-group.utils.ts +646 -646
  176. package/src/services/clinic/utils/clinic.utils.ts +949 -949
  177. package/src/services/clinic/utils/filter.utils.d.ts +23 -23
  178. package/src/services/clinic/utils/filter.utils.ts +446 -446
  179. package/src/services/clinic/utils/index.ts +11 -11
  180. package/src/services/clinic/utils/photos.utils.ts +188 -188
  181. package/src/services/clinic/utils/search.utils.ts +84 -84
  182. package/src/services/clinic/utils/tag.utils.ts +124 -124
  183. package/src/services/documentation-templates/documentation-template.service.ts +537 -537
  184. package/src/services/documentation-templates/filled-document.service.ts +587 -587
  185. package/src/services/documentation-templates/index.ts +2 -2
  186. package/src/services/index.ts +13 -13
  187. package/src/services/media/index.ts +1 -1
  188. package/src/services/media/media.service.ts +418 -418
  189. package/src/services/notifications/__tests__/notification.service.test.ts +242 -242
  190. package/src/services/notifications/index.ts +1 -1
  191. package/src/services/notifications/notification.service.ts +215 -215
  192. package/src/services/patient/README.md +48 -48
  193. package/src/services/patient/To-Do.md +43 -43
  194. package/src/services/patient/__tests__/patient.service.test.ts +294 -294
  195. package/src/services/patient/index.ts +2 -2
  196. package/src/services/patient/patient.service.ts +883 -883
  197. package/src/services/patient/patientRequirements.service.ts +285 -285
  198. package/src/services/patient/utils/aesthetic-analysis.utils.ts +176 -176
  199. package/src/services/patient/utils/clinic.utils.ts +80 -80
  200. package/src/services/patient/utils/docs.utils.ts +142 -142
  201. package/src/services/patient/utils/index.ts +9 -9
  202. package/src/services/patient/utils/location.utils.ts +126 -126
  203. package/src/services/patient/utils/medical-stuff.utils.ts +143 -143
  204. package/src/services/patient/utils/medical.utils.ts +458 -458
  205. package/src/services/patient/utils/practitioner.utils.ts +260 -260
  206. package/src/services/patient/utils/profile.utils.ts +510 -510
  207. package/src/services/patient/utils/sensitive.utils.ts +260 -260
  208. package/src/services/patient/utils/token.utils.ts +211 -211
  209. package/src/services/practitioner/README.md +145 -145
  210. package/src/services/practitioner/index.ts +1 -1
  211. package/src/services/practitioner/practitioner.service.ts +1742 -1742
  212. package/src/services/procedure/README.md +163 -163
  213. package/src/services/procedure/index.ts +1 -1
  214. package/src/services/procedure/procedure.service.ts +1682 -1682
  215. package/src/services/reviews/index.ts +1 -1
  216. package/src/services/reviews/reviews.service.ts +636 -636
  217. package/src/services/user/index.ts +1 -1
  218. package/src/services/user/user.service.ts +489 -489
  219. package/src/services/user/user.v2.service.ts +466 -466
  220. package/src/types/appointment/index.ts +453 -453
  221. package/src/types/calendar/index.ts +258 -258
  222. package/src/types/calendar/synced-calendar.types.ts +66 -66
  223. package/src/types/clinic/index.ts +489 -489
  224. package/src/types/clinic/practitioner-invite.types.ts +91 -91
  225. package/src/types/clinic/preferences.types.ts +159 -159
  226. package/src/types/clinic/to-do +3 -3
  227. package/src/types/documentation-templates/index.ts +308 -308
  228. package/src/types/index.ts +44 -44
  229. package/src/types/notifications/README.md +77 -77
  230. package/src/types/notifications/index.ts +265 -265
  231. package/src/types/patient/aesthetic-analysis.types.ts +66 -66
  232. package/src/types/patient/allergies.ts +58 -58
  233. package/src/types/patient/index.ts +273 -273
  234. package/src/types/patient/medical-info.types.ts +152 -152
  235. package/src/types/patient/patient-requirements.ts +92 -81
  236. package/src/types/patient/token.types.ts +61 -61
  237. package/src/types/practitioner/index.ts +206 -206
  238. package/src/types/procedure/index.ts +181 -181
  239. package/src/types/profile/index.ts +39 -39
  240. package/src/types/reviews/index.ts +130 -130
  241. package/src/types/tz-lookup.d.ts +4 -4
  242. package/src/types/user/index.ts +38 -38
  243. package/src/utils/TIMESTAMPS.md +176 -176
  244. package/src/utils/TimestampUtils.ts +241 -241
  245. package/src/utils/index.ts +1 -1
  246. package/src/validations/appointment.schema.ts +574 -574
  247. package/src/validations/calendar.schema.ts +225 -225
  248. package/src/validations/clinic.schema.ts +493 -493
  249. package/src/validations/common.schema.ts +25 -25
  250. package/src/validations/documentation-templates/index.ts +1 -1
  251. package/src/validations/documentation-templates/template.schema.ts +220 -220
  252. package/src/validations/documentation-templates.schema.ts +10 -10
  253. package/src/validations/index.ts +20 -20
  254. package/src/validations/media.schema.ts +10 -10
  255. package/src/validations/notification.schema.ts +90 -90
  256. package/src/validations/patient/aesthetic-analysis.schema.ts +55 -55
  257. package/src/validations/patient/medical-info.schema.ts +125 -125
  258. package/src/validations/patient/patient-requirements.schema.ts +84 -75
  259. package/src/validations/patient/token.schema.ts +29 -29
  260. package/src/validations/patient.schema.ts +216 -216
  261. package/src/validations/practitioner.schema.ts +222 -222
  262. package/src/validations/procedure-product.schema.ts +41 -41
  263. package/src/validations/procedure.schema.ts +124 -124
  264. package/src/validations/profile-info.schema.ts +41 -41
  265. package/src/validations/reviews.schema.ts +189 -189
  266. package/src/validations/schemas.ts +104 -104
  267. package/src/validations/shared.schema.ts +78 -78
@@ -1,883 +1,883 @@
1
- import {
2
- doc,
3
- getDoc,
4
- writeBatch,
5
- updateDoc,
6
- arrayUnion,
7
- serverTimestamp,
8
- } from 'firebase/firestore';
9
- import { BaseService } from '../base.service';
10
- import { MediaService, MediaAccessLevel, MediaResource } from '../media/media.service';
11
- import {
12
- PatientProfile,
13
- PatientSensitiveInfo,
14
- PatientLocationInfo,
15
- CreatePatientProfileData,
16
- CreatePatientSensitiveInfoData,
17
- UpdatePatientSensitiveInfoData,
18
- CreatePatientLocationInfoData,
19
- UpdatePatientLocationInfoData,
20
- PatientMedicalInfo,
21
- CreatePatientMedicalInfoData,
22
- UpdateVitalStatsData,
23
- AddAllergyData,
24
- UpdateAllergyData,
25
- AddBlockingConditionData,
26
- UpdateBlockingConditionData,
27
- AddContraindicationData,
28
- UpdateContraindicationData,
29
- AddMedicationData,
30
- UpdateMedicationData,
31
- PatientDoctor,
32
- PatientClinic,
33
- SearchPatientsParams,
34
- RequesterInfo,
35
- PatientProfileForDoctor,
36
- CreateManualPatientData,
37
- } from '../../types/patient';
38
- import { Auth } from 'firebase/auth';
39
- import { Firestore } from 'firebase/firestore';
40
- import { FirebaseApp } from 'firebase/app';
41
- import { Timestamp } from 'firebase/firestore';
42
-
43
- // Importujemo utility funkcije
44
- import {
45
- createPatientProfileUtil,
46
- getPatientProfileUtil,
47
- getPatientProfileByUserRefUtil,
48
- addExpoTokenUtil,
49
- removeExpoTokenUtil,
50
- addPointsUtil,
51
- updatePatientProfileUtil,
52
- updatePatientProfileByUserRefUtil,
53
- searchPatientsUtil,
54
- getAllPatientsUtil,
55
- updatePatientLocationUtil,
56
- createLocationInfoUtil,
57
- getLocationInfoUtil,
58
- updateLocationInfoUtil,
59
- createSensitiveInfoUtil,
60
- getSensitiveInfoUtil,
61
- updateSensitiveInfoUtil,
62
- claimPatientSensitiveInfoUtil,
63
- createMedicalInfoUtil,
64
- getMedicalInfoUtil,
65
- updateVitalStatsUtil,
66
- addAllergyUtil,
67
- updateAllergyUtil,
68
- removeAllergyUtil,
69
- addBlockingConditionUtil,
70
- updateBlockingConditionUtil,
71
- removeBlockingConditionUtil,
72
- addContraindicationUtil,
73
- updateContraindicationUtil,
74
- removeContraindicationUtil,
75
- addMedicationUtil,
76
- updateMedicationUtil,
77
- removeMedicationUtil,
78
- getPatientDocRef,
79
- getSensitiveInfoDocRef,
80
- getLocationInfoDocRef,
81
- getMedicalInfoDocRef,
82
- addDoctorUtil,
83
- removeDoctorUtil,
84
- addClinicUtil,
85
- removeClinicUtil,
86
- getPatientsByPractitionerUtil,
87
- getPatientsByPractitionerWithDetailsUtil,
88
- getPatientsByClinicUtil,
89
- createPatientTokenUtil,
90
- validatePatientTokenUtil,
91
- markPatientTokenAsUsedUtil,
92
- getActiveInviteTokensByClinicUtil,
93
- getActiveInviteTokensByPatientUtil,
94
- } from './utils';
95
-
96
- import {
97
- getAestheticAnalysisUtil,
98
- createOrUpdateAestheticAnalysisUtil,
99
- } from './utils/aesthetic-analysis.utils';
100
-
101
- import {
102
- AestheticAnalysis,
103
- CreateAestheticAnalysisData,
104
- UpdateAestheticAnalysisData,
105
- } from '../../types/patient';
106
-
107
- import { CreatePatientTokenData, PatientToken } from '../../types/patient/token.types';
108
-
109
- export class PatientService extends BaseService {
110
- private mediaService: MediaService;
111
-
112
- constructor(db: Firestore, auth: Auth, app: FirebaseApp) {
113
- super(db, auth, app);
114
- this.mediaService = new MediaService(db, auth, app);
115
- }
116
-
117
- // Metode za rad sa profilom pacijenta
118
- async createPatientProfile(data: CreatePatientProfileData): Promise<PatientProfile> {
119
- return createPatientProfileUtil(this.db, data, () => this.generateId());
120
- }
121
-
122
- async getPatientProfile(patientId: string): Promise<PatientProfile | null> {
123
- return getPatientProfileUtil(this.db, patientId);
124
- }
125
-
126
- /**
127
- * Manually creates a new patient profile, typically initiated by a clinic admin.
128
- * This creates a patient record that is not initially linked to an authenticated user.
129
- *
130
- * @param {CreateManualPatientData} data - The data for the new patient.
131
- * @param {RequesterInfo} requester - Information about the user creating the patient (must be a clinic admin).
132
- * @returns {Promise<PatientProfile>} The newly created patient profile.
133
- * @throws {Error} If the requester is not a valid clinic admin.
134
- */
135
- async createManualPatient(
136
- data: CreateManualPatientData,
137
- requester: RequesterInfo,
138
- ): Promise<PatientProfile> {
139
- console.log(
140
- `[PatientService.createManualPatient] Attempting to create manual patient by requester:`,
141
- requester,
142
- );
143
-
144
- // Security Check: Ensure the requester is a clinic admin
145
- if (
146
- requester.role !== 'clinic_admin' ||
147
- !requester.associatedClinicId ||
148
- requester.associatedClinicId !== data.clinicId
149
- ) {
150
- throw new Error(
151
- 'Unauthorized: Requester must be a clinic admin and can only add patients to their own clinic.',
152
- );
153
- }
154
-
155
- const patientId = this.generateId();
156
- const batch = writeBatch(this.db);
157
- const now = Timestamp.now();
158
-
159
- // 1. Create Patient Profile
160
- const patientProfileRef = getPatientDocRef(this.db, patientId);
161
- const newProfile: PatientProfile = {
162
- id: patientId,
163
- displayName: `${data.firstName} ${data.lastName.charAt(0)}.`,
164
- expoTokens: [],
165
- gamification: { level: 1, points: 0 },
166
- isActive: true,
167
- isVerified: false, // Manual profiles are not verified by default
168
- isManual: true,
169
- doctors: [],
170
- clinics: [
171
- {
172
- clinicId: data.clinicId,
173
- assignedAt: now,
174
- assignedBy: requester.id,
175
- isActive: true,
176
- notes: data.notes,
177
- },
178
- ],
179
- doctorIds: [],
180
- clinicIds: [data.clinicId],
181
- createdAt: now,
182
- updatedAt: now,
183
- phoneNumber: data.phoneNumber,
184
- dateOfBirth: data.dateOfBirth,
185
- };
186
- batch.set(patientProfileRef, newProfile);
187
-
188
- // 2. Create Patient Sensitive Info
189
- const sensitiveInfoRef = getSensitiveInfoDocRef(this.db, patientId);
190
- const newSensitiveInfo: Omit<PatientSensitiveInfo, 'photoUrl'> = {
191
- patientId,
192
- firstName: data.firstName,
193
- lastName: data.lastName,
194
- dateOfBirth: data.dateOfBirth,
195
- gender: data.gender,
196
- email: data.email,
197
- phoneNumber: data.phoneNumber,
198
- addressData: data.addressData,
199
- emergencyContacts: [],
200
- createdAt: now,
201
- updatedAt: now,
202
- };
203
- batch.set(sensitiveInfoRef, newSensitiveInfo);
204
-
205
- // 3. Create Patient Medical Info
206
- const medicalInfoRef = getMedicalInfoDocRef(this.db, patientId);
207
- const newMedicalInfo: PatientMedicalInfo = {
208
- patientId,
209
- vitalStats: {},
210
- blockingConditions: [],
211
- contraindications: [],
212
- allergies: [],
213
- currentMedications: [],
214
- emergencyNotes: '',
215
- lastUpdated: now,
216
- updatedBy: requester.id, // The admin who created the record
217
- };
218
- batch.set(medicalInfoRef, newMedicalInfo);
219
-
220
- await batch.commit();
221
-
222
- console.log(
223
- `[PatientService.createManualPatient] Successfully created manual patient with ID: ${patientId}`,
224
- );
225
-
226
- return newProfile;
227
- }
228
-
229
- async getPatientProfileByUserRef(userRef: string): Promise<PatientProfile | null> {
230
- return getPatientProfileByUserRefUtil(this.db, userRef);
231
- }
232
-
233
- // Metode za rad sa lokacijskim podacima
234
- async updatePatientLocation(
235
- patientId: string,
236
- latitude: number,
237
- longitude: number,
238
- ): Promise<void> {
239
- await updatePatientLocationUtil(this.db, patientId, latitude, longitude);
240
- }
241
-
242
- async updatePatientLocationByUserRef(
243
- userRef: string,
244
- latitude: number,
245
- longitude: number,
246
- ): Promise<void> {
247
- const profile = await this.getPatientProfileByUserRef(userRef);
248
- if (!profile) throw new Error('Patient profile not found');
249
- await this.updatePatientLocation(profile.id, latitude, longitude);
250
- }
251
-
252
- async createLocationInfo(
253
- data: CreatePatientLocationInfoData,
254
- requesterId: string,
255
- ): Promise<PatientLocationInfo> {
256
- return createLocationInfoUtil(this.db, data, requesterId);
257
- }
258
-
259
- async getLocationInfo(
260
- patientId: string,
261
- requesterId: string,
262
- ): Promise<PatientLocationInfo | null> {
263
- return getLocationInfoUtil(this.db, patientId, requesterId);
264
- }
265
-
266
- async getLocationInfoByUserRef(
267
- userRef: string,
268
- requesterId: string,
269
- ): Promise<PatientLocationInfo | null> {
270
- const profile = await this.getPatientProfileByUserRef(userRef);
271
- if (!profile) return null;
272
- return this.getLocationInfo(profile.id, requesterId);
273
- }
274
-
275
- async updateLocationInfo(
276
- patientId: string,
277
- data: UpdatePatientLocationInfoData,
278
- requesterId: string,
279
- ): Promise<PatientLocationInfo> {
280
- return updateLocationInfoUtil(this.db, patientId, data, requesterId);
281
- }
282
-
283
- // Metode za rad sa osetljivim informacijama
284
- async createSensitiveInfo(
285
- data: CreatePatientSensitiveInfoData,
286
- requesterUserId: string,
287
- ): Promise<PatientSensitiveInfo> {
288
- const currentUser = await this.getCurrentUser();
289
- if (currentUser.uid !== requesterUserId) {
290
- throw new Error('Requester does not match authenticated user.');
291
- }
292
-
293
- return createSensitiveInfoUtil(
294
- this.db,
295
- data,
296
- requesterUserId,
297
- currentUser.roles,
298
- this.mediaService,
299
- );
300
- }
301
-
302
- async getSensitiveInfo(
303
- patientId: string,
304
- requesterUserId: string,
305
- ): Promise<PatientSensitiveInfo | null> {
306
- const currentUser = await this.getCurrentUser();
307
- if (currentUser.uid !== requesterUserId) {
308
- // Allow for read-only access if authorized, but for now we check identity
309
- // This could be expanded later based on practitioner/admin roles
310
- }
311
- return getSensitiveInfoUtil(this.db, patientId, requesterUserId, currentUser.roles);
312
- }
313
-
314
- async getSensitiveInfoByUserRef(
315
- userRef: string,
316
- requesterUserId: string,
317
- ): Promise<PatientSensitiveInfo | null> {
318
- const profile = await this.getPatientProfileByUserRef(userRef);
319
- if (!profile) return null;
320
- // We pass requesterUserId which is the UID of the one asking.
321
- return this.getSensitiveInfo(profile.id, requesterUserId);
322
- }
323
-
324
- async updateSensitiveInfo(
325
- patientId: string,
326
- data: UpdatePatientSensitiveInfoData,
327
- requesterUserId: string,
328
- ): Promise<PatientSensitiveInfo> {
329
- const currentUser = await this.getCurrentUser();
330
- if (currentUser.uid !== requesterUserId) {
331
- throw new Error('Requester does not match authenticated user.');
332
- }
333
- return updateSensitiveInfoUtil(
334
- this.db,
335
- patientId,
336
- data,
337
- requesterUserId,
338
- currentUser.roles,
339
- this.mediaService,
340
- );
341
- }
342
-
343
- async claimPatientSensitiveInfo(
344
- patientId: string,
345
- userId: string,
346
- ): Promise<PatientSensitiveInfo> {
347
- return claimPatientSensitiveInfoUtil(this.db, patientId, userId);
348
- }
349
-
350
- // Metode za rad sa medicinskim informacijama
351
- async createMedicalInfo(patientId: string, data: CreatePatientMedicalInfoData): Promise<void> {
352
- const currentUser = await this.getCurrentUser();
353
- await createMedicalInfoUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
354
- }
355
-
356
- async getMedicalInfo(patientId: string): Promise<PatientMedicalInfo> {
357
- const currentUser = await this.getCurrentUser();
358
- return getMedicalInfoUtil(this.db, patientId, currentUser.uid, currentUser.roles);
359
- }
360
-
361
- async getMedicalInfoByUserRef(userRef: string): Promise<PatientMedicalInfo> {
362
- const profile = await this.getPatientProfileByUserRef(userRef);
363
- if (!profile) throw new Error('Patient profile not found');
364
- return this.getMedicalInfo(profile.id);
365
- }
366
-
367
- // Metode za rad sa vitalnim statistikama
368
- async updateVitalStats(patientId: string, data: UpdateVitalStatsData): Promise<void> {
369
- const currentUser = await this.getCurrentUser();
370
- await updateVitalStatsUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
371
- }
372
-
373
- // Metode za rad sa alergijama
374
- async addAllergy(patientId: string, data: AddAllergyData): Promise<void> {
375
- const currentUser = await this.getCurrentUser();
376
- await addAllergyUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
377
- }
378
-
379
- async updateAllergy(patientId: string, data: UpdateAllergyData): Promise<void> {
380
- const currentUser = await this.getCurrentUser();
381
- await updateAllergyUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
382
- }
383
-
384
- async removeAllergy(patientId: string, allergyIndex: number): Promise<void> {
385
- const currentUser = await this.getCurrentUser();
386
- await removeAllergyUtil(this.db, patientId, allergyIndex, currentUser.uid, currentUser.roles);
387
- }
388
-
389
- // Metode za rad sa blocking conditions
390
- async addBlockingCondition(patientId: string, data: AddBlockingConditionData): Promise<void> {
391
- const currentUser = await this.getCurrentUser();
392
- await addBlockingConditionUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
393
- }
394
-
395
- async updateBlockingCondition(
396
- patientId: string,
397
- data: UpdateBlockingConditionData,
398
- ): Promise<void> {
399
- const currentUser = await this.getCurrentUser();
400
- await updateBlockingConditionUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
401
- }
402
-
403
- async removeBlockingCondition(patientId: string, conditionIndex: number): Promise<void> {
404
- const currentUser = await this.getCurrentUser();
405
- await removeBlockingConditionUtil(
406
- this.db,
407
- patientId,
408
- conditionIndex,
409
- currentUser.uid,
410
- currentUser.roles,
411
- );
412
- }
413
-
414
- // Metode za rad sa kontraindikacijama
415
- async addContraindication(patientId: string, data: AddContraindicationData): Promise<void> {
416
- const currentUser = await this.getCurrentUser();
417
- await addContraindicationUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
418
- }
419
-
420
- async updateContraindication(patientId: string, data: UpdateContraindicationData): Promise<void> {
421
- const currentUser = await this.getCurrentUser();
422
- await updateContraindicationUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
423
- }
424
-
425
- async removeContraindication(patientId: string, contraindicationIndex: number): Promise<void> {
426
- const currentUser = await this.getCurrentUser();
427
- await removeContraindicationUtil(
428
- this.db,
429
- patientId,
430
- contraindicationIndex,
431
- currentUser.uid,
432
- currentUser.roles,
433
- );
434
- }
435
-
436
- // Metode za rad sa medikacijama
437
- async addMedication(patientId: string, data: AddMedicationData): Promise<void> {
438
- const currentUser = await this.getCurrentUser();
439
- await addMedicationUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
440
- }
441
-
442
- async updateMedication(patientId: string, data: UpdateMedicationData): Promise<void> {
443
- const currentUser = await this.getCurrentUser();
444
- await updateMedicationUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
445
- }
446
-
447
- async removeMedication(patientId: string, medicationIndex: number): Promise<void> {
448
- const currentUser = await this.getCurrentUser();
449
- await removeMedicationUtil(
450
- this.db,
451
- patientId,
452
- medicationIndex,
453
- currentUser.uid,
454
- currentUser.roles,
455
- );
456
- }
457
-
458
- // Pomoćne metode
459
- async addExpoToken(patientId: string, token: string): Promise<void> {
460
- await addExpoTokenUtil(this.db, patientId, token);
461
- }
462
-
463
- async addExpoTokenByUserRef(userRef: string, token: string): Promise<void> {
464
- const profile = await this.getPatientProfileByUserRef(userRef);
465
- if (!profile) throw new Error('Patient profile not found');
466
- await this.addExpoToken(profile.id, token);
467
- }
468
-
469
- async removeExpoToken(patientId: string, token: string): Promise<void> {
470
- await removeExpoTokenUtil(this.db, patientId, token);
471
- }
472
-
473
- async removeExpoTokenByUserRef(userRef: string, token: string): Promise<void> {
474
- const profile = await this.getPatientProfileByUserRef(userRef);
475
- if (!profile) throw new Error('Patient profile not found');
476
- await this.removeExpoToken(profile.id, token);
477
- }
478
-
479
- async addPoints(patientId: string, points: number): Promise<void> {
480
- await addPointsUtil(this.db, patientId, points);
481
- }
482
-
483
- async addPointsByUserRef(userRef: string, points: number): Promise<void> {
484
- const profile = await this.getPatientProfileByUserRef(userRef);
485
- if (!profile) throw new Error('Patient profile not found');
486
- await this.addPoints(profile.id, points);
487
- }
488
-
489
- private async getCurrentUser(): Promise<any> {
490
- if (!this.auth.currentUser) {
491
- throw new Error('No authenticated user');
492
- }
493
- const userDoc = await getDoc(doc(this.db, 'users', this.auth.currentUser.uid));
494
- if (!userDoc.exists()) {
495
- throw new Error('User not found');
496
- }
497
- return userDoc.data();
498
- }
499
-
500
- /**
501
- * Briše profil pacijenta i sve povezane subkolekcije
502
- */
503
- async deletePatientProfile(patientId: string): Promise<void> {
504
- const batch = writeBatch(this.db);
505
-
506
- // Brisanje sensitive info
507
- batch.delete(getSensitiveInfoDocRef(this.db, patientId));
508
-
509
- // Brisanje location info
510
- batch.delete(getLocationInfoDocRef(this.db, patientId));
511
-
512
- // Brisanje medical info
513
- batch.delete(getMedicalInfoDocRef(this.db, patientId));
514
-
515
- // Brisanje glavnog profila
516
- batch.delete(getPatientDocRef(this.db, patientId));
517
-
518
- await batch.commit();
519
- }
520
-
521
- // Metode za rad sa doktorima
522
- async addDoctor(patientId: string, doctorRef: string): Promise<void> {
523
- const currentUser = await this.getCurrentUser();
524
- await addDoctorUtil(this.db, patientId, doctorRef, currentUser.uid);
525
- }
526
-
527
- async removeDoctor(patientId: string, doctorRef: string): Promise<void> {
528
- await removeDoctorUtil(this.db, patientId, doctorRef);
529
- }
530
-
531
- // Metode za rad sa klinikama
532
- async addClinic(patientId: string, clinicId: string): Promise<void> {
533
- const currentUser = await this.getCurrentUser();
534
- await addClinicUtil(this.db, patientId, clinicId, currentUser.uid);
535
- }
536
-
537
- async removeClinic(patientId: string, clinicId: string): Promise<void> {
538
- await removeClinicUtil(this.db, patientId, clinicId);
539
- }
540
-
541
- // Metode za rad sa profilnom slikom
542
- /**
543
- * Uploads a profile photo for a patient
544
- * @param patientId - ID of the patient
545
- * @param file - File or Blob to upload
546
- * @returns URL of the uploaded photo
547
- */
548
- async uploadProfilePhoto(patientId: string, file: File | Blob): Promise<string> {
549
- console.log(`[PatientService] Uploading profile photo for patient ${patientId}`);
550
-
551
- const mediaMetadata = await this.mediaService.uploadMedia(
552
- file,
553
- patientId, // Using patientId as ownerId
554
- MediaAccessLevel.PRIVATE, // Profile photos should be private
555
- 'patient_profile_photos',
556
- file instanceof File ? file.name : `profile_photo_${patientId}`,
557
- );
558
-
559
- // Update the patient sensitive info with the new photo URL
560
- await updateDoc(getSensitiveInfoDocRef(this.db, patientId), {
561
- photoUrl: mediaMetadata.url,
562
- updatedAt: serverTimestamp(),
563
- });
564
-
565
- return mediaMetadata.url;
566
- }
567
-
568
- /**
569
- * Updates a patient's profile photo (replaces existing one)
570
- * @param patientId - ID of the patient
571
- * @param file - New file or Blob to upload
572
- * @returns URL of the new uploaded photo
573
- */
574
- async updateProfilePhoto(patientId: string, file: File | Blob): Promise<string> {
575
- console.log(`[PatientService] Updating profile photo for patient ${patientId}`);
576
-
577
- // Get current patient sensitive info to check for existing photo
578
- const currentUser = await this.getCurrentUser();
579
- const currentSensitiveInfo = await this.getSensitiveInfo(patientId, currentUser.uid);
580
-
581
- // Delete old photo if it exists and is managed by our MediaService
582
- if (currentSensitiveInfo?.photoUrl && typeof currentSensitiveInfo.photoUrl === 'string') {
583
- try {
584
- const existingMediaMetadata = await this.mediaService.getMediaMetadataByUrl(
585
- currentSensitiveInfo.photoUrl,
586
- );
587
- if (existingMediaMetadata) {
588
- await this.mediaService.deleteMedia(existingMediaMetadata.id);
589
- }
590
- } catch (error) {
591
- console.warn(
592
- `[PatientService] Could not delete old profile photo for patient ${patientId}:`,
593
- error,
594
- );
595
- // Continue with upload even if deletion fails
596
- }
597
- }
598
-
599
- // Upload new photo
600
- return this.uploadProfilePhoto(patientId, file);
601
- }
602
-
603
- /**
604
- * Deletes a patient's profile photo
605
- * @param patientId - ID of the patient
606
- */
607
- async deleteProfilePhoto(patientId: string): Promise<void> {
608
- console.log(`[PatientService] Deleting profile photo for patient ${patientId}`);
609
-
610
- // Get current patient sensitive info to find the photo URL
611
- const currentUser = await this.getCurrentUser();
612
- const currentSensitiveInfo = await this.getSensitiveInfo(patientId, currentUser.uid);
613
-
614
- if (currentSensitiveInfo?.photoUrl && typeof currentSensitiveInfo.photoUrl === 'string') {
615
- try {
616
- const existingMediaMetadata = await this.mediaService.getMediaMetadataByUrl(
617
- currentSensitiveInfo.photoUrl,
618
- );
619
- if (existingMediaMetadata) {
620
- await this.mediaService.deleteMedia(existingMediaMetadata.id);
621
- }
622
- } catch (error) {
623
- console.warn(
624
- `[PatientService] Could not delete profile photo for patient ${patientId}:`,
625
- error,
626
- );
627
- }
628
-
629
- // Remove photo URL from patient sensitive info
630
- await updateDoc(getSensitiveInfoDocRef(this.db, patientId), {
631
- photoUrl: null,
632
- updatedAt: serverTimestamp(),
633
- });
634
- }
635
- }
636
-
637
- /**
638
- * Handles profile photo upload for patients (supports MediaResource)
639
- * @param photoUrl - MediaResource (File, Blob, or URL string) from CreatePatientSensitiveInfoData
640
- * @param patientId - ID of the patient
641
- * @returns URL string of the uploaded or existing photo
642
- */
643
- private async handleProfilePhotoUpload(
644
- photoUrl: MediaResource | undefined,
645
- patientId: string,
646
- ): Promise<string | undefined> {
647
- if (!photoUrl) {
648
- return undefined;
649
- }
650
-
651
- // If it's already a URL string, return it as is
652
- if (typeof photoUrl === 'string') {
653
- return photoUrl;
654
- }
655
-
656
- // If it's a File or Blob, upload it
657
- if (photoUrl instanceof File || photoUrl instanceof Blob) {
658
- return this.uploadProfilePhoto(patientId, photoUrl);
659
- }
660
-
661
- return undefined;
662
- }
663
-
664
- // Metode za ažuriranje profila
665
- async updatePatientProfile(
666
- patientId: string,
667
- data: Partial<Omit<PatientProfile, 'id' | 'createdAt' | 'updatedAt'>>,
668
- ): Promise<PatientProfile> {
669
- return updatePatientProfileUtil(this.db, patientId, data);
670
- }
671
-
672
- async updatePatientProfileByUserRef(
673
- userRef: string,
674
- data: Partial<Omit<PatientProfile, 'id' | 'createdAt' | 'updatedAt'>>,
675
- ): Promise<PatientProfile> {
676
- return updatePatientProfileByUserRefUtil(this.db, userRef, data);
677
- }
678
-
679
- /**
680
- * Searches for patient profiles based on clinic/practitioner association.
681
- * Requires information about the requester for security checks.
682
- *
683
- * @param {SearchPatientsParams} params - The search criteria (clinicId, practitionerId).
684
- * @param {RequesterInfo} requester - Information about the user performing the search (ID, role, associated IDs).
685
- * @returns {Promise<PatientProfile[]>} A promise resolving to an array of matching patient profiles.
686
- */
687
- async searchPatients(
688
- params: SearchPatientsParams,
689
- requester: RequesterInfo,
690
- ): Promise<PatientProfile[]> {
691
- // We can potentially add more service-level logic here in the future,
692
- // like fetching additional data or enriching the results.
693
- // For now, we delegate directly to the utility function.
694
- console.log(
695
- `[PatientService.searchPatients] Initiating search with params:`,
696
- params,
697
- `by requester:`,
698
- requester,
699
- );
700
-
701
- // The utility function already handles validation and security checks.
702
- return searchPatientsUtil(this.db, params, requester);
703
- }
704
-
705
- /**
706
- * Gets all patient profiles.
707
- *
708
- * @param {Object} options - Optional parameters for pagination
709
- * @param {number} options.limit - Maximum number of profiles to return
710
- * @param {string} options.startAfter - The ID of the document to start after (for pagination)
711
- * @returns {Promise<PatientProfile[]>} A promise resolving to an array of all patient profiles.
712
- */
713
- async getAllPatients(options?: {
714
- limit?: number;
715
- startAfter?: string;
716
- }): Promise<PatientProfile[]> {
717
- console.log(`[PatientService.getAllPatients] Fetching patients with options:`, options);
718
- return getAllPatientsUtil(this.db, options);
719
- }
720
-
721
- /**
722
- * Gets all patients associated with a specific practitioner.
723
- *
724
- * @param {string} practitionerId - ID of the practitioner whose patients to retrieve
725
- * @param {Object} options - Optional parameters for pagination
726
- * @param {number} options.limit - Maximum number of profiles to return
727
- * @param {string} options.startAfter - The ID of the document to start after (for pagination)
728
- * @returns {Promise<PatientProfile[]>} A promise resolving to an array of patient profiles
729
- */
730
- async getPatientsByPractitioner(
731
- practitionerId: string,
732
- options?: {
733
- limit?: number;
734
- startAfter?: string;
735
- },
736
- ): Promise<PatientProfile[]> {
737
- console.log(
738
- `[PatientService.getPatientsByPractitioner] Fetching patients for practitioner: ${practitionerId}`,
739
- );
740
- return getPatientsByPractitionerUtil(this.db, practitionerId, options);
741
- }
742
-
743
- /**
744
- * Gets all patients associated with a specific practitioner with their sensitive information.
745
- *
746
- * @param {string} practitionerId - ID of the practitioner whose patients to retrieve
747
- * @param {Object} options - Optional parameters for pagination
748
- * @param {number} options.limit - Maximum number of profiles to return
749
- * @param {string} options.startAfter - The ID of the document to start after (for pagination)
750
- * @returns {Promise<PatientProfileForDoctor[]>} A promise resolving to an array of patient profiles with sensitive info
751
- */
752
- async getPatientsByPractitionerWithDetails(
753
- practitionerId: string,
754
- options?: {
755
- limit?: number;
756
- startAfter?: string;
757
- },
758
- ): Promise<PatientProfileForDoctor[]> {
759
- console.log(
760
- `[PatientService.getPatientsByPractitionerWithDetails] Fetching detailed patient profiles for practitioner: ${practitionerId}`,
761
- );
762
- return getPatientsByPractitionerWithDetailsUtil(this.db, practitionerId, options);
763
- }
764
-
765
- /**
766
- * Gets all patients associated with a specific clinic.
767
- *
768
- * @param {string} clinicId - ID of the clinic whose patients to retrieve
769
- * @param {Object} options - Optional parameters for pagination
770
- * @param {number} options.limit - Maximum number of profiles to return
771
- * @param {string} options.startAfter - The ID of the document to start after (for pagination)
772
- * @returns {Promise<PatientProfile[]>} A promise resolving to an array of patient profiles
773
- */
774
- async getPatientsByClinic(
775
- clinicId: string,
776
- options?: {
777
- limit?: number;
778
- startAfter?: string;
779
- },
780
- ): Promise<PatientProfile[]> {
781
- console.log(`[PatientService.getPatientsByClinic] Fetching patients for clinic: ${clinicId}`);
782
- return getPatientsByClinicUtil(this.db, clinicId, options);
783
- }
784
-
785
- /**
786
- * Creates a token for inviting a patient to claim their profile.
787
- *
788
- * @param {CreatePatientTokenData} data - Data for creating the token.
789
- * @param {string} createdBy - ID of the admin user creating the token.
790
- * @returns {Promise<PatientToken>} The created token.
791
- */
792
- async createPatientToken(data: CreatePatientTokenData, createdBy: string): Promise<PatientToken> {
793
- // We assume the 'createdBy' user is validated to be a clinic admin
794
- // in the calling context (e.g., a cloud function or API endpoint).
795
- return createPatientTokenUtil(
796
- this.db,
797
- data,
798
- createdBy,
799
- () => this.generateId(), // Pass the ID generation function
800
- );
801
- }
802
-
803
- /**
804
- * Validates a patient invitation token.
805
- *
806
- * @param {string} tokenString - The token string to validate.
807
- * @returns {Promise<PatientToken | null>} The token if found and valid, otherwise null.
808
- */
809
- async validatePatientToken(tokenString: string): Promise<PatientToken | null> {
810
- return validatePatientTokenUtil(this.db, tokenString);
811
- }
812
-
813
- /**
814
- * Marks a patient invitation token as used.
815
- *
816
- * @param {string} tokenId - The ID of the token to mark as used.
817
- * @param {string} patientId - The ID of the patient associated with the token.
818
- * @param {string} userId - The ID of the user who is using the token.
819
- * @returns {Promise<void>}
820
- */
821
- async markPatientTokenAsUsed(tokenId: string, patientId: string, userId: string): Promise<void> {
822
- return markPatientTokenAsUsedUtil(this.db, tokenId, patientId, userId);
823
- }
824
-
825
- /**
826
- * Retrieves all active invitation tokens for a specific clinic.
827
- * NOTE: This should be protected and only exposed to authorized clinic admins.
828
- *
829
- * @param {string} clinicId - The ID of the clinic.
830
- * @returns {Promise<PatientToken[]>} An array of active tokens for the clinic.
831
- */
832
- async getActiveInviteTokensByClinic(clinicId: string): Promise<PatientToken[]> {
833
- return getActiveInviteTokensByClinicUtil(this.db, clinicId);
834
- }
835
-
836
- /**
837
- * Retrieves all active invitation tokens for a specific patient.
838
- * NOTE: This should be protected and only exposed to authorized clinic admins.
839
- *
840
- * @param {string} patientId - The ID of the patient.
841
- * @returns {Promise<PatientToken[]>} An array of active tokens for the patient.
842
- */
843
- async getActiveInviteTokensByPatient(patientId: string): Promise<PatientToken[]> {
844
- // Security check should be done in the calling context to ensure
845
- // the admin has permission to view this patient's tokens.
846
- return getActiveInviteTokensByPatientUtil(this.db, patientId);
847
- }
848
-
849
- async getAestheticAnalysis(patientId: string): Promise<AestheticAnalysis | null> {
850
- const currentUser = await this.getCurrentUser();
851
- return getAestheticAnalysisUtil(this.db, patientId, currentUser.uid, currentUser.roles);
852
- }
853
-
854
- async createAestheticAnalysis(
855
- patientId: string,
856
- data: CreateAestheticAnalysisData
857
- ): Promise<void> {
858
- const currentUser = await this.getCurrentUser();
859
- return createOrUpdateAestheticAnalysisUtil(
860
- this.db,
861
- patientId,
862
- data,
863
- currentUser.uid,
864
- currentUser.roles,
865
- false
866
- );
867
- }
868
-
869
- async updateAestheticAnalysis(
870
- patientId: string,
871
- data: UpdateAestheticAnalysisData
872
- ): Promise<void> {
873
- const currentUser = await this.getCurrentUser();
874
- return createOrUpdateAestheticAnalysisUtil(
875
- this.db,
876
- patientId,
877
- data,
878
- currentUser.uid,
879
- currentUser.roles,
880
- true
881
- );
882
- }
883
- }
1
+ import {
2
+ doc,
3
+ getDoc,
4
+ writeBatch,
5
+ updateDoc,
6
+ arrayUnion,
7
+ serverTimestamp,
8
+ } from 'firebase/firestore';
9
+ import { BaseService } from '../base.service';
10
+ import { MediaService, MediaAccessLevel, MediaResource } from '../media/media.service';
11
+ import {
12
+ PatientProfile,
13
+ PatientSensitiveInfo,
14
+ PatientLocationInfo,
15
+ CreatePatientProfileData,
16
+ CreatePatientSensitiveInfoData,
17
+ UpdatePatientSensitiveInfoData,
18
+ CreatePatientLocationInfoData,
19
+ UpdatePatientLocationInfoData,
20
+ PatientMedicalInfo,
21
+ CreatePatientMedicalInfoData,
22
+ UpdateVitalStatsData,
23
+ AddAllergyData,
24
+ UpdateAllergyData,
25
+ AddBlockingConditionData,
26
+ UpdateBlockingConditionData,
27
+ AddContraindicationData,
28
+ UpdateContraindicationData,
29
+ AddMedicationData,
30
+ UpdateMedicationData,
31
+ PatientDoctor,
32
+ PatientClinic,
33
+ SearchPatientsParams,
34
+ RequesterInfo,
35
+ PatientProfileForDoctor,
36
+ CreateManualPatientData,
37
+ } from '../../types/patient';
38
+ import { Auth } from 'firebase/auth';
39
+ import { Firestore } from 'firebase/firestore';
40
+ import { FirebaseApp } from 'firebase/app';
41
+ import { Timestamp } from 'firebase/firestore';
42
+
43
+ // Importujemo utility funkcije
44
+ import {
45
+ createPatientProfileUtil,
46
+ getPatientProfileUtil,
47
+ getPatientProfileByUserRefUtil,
48
+ addExpoTokenUtil,
49
+ removeExpoTokenUtil,
50
+ addPointsUtil,
51
+ updatePatientProfileUtil,
52
+ updatePatientProfileByUserRefUtil,
53
+ searchPatientsUtil,
54
+ getAllPatientsUtil,
55
+ updatePatientLocationUtil,
56
+ createLocationInfoUtil,
57
+ getLocationInfoUtil,
58
+ updateLocationInfoUtil,
59
+ createSensitiveInfoUtil,
60
+ getSensitiveInfoUtil,
61
+ updateSensitiveInfoUtil,
62
+ claimPatientSensitiveInfoUtil,
63
+ createMedicalInfoUtil,
64
+ getMedicalInfoUtil,
65
+ updateVitalStatsUtil,
66
+ addAllergyUtil,
67
+ updateAllergyUtil,
68
+ removeAllergyUtil,
69
+ addBlockingConditionUtil,
70
+ updateBlockingConditionUtil,
71
+ removeBlockingConditionUtil,
72
+ addContraindicationUtil,
73
+ updateContraindicationUtil,
74
+ removeContraindicationUtil,
75
+ addMedicationUtil,
76
+ updateMedicationUtil,
77
+ removeMedicationUtil,
78
+ getPatientDocRef,
79
+ getSensitiveInfoDocRef,
80
+ getLocationInfoDocRef,
81
+ getMedicalInfoDocRef,
82
+ addDoctorUtil,
83
+ removeDoctorUtil,
84
+ addClinicUtil,
85
+ removeClinicUtil,
86
+ getPatientsByPractitionerUtil,
87
+ getPatientsByPractitionerWithDetailsUtil,
88
+ getPatientsByClinicUtil,
89
+ createPatientTokenUtil,
90
+ validatePatientTokenUtil,
91
+ markPatientTokenAsUsedUtil,
92
+ getActiveInviteTokensByClinicUtil,
93
+ getActiveInviteTokensByPatientUtil,
94
+ } from './utils';
95
+
96
+ import {
97
+ getAestheticAnalysisUtil,
98
+ createOrUpdateAestheticAnalysisUtil,
99
+ } from './utils/aesthetic-analysis.utils';
100
+
101
+ import {
102
+ AestheticAnalysis,
103
+ CreateAestheticAnalysisData,
104
+ UpdateAestheticAnalysisData,
105
+ } from '../../types/patient';
106
+
107
+ import { CreatePatientTokenData, PatientToken } from '../../types/patient/token.types';
108
+
109
+ export class PatientService extends BaseService {
110
+ private mediaService: MediaService;
111
+
112
+ constructor(db: Firestore, auth: Auth, app: FirebaseApp) {
113
+ super(db, auth, app);
114
+ this.mediaService = new MediaService(db, auth, app);
115
+ }
116
+
117
+ // Metode za rad sa profilom pacijenta
118
+ async createPatientProfile(data: CreatePatientProfileData): Promise<PatientProfile> {
119
+ return createPatientProfileUtil(this.db, data, () => this.generateId());
120
+ }
121
+
122
+ async getPatientProfile(patientId: string): Promise<PatientProfile | null> {
123
+ return getPatientProfileUtil(this.db, patientId);
124
+ }
125
+
126
+ /**
127
+ * Manually creates a new patient profile, typically initiated by a clinic admin.
128
+ * This creates a patient record that is not initially linked to an authenticated user.
129
+ *
130
+ * @param {CreateManualPatientData} data - The data for the new patient.
131
+ * @param {RequesterInfo} requester - Information about the user creating the patient (must be a clinic admin).
132
+ * @returns {Promise<PatientProfile>} The newly created patient profile.
133
+ * @throws {Error} If the requester is not a valid clinic admin.
134
+ */
135
+ async createManualPatient(
136
+ data: CreateManualPatientData,
137
+ requester: RequesterInfo,
138
+ ): Promise<PatientProfile> {
139
+ console.log(
140
+ `[PatientService.createManualPatient] Attempting to create manual patient by requester:`,
141
+ requester,
142
+ );
143
+
144
+ // Security Check: Ensure the requester is a clinic admin
145
+ if (
146
+ requester.role !== 'clinic_admin' ||
147
+ !requester.associatedClinicId ||
148
+ requester.associatedClinicId !== data.clinicId
149
+ ) {
150
+ throw new Error(
151
+ 'Unauthorized: Requester must be a clinic admin and can only add patients to their own clinic.',
152
+ );
153
+ }
154
+
155
+ const patientId = this.generateId();
156
+ const batch = writeBatch(this.db);
157
+ const now = Timestamp.now();
158
+
159
+ // 1. Create Patient Profile
160
+ const patientProfileRef = getPatientDocRef(this.db, patientId);
161
+ const newProfile: PatientProfile = {
162
+ id: patientId,
163
+ displayName: `${data.firstName} ${data.lastName.charAt(0)}.`,
164
+ expoTokens: [],
165
+ gamification: { level: 1, points: 0 },
166
+ isActive: true,
167
+ isVerified: false, // Manual profiles are not verified by default
168
+ isManual: true,
169
+ doctors: [],
170
+ clinics: [
171
+ {
172
+ clinicId: data.clinicId,
173
+ assignedAt: now,
174
+ assignedBy: requester.id,
175
+ isActive: true,
176
+ notes: data.notes,
177
+ },
178
+ ],
179
+ doctorIds: [],
180
+ clinicIds: [data.clinicId],
181
+ createdAt: now,
182
+ updatedAt: now,
183
+ phoneNumber: data.phoneNumber,
184
+ dateOfBirth: data.dateOfBirth,
185
+ };
186
+ batch.set(patientProfileRef, newProfile);
187
+
188
+ // 2. Create Patient Sensitive Info
189
+ const sensitiveInfoRef = getSensitiveInfoDocRef(this.db, patientId);
190
+ const newSensitiveInfo: Omit<PatientSensitiveInfo, 'photoUrl'> = {
191
+ patientId,
192
+ firstName: data.firstName,
193
+ lastName: data.lastName,
194
+ dateOfBirth: data.dateOfBirth,
195
+ gender: data.gender,
196
+ email: data.email,
197
+ phoneNumber: data.phoneNumber,
198
+ addressData: data.addressData,
199
+ emergencyContacts: [],
200
+ createdAt: now,
201
+ updatedAt: now,
202
+ };
203
+ batch.set(sensitiveInfoRef, newSensitiveInfo);
204
+
205
+ // 3. Create Patient Medical Info
206
+ const medicalInfoRef = getMedicalInfoDocRef(this.db, patientId);
207
+ const newMedicalInfo: PatientMedicalInfo = {
208
+ patientId,
209
+ vitalStats: {},
210
+ blockingConditions: [],
211
+ contraindications: [],
212
+ allergies: [],
213
+ currentMedications: [],
214
+ emergencyNotes: '',
215
+ lastUpdated: now,
216
+ updatedBy: requester.id, // The admin who created the record
217
+ };
218
+ batch.set(medicalInfoRef, newMedicalInfo);
219
+
220
+ await batch.commit();
221
+
222
+ console.log(
223
+ `[PatientService.createManualPatient] Successfully created manual patient with ID: ${patientId}`,
224
+ );
225
+
226
+ return newProfile;
227
+ }
228
+
229
+ async getPatientProfileByUserRef(userRef: string): Promise<PatientProfile | null> {
230
+ return getPatientProfileByUserRefUtil(this.db, userRef);
231
+ }
232
+
233
+ // Metode za rad sa lokacijskim podacima
234
+ async updatePatientLocation(
235
+ patientId: string,
236
+ latitude: number,
237
+ longitude: number,
238
+ ): Promise<void> {
239
+ await updatePatientLocationUtil(this.db, patientId, latitude, longitude);
240
+ }
241
+
242
+ async updatePatientLocationByUserRef(
243
+ userRef: string,
244
+ latitude: number,
245
+ longitude: number,
246
+ ): Promise<void> {
247
+ const profile = await this.getPatientProfileByUserRef(userRef);
248
+ if (!profile) throw new Error('Patient profile not found');
249
+ await this.updatePatientLocation(profile.id, latitude, longitude);
250
+ }
251
+
252
+ async createLocationInfo(
253
+ data: CreatePatientLocationInfoData,
254
+ requesterId: string,
255
+ ): Promise<PatientLocationInfo> {
256
+ return createLocationInfoUtil(this.db, data, requesterId);
257
+ }
258
+
259
+ async getLocationInfo(
260
+ patientId: string,
261
+ requesterId: string,
262
+ ): Promise<PatientLocationInfo | null> {
263
+ return getLocationInfoUtil(this.db, patientId, requesterId);
264
+ }
265
+
266
+ async getLocationInfoByUserRef(
267
+ userRef: string,
268
+ requesterId: string,
269
+ ): Promise<PatientLocationInfo | null> {
270
+ const profile = await this.getPatientProfileByUserRef(userRef);
271
+ if (!profile) return null;
272
+ return this.getLocationInfo(profile.id, requesterId);
273
+ }
274
+
275
+ async updateLocationInfo(
276
+ patientId: string,
277
+ data: UpdatePatientLocationInfoData,
278
+ requesterId: string,
279
+ ): Promise<PatientLocationInfo> {
280
+ return updateLocationInfoUtil(this.db, patientId, data, requesterId);
281
+ }
282
+
283
+ // Metode za rad sa osetljivim informacijama
284
+ async createSensitiveInfo(
285
+ data: CreatePatientSensitiveInfoData,
286
+ requesterUserId: string,
287
+ ): Promise<PatientSensitiveInfo> {
288
+ const currentUser = await this.getCurrentUser();
289
+ if (currentUser.uid !== requesterUserId) {
290
+ throw new Error('Requester does not match authenticated user.');
291
+ }
292
+
293
+ return createSensitiveInfoUtil(
294
+ this.db,
295
+ data,
296
+ requesterUserId,
297
+ currentUser.roles,
298
+ this.mediaService,
299
+ );
300
+ }
301
+
302
+ async getSensitiveInfo(
303
+ patientId: string,
304
+ requesterUserId: string,
305
+ ): Promise<PatientSensitiveInfo | null> {
306
+ const currentUser = await this.getCurrentUser();
307
+ if (currentUser.uid !== requesterUserId) {
308
+ // Allow for read-only access if authorized, but for now we check identity
309
+ // This could be expanded later based on practitioner/admin roles
310
+ }
311
+ return getSensitiveInfoUtil(this.db, patientId, requesterUserId, currentUser.roles);
312
+ }
313
+
314
+ async getSensitiveInfoByUserRef(
315
+ userRef: string,
316
+ requesterUserId: string,
317
+ ): Promise<PatientSensitiveInfo | null> {
318
+ const profile = await this.getPatientProfileByUserRef(userRef);
319
+ if (!profile) return null;
320
+ // We pass requesterUserId which is the UID of the one asking.
321
+ return this.getSensitiveInfo(profile.id, requesterUserId);
322
+ }
323
+
324
+ async updateSensitiveInfo(
325
+ patientId: string,
326
+ data: UpdatePatientSensitiveInfoData,
327
+ requesterUserId: string,
328
+ ): Promise<PatientSensitiveInfo> {
329
+ const currentUser = await this.getCurrentUser();
330
+ if (currentUser.uid !== requesterUserId) {
331
+ throw new Error('Requester does not match authenticated user.');
332
+ }
333
+ return updateSensitiveInfoUtil(
334
+ this.db,
335
+ patientId,
336
+ data,
337
+ requesterUserId,
338
+ currentUser.roles,
339
+ this.mediaService,
340
+ );
341
+ }
342
+
343
+ async claimPatientSensitiveInfo(
344
+ patientId: string,
345
+ userId: string,
346
+ ): Promise<PatientSensitiveInfo> {
347
+ return claimPatientSensitiveInfoUtil(this.db, patientId, userId);
348
+ }
349
+
350
+ // Metode za rad sa medicinskim informacijama
351
+ async createMedicalInfo(patientId: string, data: CreatePatientMedicalInfoData): Promise<void> {
352
+ const currentUser = await this.getCurrentUser();
353
+ await createMedicalInfoUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
354
+ }
355
+
356
+ async getMedicalInfo(patientId: string): Promise<PatientMedicalInfo> {
357
+ const currentUser = await this.getCurrentUser();
358
+ return getMedicalInfoUtil(this.db, patientId, currentUser.uid, currentUser.roles);
359
+ }
360
+
361
+ async getMedicalInfoByUserRef(userRef: string): Promise<PatientMedicalInfo> {
362
+ const profile = await this.getPatientProfileByUserRef(userRef);
363
+ if (!profile) throw new Error('Patient profile not found');
364
+ return this.getMedicalInfo(profile.id);
365
+ }
366
+
367
+ // Metode za rad sa vitalnim statistikama
368
+ async updateVitalStats(patientId: string, data: UpdateVitalStatsData): Promise<void> {
369
+ const currentUser = await this.getCurrentUser();
370
+ await updateVitalStatsUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
371
+ }
372
+
373
+ // Metode za rad sa alergijama
374
+ async addAllergy(patientId: string, data: AddAllergyData): Promise<void> {
375
+ const currentUser = await this.getCurrentUser();
376
+ await addAllergyUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
377
+ }
378
+
379
+ async updateAllergy(patientId: string, data: UpdateAllergyData): Promise<void> {
380
+ const currentUser = await this.getCurrentUser();
381
+ await updateAllergyUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
382
+ }
383
+
384
+ async removeAllergy(patientId: string, allergyIndex: number): Promise<void> {
385
+ const currentUser = await this.getCurrentUser();
386
+ await removeAllergyUtil(this.db, patientId, allergyIndex, currentUser.uid, currentUser.roles);
387
+ }
388
+
389
+ // Metode za rad sa blocking conditions
390
+ async addBlockingCondition(patientId: string, data: AddBlockingConditionData): Promise<void> {
391
+ const currentUser = await this.getCurrentUser();
392
+ await addBlockingConditionUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
393
+ }
394
+
395
+ async updateBlockingCondition(
396
+ patientId: string,
397
+ data: UpdateBlockingConditionData,
398
+ ): Promise<void> {
399
+ const currentUser = await this.getCurrentUser();
400
+ await updateBlockingConditionUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
401
+ }
402
+
403
+ async removeBlockingCondition(patientId: string, conditionIndex: number): Promise<void> {
404
+ const currentUser = await this.getCurrentUser();
405
+ await removeBlockingConditionUtil(
406
+ this.db,
407
+ patientId,
408
+ conditionIndex,
409
+ currentUser.uid,
410
+ currentUser.roles,
411
+ );
412
+ }
413
+
414
+ // Metode za rad sa kontraindikacijama
415
+ async addContraindication(patientId: string, data: AddContraindicationData): Promise<void> {
416
+ const currentUser = await this.getCurrentUser();
417
+ await addContraindicationUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
418
+ }
419
+
420
+ async updateContraindication(patientId: string, data: UpdateContraindicationData): Promise<void> {
421
+ const currentUser = await this.getCurrentUser();
422
+ await updateContraindicationUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
423
+ }
424
+
425
+ async removeContraindication(patientId: string, contraindicationIndex: number): Promise<void> {
426
+ const currentUser = await this.getCurrentUser();
427
+ await removeContraindicationUtil(
428
+ this.db,
429
+ patientId,
430
+ contraindicationIndex,
431
+ currentUser.uid,
432
+ currentUser.roles,
433
+ );
434
+ }
435
+
436
+ // Metode za rad sa medikacijama
437
+ async addMedication(patientId: string, data: AddMedicationData): Promise<void> {
438
+ const currentUser = await this.getCurrentUser();
439
+ await addMedicationUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
440
+ }
441
+
442
+ async updateMedication(patientId: string, data: UpdateMedicationData): Promise<void> {
443
+ const currentUser = await this.getCurrentUser();
444
+ await updateMedicationUtil(this.db, patientId, data, currentUser.uid, currentUser.roles);
445
+ }
446
+
447
+ async removeMedication(patientId: string, medicationIndex: number): Promise<void> {
448
+ const currentUser = await this.getCurrentUser();
449
+ await removeMedicationUtil(
450
+ this.db,
451
+ patientId,
452
+ medicationIndex,
453
+ currentUser.uid,
454
+ currentUser.roles,
455
+ );
456
+ }
457
+
458
+ // Pomoćne metode
459
+ async addExpoToken(patientId: string, token: string): Promise<void> {
460
+ await addExpoTokenUtil(this.db, patientId, token);
461
+ }
462
+
463
+ async addExpoTokenByUserRef(userRef: string, token: string): Promise<void> {
464
+ const profile = await this.getPatientProfileByUserRef(userRef);
465
+ if (!profile) throw new Error('Patient profile not found');
466
+ await this.addExpoToken(profile.id, token);
467
+ }
468
+
469
+ async removeExpoToken(patientId: string, token: string): Promise<void> {
470
+ await removeExpoTokenUtil(this.db, patientId, token);
471
+ }
472
+
473
+ async removeExpoTokenByUserRef(userRef: string, token: string): Promise<void> {
474
+ const profile = await this.getPatientProfileByUserRef(userRef);
475
+ if (!profile) throw new Error('Patient profile not found');
476
+ await this.removeExpoToken(profile.id, token);
477
+ }
478
+
479
+ async addPoints(patientId: string, points: number): Promise<void> {
480
+ await addPointsUtil(this.db, patientId, points);
481
+ }
482
+
483
+ async addPointsByUserRef(userRef: string, points: number): Promise<void> {
484
+ const profile = await this.getPatientProfileByUserRef(userRef);
485
+ if (!profile) throw new Error('Patient profile not found');
486
+ await this.addPoints(profile.id, points);
487
+ }
488
+
489
+ private async getCurrentUser(): Promise<any> {
490
+ if (!this.auth.currentUser) {
491
+ throw new Error('No authenticated user');
492
+ }
493
+ const userDoc = await getDoc(doc(this.db, 'users', this.auth.currentUser.uid));
494
+ if (!userDoc.exists()) {
495
+ throw new Error('User not found');
496
+ }
497
+ return userDoc.data();
498
+ }
499
+
500
+ /**
501
+ * Briše profil pacijenta i sve povezane subkolekcije
502
+ */
503
+ async deletePatientProfile(patientId: string): Promise<void> {
504
+ const batch = writeBatch(this.db);
505
+
506
+ // Brisanje sensitive info
507
+ batch.delete(getSensitiveInfoDocRef(this.db, patientId));
508
+
509
+ // Brisanje location info
510
+ batch.delete(getLocationInfoDocRef(this.db, patientId));
511
+
512
+ // Brisanje medical info
513
+ batch.delete(getMedicalInfoDocRef(this.db, patientId));
514
+
515
+ // Brisanje glavnog profila
516
+ batch.delete(getPatientDocRef(this.db, patientId));
517
+
518
+ await batch.commit();
519
+ }
520
+
521
+ // Metode za rad sa doktorima
522
+ async addDoctor(patientId: string, doctorRef: string): Promise<void> {
523
+ const currentUser = await this.getCurrentUser();
524
+ await addDoctorUtil(this.db, patientId, doctorRef, currentUser.uid);
525
+ }
526
+
527
+ async removeDoctor(patientId: string, doctorRef: string): Promise<void> {
528
+ await removeDoctorUtil(this.db, patientId, doctorRef);
529
+ }
530
+
531
+ // Metode za rad sa klinikama
532
+ async addClinic(patientId: string, clinicId: string): Promise<void> {
533
+ const currentUser = await this.getCurrentUser();
534
+ await addClinicUtil(this.db, patientId, clinicId, currentUser.uid);
535
+ }
536
+
537
+ async removeClinic(patientId: string, clinicId: string): Promise<void> {
538
+ await removeClinicUtil(this.db, patientId, clinicId);
539
+ }
540
+
541
+ // Metode za rad sa profilnom slikom
542
+ /**
543
+ * Uploads a profile photo for a patient
544
+ * @param patientId - ID of the patient
545
+ * @param file - File or Blob to upload
546
+ * @returns URL of the uploaded photo
547
+ */
548
+ async uploadProfilePhoto(patientId: string, file: File | Blob): Promise<string> {
549
+ console.log(`[PatientService] Uploading profile photo for patient ${patientId}`);
550
+
551
+ const mediaMetadata = await this.mediaService.uploadMedia(
552
+ file,
553
+ patientId, // Using patientId as ownerId
554
+ MediaAccessLevel.PRIVATE, // Profile photos should be private
555
+ 'patient_profile_photos',
556
+ file instanceof File ? file.name : `profile_photo_${patientId}`,
557
+ );
558
+
559
+ // Update the patient sensitive info with the new photo URL
560
+ await updateDoc(getSensitiveInfoDocRef(this.db, patientId), {
561
+ photoUrl: mediaMetadata.url,
562
+ updatedAt: serverTimestamp(),
563
+ });
564
+
565
+ return mediaMetadata.url;
566
+ }
567
+
568
+ /**
569
+ * Updates a patient's profile photo (replaces existing one)
570
+ * @param patientId - ID of the patient
571
+ * @param file - New file or Blob to upload
572
+ * @returns URL of the new uploaded photo
573
+ */
574
+ async updateProfilePhoto(patientId: string, file: File | Blob): Promise<string> {
575
+ console.log(`[PatientService] Updating profile photo for patient ${patientId}`);
576
+
577
+ // Get current patient sensitive info to check for existing photo
578
+ const currentUser = await this.getCurrentUser();
579
+ const currentSensitiveInfo = await this.getSensitiveInfo(patientId, currentUser.uid);
580
+
581
+ // Delete old photo if it exists and is managed by our MediaService
582
+ if (currentSensitiveInfo?.photoUrl && typeof currentSensitiveInfo.photoUrl === 'string') {
583
+ try {
584
+ const existingMediaMetadata = await this.mediaService.getMediaMetadataByUrl(
585
+ currentSensitiveInfo.photoUrl,
586
+ );
587
+ if (existingMediaMetadata) {
588
+ await this.mediaService.deleteMedia(existingMediaMetadata.id);
589
+ }
590
+ } catch (error) {
591
+ console.warn(
592
+ `[PatientService] Could not delete old profile photo for patient ${patientId}:`,
593
+ error,
594
+ );
595
+ // Continue with upload even if deletion fails
596
+ }
597
+ }
598
+
599
+ // Upload new photo
600
+ return this.uploadProfilePhoto(patientId, file);
601
+ }
602
+
603
+ /**
604
+ * Deletes a patient's profile photo
605
+ * @param patientId - ID of the patient
606
+ */
607
+ async deleteProfilePhoto(patientId: string): Promise<void> {
608
+ console.log(`[PatientService] Deleting profile photo for patient ${patientId}`);
609
+
610
+ // Get current patient sensitive info to find the photo URL
611
+ const currentUser = await this.getCurrentUser();
612
+ const currentSensitiveInfo = await this.getSensitiveInfo(patientId, currentUser.uid);
613
+
614
+ if (currentSensitiveInfo?.photoUrl && typeof currentSensitiveInfo.photoUrl === 'string') {
615
+ try {
616
+ const existingMediaMetadata = await this.mediaService.getMediaMetadataByUrl(
617
+ currentSensitiveInfo.photoUrl,
618
+ );
619
+ if (existingMediaMetadata) {
620
+ await this.mediaService.deleteMedia(existingMediaMetadata.id);
621
+ }
622
+ } catch (error) {
623
+ console.warn(
624
+ `[PatientService] Could not delete profile photo for patient ${patientId}:`,
625
+ error,
626
+ );
627
+ }
628
+
629
+ // Remove photo URL from patient sensitive info
630
+ await updateDoc(getSensitiveInfoDocRef(this.db, patientId), {
631
+ photoUrl: null,
632
+ updatedAt: serverTimestamp(),
633
+ });
634
+ }
635
+ }
636
+
637
+ /**
638
+ * Handles profile photo upload for patients (supports MediaResource)
639
+ * @param photoUrl - MediaResource (File, Blob, or URL string) from CreatePatientSensitiveInfoData
640
+ * @param patientId - ID of the patient
641
+ * @returns URL string of the uploaded or existing photo
642
+ */
643
+ private async handleProfilePhotoUpload(
644
+ photoUrl: MediaResource | undefined,
645
+ patientId: string,
646
+ ): Promise<string | undefined> {
647
+ if (!photoUrl) {
648
+ return undefined;
649
+ }
650
+
651
+ // If it's already a URL string, return it as is
652
+ if (typeof photoUrl === 'string') {
653
+ return photoUrl;
654
+ }
655
+
656
+ // If it's a File or Blob, upload it
657
+ if (photoUrl instanceof File || photoUrl instanceof Blob) {
658
+ return this.uploadProfilePhoto(patientId, photoUrl);
659
+ }
660
+
661
+ return undefined;
662
+ }
663
+
664
+ // Metode za ažuriranje profila
665
+ async updatePatientProfile(
666
+ patientId: string,
667
+ data: Partial<Omit<PatientProfile, 'id' | 'createdAt' | 'updatedAt'>>,
668
+ ): Promise<PatientProfile> {
669
+ return updatePatientProfileUtil(this.db, patientId, data);
670
+ }
671
+
672
+ async updatePatientProfileByUserRef(
673
+ userRef: string,
674
+ data: Partial<Omit<PatientProfile, 'id' | 'createdAt' | 'updatedAt'>>,
675
+ ): Promise<PatientProfile> {
676
+ return updatePatientProfileByUserRefUtil(this.db, userRef, data);
677
+ }
678
+
679
+ /**
680
+ * Searches for patient profiles based on clinic/practitioner association.
681
+ * Requires information about the requester for security checks.
682
+ *
683
+ * @param {SearchPatientsParams} params - The search criteria (clinicId, practitionerId).
684
+ * @param {RequesterInfo} requester - Information about the user performing the search (ID, role, associated IDs).
685
+ * @returns {Promise<PatientProfile[]>} A promise resolving to an array of matching patient profiles.
686
+ */
687
+ async searchPatients(
688
+ params: SearchPatientsParams,
689
+ requester: RequesterInfo,
690
+ ): Promise<PatientProfile[]> {
691
+ // We can potentially add more service-level logic here in the future,
692
+ // like fetching additional data or enriching the results.
693
+ // For now, we delegate directly to the utility function.
694
+ console.log(
695
+ `[PatientService.searchPatients] Initiating search with params:`,
696
+ params,
697
+ `by requester:`,
698
+ requester,
699
+ );
700
+
701
+ // The utility function already handles validation and security checks.
702
+ return searchPatientsUtil(this.db, params, requester);
703
+ }
704
+
705
+ /**
706
+ * Gets all patient profiles.
707
+ *
708
+ * @param {Object} options - Optional parameters for pagination
709
+ * @param {number} options.limit - Maximum number of profiles to return
710
+ * @param {string} options.startAfter - The ID of the document to start after (for pagination)
711
+ * @returns {Promise<PatientProfile[]>} A promise resolving to an array of all patient profiles.
712
+ */
713
+ async getAllPatients(options?: {
714
+ limit?: number;
715
+ startAfter?: string;
716
+ }): Promise<PatientProfile[]> {
717
+ console.log(`[PatientService.getAllPatients] Fetching patients with options:`, options);
718
+ return getAllPatientsUtil(this.db, options);
719
+ }
720
+
721
+ /**
722
+ * Gets all patients associated with a specific practitioner.
723
+ *
724
+ * @param {string} practitionerId - ID of the practitioner whose patients to retrieve
725
+ * @param {Object} options - Optional parameters for pagination
726
+ * @param {number} options.limit - Maximum number of profiles to return
727
+ * @param {string} options.startAfter - The ID of the document to start after (for pagination)
728
+ * @returns {Promise<PatientProfile[]>} A promise resolving to an array of patient profiles
729
+ */
730
+ async getPatientsByPractitioner(
731
+ practitionerId: string,
732
+ options?: {
733
+ limit?: number;
734
+ startAfter?: string;
735
+ },
736
+ ): Promise<PatientProfile[]> {
737
+ console.log(
738
+ `[PatientService.getPatientsByPractitioner] Fetching patients for practitioner: ${practitionerId}`,
739
+ );
740
+ return getPatientsByPractitionerUtil(this.db, practitionerId, options);
741
+ }
742
+
743
+ /**
744
+ * Gets all patients associated with a specific practitioner with their sensitive information.
745
+ *
746
+ * @param {string} practitionerId - ID of the practitioner whose patients to retrieve
747
+ * @param {Object} options - Optional parameters for pagination
748
+ * @param {number} options.limit - Maximum number of profiles to return
749
+ * @param {string} options.startAfter - The ID of the document to start after (for pagination)
750
+ * @returns {Promise<PatientProfileForDoctor[]>} A promise resolving to an array of patient profiles with sensitive info
751
+ */
752
+ async getPatientsByPractitionerWithDetails(
753
+ practitionerId: string,
754
+ options?: {
755
+ limit?: number;
756
+ startAfter?: string;
757
+ },
758
+ ): Promise<PatientProfileForDoctor[]> {
759
+ console.log(
760
+ `[PatientService.getPatientsByPractitionerWithDetails] Fetching detailed patient profiles for practitioner: ${practitionerId}`,
761
+ );
762
+ return getPatientsByPractitionerWithDetailsUtil(this.db, practitionerId, options);
763
+ }
764
+
765
+ /**
766
+ * Gets all patients associated with a specific clinic.
767
+ *
768
+ * @param {string} clinicId - ID of the clinic whose patients to retrieve
769
+ * @param {Object} options - Optional parameters for pagination
770
+ * @param {number} options.limit - Maximum number of profiles to return
771
+ * @param {string} options.startAfter - The ID of the document to start after (for pagination)
772
+ * @returns {Promise<PatientProfile[]>} A promise resolving to an array of patient profiles
773
+ */
774
+ async getPatientsByClinic(
775
+ clinicId: string,
776
+ options?: {
777
+ limit?: number;
778
+ startAfter?: string;
779
+ },
780
+ ): Promise<PatientProfile[]> {
781
+ console.log(`[PatientService.getPatientsByClinic] Fetching patients for clinic: ${clinicId}`);
782
+ return getPatientsByClinicUtil(this.db, clinicId, options);
783
+ }
784
+
785
+ /**
786
+ * Creates a token for inviting a patient to claim their profile.
787
+ *
788
+ * @param {CreatePatientTokenData} data - Data for creating the token.
789
+ * @param {string} createdBy - ID of the admin user creating the token.
790
+ * @returns {Promise<PatientToken>} The created token.
791
+ */
792
+ async createPatientToken(data: CreatePatientTokenData, createdBy: string): Promise<PatientToken> {
793
+ // We assume the 'createdBy' user is validated to be a clinic admin
794
+ // in the calling context (e.g., a cloud function or API endpoint).
795
+ return createPatientTokenUtil(
796
+ this.db,
797
+ data,
798
+ createdBy,
799
+ () => this.generateId(), // Pass the ID generation function
800
+ );
801
+ }
802
+
803
+ /**
804
+ * Validates a patient invitation token.
805
+ *
806
+ * @param {string} tokenString - The token string to validate.
807
+ * @returns {Promise<PatientToken | null>} The token if found and valid, otherwise null.
808
+ */
809
+ async validatePatientToken(tokenString: string): Promise<PatientToken | null> {
810
+ return validatePatientTokenUtil(this.db, tokenString);
811
+ }
812
+
813
+ /**
814
+ * Marks a patient invitation token as used.
815
+ *
816
+ * @param {string} tokenId - The ID of the token to mark as used.
817
+ * @param {string} patientId - The ID of the patient associated with the token.
818
+ * @param {string} userId - The ID of the user who is using the token.
819
+ * @returns {Promise<void>}
820
+ */
821
+ async markPatientTokenAsUsed(tokenId: string, patientId: string, userId: string): Promise<void> {
822
+ return markPatientTokenAsUsedUtil(this.db, tokenId, patientId, userId);
823
+ }
824
+
825
+ /**
826
+ * Retrieves all active invitation tokens for a specific clinic.
827
+ * NOTE: This should be protected and only exposed to authorized clinic admins.
828
+ *
829
+ * @param {string} clinicId - The ID of the clinic.
830
+ * @returns {Promise<PatientToken[]>} An array of active tokens for the clinic.
831
+ */
832
+ async getActiveInviteTokensByClinic(clinicId: string): Promise<PatientToken[]> {
833
+ return getActiveInviteTokensByClinicUtil(this.db, clinicId);
834
+ }
835
+
836
+ /**
837
+ * Retrieves all active invitation tokens for a specific patient.
838
+ * NOTE: This should be protected and only exposed to authorized clinic admins.
839
+ *
840
+ * @param {string} patientId - The ID of the patient.
841
+ * @returns {Promise<PatientToken[]>} An array of active tokens for the patient.
842
+ */
843
+ async getActiveInviteTokensByPatient(patientId: string): Promise<PatientToken[]> {
844
+ // Security check should be done in the calling context to ensure
845
+ // the admin has permission to view this patient's tokens.
846
+ return getActiveInviteTokensByPatientUtil(this.db, patientId);
847
+ }
848
+
849
+ async getAestheticAnalysis(patientId: string): Promise<AestheticAnalysis | null> {
850
+ const currentUser = await this.getCurrentUser();
851
+ return getAestheticAnalysisUtil(this.db, patientId, currentUser.uid, currentUser.roles);
852
+ }
853
+
854
+ async createAestheticAnalysis(
855
+ patientId: string,
856
+ data: CreateAestheticAnalysisData
857
+ ): Promise<void> {
858
+ const currentUser = await this.getCurrentUser();
859
+ return createOrUpdateAestheticAnalysisUtil(
860
+ this.db,
861
+ patientId,
862
+ data,
863
+ currentUser.uid,
864
+ currentUser.roles,
865
+ false
866
+ );
867
+ }
868
+
869
+ async updateAestheticAnalysis(
870
+ patientId: string,
871
+ data: UpdateAestheticAnalysisData
872
+ ): Promise<void> {
873
+ const currentUser = await this.getCurrentUser();
874
+ return createOrUpdateAestheticAnalysisUtil(
875
+ this.db,
876
+ patientId,
877
+ data,
878
+ currentUser.uid,
879
+ currentUser.roles,
880
+ true
881
+ );
882
+ }
883
+ }