@blackcode_sa/metaestetics-api 1.6.17 → 1.6.19

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.
@@ -0,0 +1,466 @@
1
+ import {
2
+ collection,
3
+ doc,
4
+ getDoc,
5
+ getDocs,
6
+ query,
7
+ where,
8
+ updateDoc,
9
+ deleteDoc,
10
+ QueryConstraint,
11
+ Timestamp,
12
+ setDoc,
13
+ serverTimestamp,
14
+ FieldValue,
15
+ } from "firebase/firestore";
16
+ import { initializeFirebase } from "../config/firebase";
17
+ import { User, UserRole, USERS_COLLECTION, CreateUserData } from "../types";
18
+ import { userSchema } from "../validations/schemas";
19
+ import { AuthError } from "../errors/auth.errors";
20
+ import { USER_ERRORS } from "../errors/user.errors";
21
+ import { AUTH_ERRORS } from "../errors/auth.errors";
22
+ import { z } from "zod";
23
+ import { BaseService } from "./base.service";
24
+ import { PatientService } from "./patient/patient.service";
25
+ import { ClinicAdminService } from "./clinic/clinic-admin.service";
26
+ import { PatientProfile, PATIENTS_COLLECTION } from "../types/patient";
27
+ import { User as FirebaseUser } from "firebase/auth";
28
+ import { Auth } from "firebase/auth";
29
+ import { PractitionerService } from "./practitioner/practitioner.service";
30
+ import { CertificationLevel } from "../backoffice/types/static/certification.types";
31
+ import { Firestore } from "firebase/firestore";
32
+ import { FirebaseApp } from "firebase/app";
33
+
34
+ export class UserServiceV2 extends BaseService {
35
+ private patientService: PatientService;
36
+ private clinicAdminService: ClinicAdminService;
37
+ private practitionerService: PractitionerService;
38
+
39
+ constructor(
40
+ db: Firestore,
41
+ auth: Auth,
42
+ app: FirebaseApp,
43
+ patientService?: PatientService,
44
+ clinicAdminService?: ClinicAdminService,
45
+ practitionerService?: PractitionerService
46
+ ) {
47
+ super(db, auth, app);
48
+
49
+ // Kreiramo servise samo ako nisu prosleđeni
50
+ if (!patientService) {
51
+ patientService = new PatientService(db, auth, app);
52
+ }
53
+ if (!clinicAdminService) {
54
+ clinicAdminService = new ClinicAdminService(db, auth, app);
55
+ }
56
+ if (!practitionerService) {
57
+ practitionerService = new PractitionerService(db, auth, app);
58
+ }
59
+
60
+ this.patientService = patientService;
61
+ this.clinicAdminService = clinicAdminService;
62
+ this.practitionerService = practitionerService;
63
+ }
64
+
65
+ private getPatientService(): PatientService {
66
+ return this.patientService;
67
+ }
68
+
69
+ private getClinicAdminService(): ClinicAdminService {
70
+ return this.clinicAdminService;
71
+ }
72
+
73
+ private getPractitionerService(): PractitionerService {
74
+ return this.practitionerService;
75
+ }
76
+
77
+ /**
78
+ * Kreira novog korisnika na osnovu Firebase korisnika
79
+ */
80
+ async createUser(
81
+ firebaseUser: FirebaseUser,
82
+ roles: UserRole[] = [UserRole.PATIENT],
83
+ options?: {
84
+ clinicAdminData?: {
85
+ isGroupOwner: boolean;
86
+ groupToken?: string;
87
+ groupId?: string;
88
+ };
89
+ skipProfileCreation?: boolean;
90
+ }
91
+ ): Promise<User> {
92
+ const userData: CreateUserData = {
93
+ uid: firebaseUser.uid,
94
+ email: firebaseUser.email,
95
+ roles: roles.length > 0 ? roles : [UserRole.PATIENT],
96
+ isAnonymous: firebaseUser.isAnonymous,
97
+ createdAt: serverTimestamp(),
98
+ updatedAt: serverTimestamp(),
99
+ lastLoginAt: serverTimestamp(),
100
+ };
101
+
102
+ // Kreiramo osnovnog korisnika
103
+ await setDoc(doc(this.db, USERS_COLLECTION, userData.uid), userData);
104
+
105
+ // Kreiramo odgovarajuće profile na osnovu rola
106
+ const profiles = await this.createProfilesForRoles(
107
+ userData.uid,
108
+ roles,
109
+ options
110
+ );
111
+
112
+ // Ažuriramo korisnika sa referencama na profile
113
+ await updateDoc(doc(this.db, USERS_COLLECTION, userData.uid), profiles);
114
+
115
+ return this.getUserById(userData.uid);
116
+ }
117
+
118
+ /**
119
+ * Dohvata ili kreira korisnika na osnovu Firebase korisnika
120
+ */
121
+ async getOrCreateUser(
122
+ firebaseUser: FirebaseUser,
123
+ initialRole?: UserRole
124
+ ): Promise<User> {
125
+ try {
126
+ const existingUser = await this.getUserById(firebaseUser.uid);
127
+ await this.updateUserLoginTimestamp(firebaseUser.uid);
128
+ return existingUser;
129
+ } catch (error) {
130
+ return this.createUser(firebaseUser, [initialRole || UserRole.PATIENT]);
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Kreira profile za odgovarajuće role
136
+ */
137
+ private async createProfilesForRoles(
138
+ userId: string,
139
+ roles: UserRole[],
140
+ options?: {
141
+ clinicAdminData?: {
142
+ isGroupOwner: boolean;
143
+ groupToken?: string;
144
+ groupId?: string;
145
+ };
146
+ skipProfileCreation?: boolean;
147
+ }
148
+ ): Promise<{
149
+ patientProfile?: string;
150
+ practitionerProfile?: string;
151
+ adminProfile?: string;
152
+ }> {
153
+ const profiles: {
154
+ patientProfile?: string;
155
+ practitionerProfile?: string;
156
+ adminProfile?: string;
157
+ } = {};
158
+
159
+ for (const role of roles) {
160
+ switch (role) {
161
+ case UserRole.PATIENT:
162
+ const patientProfile =
163
+ await this.getPatientService().createPatientProfile({
164
+ userRef: userId,
165
+ displayName: "Patient", // Default displayName, može se kasnije promeniti
166
+ expoTokens: [],
167
+ gamification: {
168
+ level: 1,
169
+ points: 0,
170
+ },
171
+ isActive: true,
172
+ isVerified: false,
173
+ });
174
+ profiles.patientProfile = patientProfile.id;
175
+ break;
176
+ case UserRole.CLINIC_ADMIN:
177
+ // Skip profile creation if explicitly requested
178
+ // This is used when we know the profile will be created elsewhere (e.g. in signUpClinicAdmin)
179
+ if (options?.skipProfileCreation) {
180
+ break;
181
+ }
182
+
183
+ // Ako imamo token, verifikujemo ga i dodajemo admina u postojeću grupu
184
+ if (
185
+ options?.clinicAdminData?.groupToken &&
186
+ options?.clinicAdminData?.groupId
187
+ ) {
188
+ const isValid = await this.getClinicAdminService()
189
+ .getClinicGroupService()
190
+ .verifyAndUseAdminToken(
191
+ options.clinicAdminData.groupId,
192
+ options.clinicAdminData.groupToken,
193
+ userId
194
+ );
195
+
196
+ if (!isValid) {
197
+ throw new Error("Invalid admin token");
198
+ }
199
+ }
200
+
201
+ const clinicAdminProfile =
202
+ await this.getClinicAdminService().createClinicAdmin({
203
+ userRef: userId,
204
+ clinicGroupId: options?.clinicAdminData?.groupId || "",
205
+ isGroupOwner: options?.clinicAdminData?.isGroupOwner || false,
206
+ clinicsManaged: [],
207
+ contactInfo: {
208
+ firstName: "",
209
+ lastName: "",
210
+ title: "Clinic Administrator",
211
+ email: "",
212
+ phoneNumber: "",
213
+ },
214
+ roleTitle: "Clinic Administrator",
215
+ isActive: true,
216
+ });
217
+ profiles.adminProfile = clinicAdminProfile.id;
218
+ break;
219
+ case UserRole.PRACTITIONER:
220
+ const practitionerProfile =
221
+ await this.getPractitionerService().createPractitioner({
222
+ userRef: userId,
223
+ basicInfo: {
224
+ firstName: "",
225
+ lastName: "",
226
+ email: "",
227
+ phoneNumber: "",
228
+ title: "",
229
+ dateOfBirth: Timestamp.now(),
230
+ gender: "other",
231
+ languages: ["Serbian"],
232
+ },
233
+ certification: {
234
+ level: CertificationLevel.AESTHETICIAN,
235
+ specialties: [],
236
+ licenseNumber: "",
237
+ issuingAuthority: "",
238
+ issueDate: Timestamp.now(),
239
+ verificationStatus: "pending",
240
+ },
241
+ isActive: true,
242
+ isVerified: false,
243
+ });
244
+ profiles.practitionerProfile = practitionerProfile.id;
245
+ break;
246
+ }
247
+ }
248
+
249
+ return profiles;
250
+ }
251
+
252
+ /**
253
+ * Dohvata korisnika po ID-u
254
+ */
255
+ async getUserById(uid: string): Promise<User> {
256
+ const userDoc = await getDoc(doc(this.db, USERS_COLLECTION, uid));
257
+
258
+ if (!userDoc.exists()) {
259
+ throw USER_ERRORS.NOT_FOUND;
260
+ }
261
+
262
+ const userData = userDoc.data();
263
+ return userSchema.parse(userData);
264
+ }
265
+
266
+ /**
267
+ * Dohvata korisnika po email-u
268
+ */
269
+ async getUserByEmail(email: string): Promise<User | null> {
270
+ const usersRef = collection(this.db, USERS_COLLECTION);
271
+ const q = query(usersRef, where("email", "==", email));
272
+ const querySnapshot = await getDocs(q);
273
+
274
+ if (querySnapshot.empty) return null;
275
+
276
+ const userData = querySnapshot.docs[0].data();
277
+ return userSchema.parse(userData);
278
+ }
279
+
280
+ async getUsersByRole(role: UserRole): Promise<User[]> {
281
+ const constraints: QueryConstraint[] = [
282
+ where("roles", "array-contains", role),
283
+ ];
284
+ const q = query(collection(this.db, USERS_COLLECTION), ...constraints);
285
+ const querySnapshot = await getDocs(q);
286
+
287
+ const users = querySnapshot.docs.map((doc) => doc.data());
288
+ return Promise.all(users.map((userData) => userSchema.parse(userData)));
289
+ }
290
+
291
+ /**
292
+ * Ažurira timestamp poslednjeg logovanja
293
+ */
294
+ async updateUserLoginTimestamp(uid: string): Promise<User> {
295
+ const userRef = doc(this.db, USERS_COLLECTION, uid);
296
+ const userDoc = await getDoc(userRef);
297
+
298
+ if (!userDoc.exists()) {
299
+ throw AUTH_ERRORS.USER_NOT_FOUND;
300
+ }
301
+
302
+ await updateDoc(userRef, {
303
+ lastLoginAt: serverTimestamp(),
304
+ updatedAt: serverTimestamp(),
305
+ });
306
+
307
+ return this.getUserById(uid);
308
+ }
309
+
310
+ async upgradeAnonymousUser(uid: string, email: string): Promise<User> {
311
+ const userRef = doc(this.db, USERS_COLLECTION, uid);
312
+ const userDoc = await getDoc(userRef);
313
+
314
+ if (!userDoc.exists()) {
315
+ throw USER_ERRORS.NOT_FOUND;
316
+ }
317
+
318
+ await updateDoc(userRef, {
319
+ email: email,
320
+ isAnonymous: false,
321
+ updatedAt: serverTimestamp(),
322
+ });
323
+
324
+ return this.getUserById(uid);
325
+ }
326
+
327
+ async updateUser(
328
+ uid: string,
329
+ updates: Partial<Omit<User, "uid">>
330
+ ): Promise<User> {
331
+ const userRef = doc(this.db, USERS_COLLECTION, uid);
332
+ const userDoc = await getDoc(userRef);
333
+
334
+ if (!userDoc.exists()) {
335
+ throw USER_ERRORS.NOT_FOUND;
336
+ }
337
+
338
+ try {
339
+ const currentUser = userDoc.data() as User;
340
+ const updatedUser = {
341
+ ...currentUser,
342
+ ...updates,
343
+ updatedAt: serverTimestamp(),
344
+ };
345
+
346
+ // Validate the complete updated user object
347
+ userSchema.parse(updatedUser);
348
+
349
+ // Update only the specified fields plus updatedAt
350
+ await updateDoc(userRef, {
351
+ ...updates,
352
+ updatedAt: serverTimestamp(),
353
+ });
354
+
355
+ return this.getUserById(uid);
356
+ } catch (error) {
357
+ if (error instanceof z.ZodError) {
358
+ throw USER_ERRORS.VALIDATION_ERROR;
359
+ }
360
+ throw error;
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Dodaje novu rolu korisniku
366
+ */
367
+ async addRole(
368
+ uid: string,
369
+ role: UserRole,
370
+ options?: {
371
+ clinicAdminData?: {
372
+ isGroupOwner: boolean;
373
+ groupToken?: string;
374
+ groupId?: string;
375
+ };
376
+ }
377
+ ): Promise<void> {
378
+ const user = await this.getUserById(uid);
379
+ if (user.roles.includes(role)) return;
380
+
381
+ const profiles = await this.createProfilesForRoles(uid, [role], options);
382
+
383
+ await updateDoc(doc(this.db, USERS_COLLECTION, uid), {
384
+ roles: [...user.roles, role],
385
+ ...profiles,
386
+ updatedAt: serverTimestamp(),
387
+ });
388
+ }
389
+
390
+ /**
391
+ * Uklanja rolu korisniku i briše odgovarajući profil
392
+ */
393
+ async removeRoleAndProfile(uid: string, role: UserRole): Promise<void> {
394
+ const user = await this.getUserById(uid);
395
+ if (!user.roles.includes(role)) return;
396
+
397
+ // Prvo brišemo profil
398
+ switch (role) {
399
+ case UserRole.PATIENT:
400
+ if (user.patientProfile) {
401
+ await this.getPatientService().deletePatientProfile(
402
+ user.patientProfile
403
+ );
404
+ }
405
+ break;
406
+ case UserRole.CLINIC_ADMIN:
407
+ if (user.adminProfile) {
408
+ await this.getClinicAdminService().deleteClinicAdmin(
409
+ user.adminProfile
410
+ );
411
+ }
412
+ break;
413
+ case UserRole.PRACTITIONER:
414
+ if (user.practitionerProfile) {
415
+ await this.getPractitionerService().deletePractitioner(
416
+ user.practitionerProfile
417
+ );
418
+ }
419
+ break;
420
+ // Dodati ostale role po potrebi
421
+ }
422
+
423
+ // Zatim uklanjamo rolu
424
+ await updateDoc(doc(this.db, USERS_COLLECTION, uid), {
425
+ roles: user.roles.filter((r) => r !== role),
426
+ updatedAt: serverTimestamp(),
427
+ });
428
+ }
429
+
430
+ // Delete operations
431
+ async deleteUser(uid: string): Promise<void> {
432
+ const userRef = doc(this.db, USERS_COLLECTION, uid);
433
+ const userDoc = await getDoc(userRef);
434
+
435
+ if (!userDoc.exists()) {
436
+ throw USER_ERRORS.NOT_FOUND;
437
+ }
438
+
439
+ const userData = userDoc.data() as User;
440
+
441
+ try {
442
+ // Delete all associated profiles
443
+ if (userData.patientProfile) {
444
+ await this.getPatientService().deletePatientProfile(
445
+ userData.patientProfile
446
+ );
447
+ }
448
+
449
+ if (userData.practitionerProfile) {
450
+ await this.getPractitionerService().deletePractitioner(
451
+ userData.practitionerProfile
452
+ );
453
+ }
454
+
455
+ if (userData.adminProfile) {
456
+ await this.getClinicAdminService().deleteClinicAdmin(
457
+ userData.adminProfile
458
+ );
459
+ }
460
+
461
+ await deleteDoc(userRef);
462
+ } catch (error) {
463
+ throw error;
464
+ }
465
+ }
466
+ }