@blackcode_sa/metaestetics-api 1.5.28 → 1.5.30

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 (49) hide show
  1. package/dist/admin/index.d.mts +1324 -1
  2. package/dist/admin/index.d.ts +1324 -1
  3. package/dist/admin/index.js +1674 -2
  4. package/dist/admin/index.mjs +1668 -2
  5. package/dist/backoffice/index.d.mts +99 -7
  6. package/dist/backoffice/index.d.ts +99 -7
  7. package/dist/index.d.mts +4036 -2372
  8. package/dist/index.d.ts +4036 -2372
  9. package/dist/index.js +2331 -2009
  10. package/dist/index.mjs +2279 -1954
  11. package/package.json +2 -1
  12. package/src/admin/aggregation/README.md +79 -0
  13. package/src/admin/aggregation/clinic/README.md +52 -0
  14. package/src/admin/aggregation/clinic/clinic.aggregation.service.ts +642 -0
  15. package/src/admin/aggregation/patient/README.md +27 -0
  16. package/src/admin/aggregation/patient/patient.aggregation.service.ts +141 -0
  17. package/src/admin/aggregation/practitioner/README.md +42 -0
  18. package/src/admin/aggregation/practitioner/practitioner.aggregation.service.ts +433 -0
  19. package/src/admin/aggregation/procedure/README.md +43 -0
  20. package/src/admin/aggregation/procedure/procedure.aggregation.service.ts +508 -0
  21. package/src/admin/index.ts +60 -4
  22. package/src/admin/mailing/README.md +95 -0
  23. package/src/admin/mailing/base.mailing.service.ts +131 -0
  24. package/src/admin/mailing/index.ts +2 -0
  25. package/src/admin/mailing/practitionerInvite/index.ts +1 -0
  26. package/src/admin/mailing/practitionerInvite/practitionerInvite.mailing.ts +256 -0
  27. package/src/admin/mailing/practitionerInvite/templates/invitation.template.ts +101 -0
  28. package/src/index.ts +28 -4
  29. package/src/services/README.md +106 -0
  30. package/src/services/clinic/README.md +87 -0
  31. package/src/services/clinic/clinic.service.ts +197 -107
  32. package/src/services/clinic/utils/clinic.utils.ts +68 -119
  33. package/src/services/clinic/utils/filter.utils.d.ts +23 -0
  34. package/src/services/clinic/utils/filter.utils.ts +264 -0
  35. package/src/services/practitioner/README.md +145 -0
  36. package/src/services/practitioner/practitioner.service.ts +439 -104
  37. package/src/services/procedure/README.md +88 -0
  38. package/src/services/procedure/procedure.service.ts +521 -311
  39. package/src/services/reviews/reviews.service.ts +842 -0
  40. package/src/types/clinic/index.ts +24 -56
  41. package/src/types/practitioner/index.ts +34 -33
  42. package/src/types/procedure/index.ts +32 -0
  43. package/src/types/profile/index.ts +1 -1
  44. package/src/types/reviews/index.ts +126 -0
  45. package/src/validations/clinic.schema.ts +37 -64
  46. package/src/validations/practitioner.schema.ts +42 -32
  47. package/src/validations/procedure.schema.ts +11 -3
  48. package/src/validations/reviews.schema.ts +189 -0
  49. package/src/services/clinic/utils/review.utils.ts +0 -93
@@ -20,9 +20,9 @@ var NotificationStatus = /* @__PURE__ */ ((NotificationStatus2) => {
20
20
  import * as admin from "firebase-admin";
21
21
  import { Expo } from "expo-server-sdk";
22
22
  var NotificationsAdmin = class {
23
- constructor(firestore2) {
23
+ constructor(firestore7) {
24
24
  this.expo = new Expo();
25
- this.db = firestore2 || admin.firestore();
25
+ this.db = firestore7 || admin.firestore();
26
26
  }
27
27
  /**
28
28
  * Dohvata notifikaciju po ID-u
@@ -186,6 +186,1663 @@ var NotificationsAdmin = class {
186
186
  }
187
187
  };
188
188
 
189
+ // src/admin/aggregation/clinic/clinic.aggregation.service.ts
190
+ import * as admin2 from "firebase-admin";
191
+
192
+ // src/types/practitioner/index.ts
193
+ var PRACTITIONERS_COLLECTION = "practitioners";
194
+
195
+ // src/types/procedure/index.ts
196
+ var PROCEDURES_COLLECTION = "procedures";
197
+
198
+ // src/types/clinic/index.ts
199
+ var CLINIC_GROUPS_COLLECTION = "clinic_groups";
200
+ var CLINICS_COLLECTION = "clinics";
201
+
202
+ // src/types/patient/index.ts
203
+ var PATIENTS_COLLECTION = "patients";
204
+
205
+ // src/admin/aggregation/clinic/clinic.aggregation.service.ts
206
+ var CALENDAR_SUBCOLLECTION_ID = "calendar";
207
+ var ClinicAggregationService = class {
208
+ /**
209
+ * Constructor for ClinicAggregationService.
210
+ * @param firestore Optional Firestore instance. If not provided, it uses the default admin SDK instance.
211
+ */
212
+ constructor(firestore7) {
213
+ this.db = firestore7 || admin2.firestore();
214
+ }
215
+ /**
216
+ * Adds clinic information to a clinic group when a new clinic is created
217
+ * @param clinicGroupId - ID of the parent clinic group
218
+ * @param clinicInfo - The clinic information to add to the group
219
+ * @returns {Promise<void>}
220
+ * @throws Will throw an error if the batch write fails
221
+ */
222
+ async addClinicToClinicGroup(clinicGroupId, clinicInfo) {
223
+ if (!clinicGroupId) {
224
+ console.log(
225
+ "[ClinicAggregationService] No Clinic Group ID provided for clinic addition. Skipping."
226
+ );
227
+ return;
228
+ }
229
+ const clinicId = clinicInfo.id;
230
+ const groupRef = this.db.collection(CLINIC_GROUPS_COLLECTION).doc(clinicGroupId);
231
+ console.log(
232
+ `[ClinicAggregationService] Adding ClinicInfo (ID: ${clinicId}) to Clinic Group ${clinicGroupId}.`
233
+ );
234
+ try {
235
+ await groupRef.update({
236
+ clinicsInfo: admin2.firestore.FieldValue.arrayUnion(clinicInfo),
237
+ clinicIds: admin2.firestore.FieldValue.arrayUnion(clinicId),
238
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
239
+ });
240
+ console.log(
241
+ `[ClinicAggregationService] Successfully added ClinicInfo (ID: ${clinicId}) to Clinic Group ${clinicGroupId}.`
242
+ );
243
+ } catch (error) {
244
+ console.error(
245
+ `[ClinicAggregationService] Error adding ClinicInfo (ID: ${clinicId}) to Clinic Group ${clinicGroupId}:`,
246
+ error
247
+ );
248
+ throw error;
249
+ }
250
+ }
251
+ /**
252
+ * Updates the ClinicInfo within the clinicsInfo array for multiple practitioners.
253
+ * This method is designed to be called when a clinic's core information changes.
254
+ * @param practitionerIds - IDs of practitioners associated with the clinic.
255
+ * @param clinicInfo - The updated ClinicInfo object to aggregate.
256
+ * @returns {Promise<void>}
257
+ * @throws Will throw an error if the batch write fails.
258
+ */
259
+ async updateClinicInfoInPractitioners(practitionerIds, clinicInfo) {
260
+ if (!practitionerIds || practitionerIds.length === 0) {
261
+ console.log(
262
+ "[ClinicAggregationService] No practitioner IDs provided for clinic info update. Skipping."
263
+ );
264
+ return;
265
+ }
266
+ const batch = this.db.batch();
267
+ const clinicId = clinicInfo.id;
268
+ console.log(
269
+ `[ClinicAggregationService] Starting batch update of ClinicInfo (ID: ${clinicId}) in ${practitionerIds.length} practitioners.`
270
+ );
271
+ for (const practitionerId of practitionerIds) {
272
+ const practitionerRef = this.db.collection(PRACTITIONERS_COLLECTION).doc(practitionerId);
273
+ batch.update(practitionerRef, {
274
+ clinicsInfo: admin2.firestore.FieldValue.arrayRemove({ id: clinicId }),
275
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
276
+ });
277
+ batch.update(practitionerRef, {
278
+ clinicsInfo: admin2.firestore.FieldValue.arrayUnion(clinicInfo),
279
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
280
+ });
281
+ }
282
+ try {
283
+ await batch.commit();
284
+ console.log(
285
+ `[ClinicAggregationService] Successfully updated ClinicInfo (ID: ${clinicId}) in ${practitionerIds.length} practitioners.`
286
+ );
287
+ } catch (error) {
288
+ console.error(
289
+ `[ClinicAggregationService] Error committing batch update for ClinicInfo (ID: ${clinicId}) in practitioners:`,
290
+ error
291
+ );
292
+ throw error;
293
+ }
294
+ }
295
+ /**
296
+ * Updates the aggregated clinicInfo field within relevant Procedure documents.
297
+ * @param procedureIds IDs of procedures performed at the clinic.
298
+ * @param clinicInfo The updated ClinicInfo object.
299
+ */
300
+ async updateClinicInfoInProcedures(procedureIds, clinicInfo) {
301
+ if (!procedureIds || procedureIds.length === 0) {
302
+ console.log(
303
+ "[ClinicAggregationService] No procedure IDs provided for clinic info update. Skipping."
304
+ );
305
+ return;
306
+ }
307
+ const batch = this.db.batch();
308
+ const clinicId = clinicInfo.id;
309
+ console.log(
310
+ `[ClinicAggregationService] Starting batch update of clinicInfo field (for Clinic ID: ${clinicId}) in ${procedureIds.length} procedures.`
311
+ );
312
+ for (const procedureId of procedureIds) {
313
+ const procedureRef = this.db.collection(PROCEDURES_COLLECTION).doc(procedureId);
314
+ batch.update(procedureRef, {
315
+ clinicInfo,
316
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
317
+ });
318
+ }
319
+ try {
320
+ await batch.commit();
321
+ console.log(
322
+ `[ClinicAggregationService] Successfully updated clinicInfo field in ${procedureIds.length} procedures for clinic ${clinicId}.`
323
+ );
324
+ } catch (error) {
325
+ console.error(
326
+ `[ClinicAggregationService] Error committing batch update for clinicInfo field in procedures (Clinic ID: ${clinicId}):`,
327
+ error
328
+ );
329
+ throw error;
330
+ }
331
+ }
332
+ /**
333
+ * Updates the aggregated clinicsInfo array within the parent ClinicGroup document.
334
+ * @param clinicGroupId The ID of the parent clinic group.
335
+ * @param clinicInfo The updated ClinicInfo object.
336
+ */
337
+ async updateClinicInfoInClinicGroup(clinicGroupId, clinicInfo) {
338
+ if (!clinicGroupId) {
339
+ console.log(
340
+ "[ClinicAggregationService] No Clinic Group ID provided for clinic info update. Skipping."
341
+ );
342
+ return;
343
+ }
344
+ const batch = this.db.batch();
345
+ const clinicId = clinicInfo.id;
346
+ const groupRef = this.db.collection(CLINIC_GROUPS_COLLECTION).doc(clinicGroupId);
347
+ console.log(
348
+ `[ClinicAggregationService] Starting update of ClinicInfo (ID: ${clinicId}) in Clinic Group ${clinicGroupId}.`
349
+ );
350
+ batch.update(groupRef, {
351
+ clinicsInfo: admin2.firestore.FieldValue.arrayRemove({ id: clinicId }),
352
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
353
+ });
354
+ batch.update(groupRef, {
355
+ clinicsInfo: admin2.firestore.FieldValue.arrayUnion(clinicInfo),
356
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
357
+ });
358
+ try {
359
+ await batch.commit();
360
+ console.log(
361
+ `[ClinicAggregationService] Successfully updated ClinicInfo (ID: ${clinicId}) in Clinic Group ${clinicGroupId}.`
362
+ );
363
+ } catch (error) {
364
+ console.error(
365
+ `[ClinicAggregationService] Error committing update for ClinicInfo (ID: ${clinicId}) in Clinic Group ${clinicGroupId}:`,
366
+ error
367
+ );
368
+ throw error;
369
+ }
370
+ }
371
+ /**
372
+ * Updates relevant clinic information within Patient documents.
373
+ * NOTE: PatientProfile stores an array of PatientClinic objects, which only contain
374
+ * clinicId, assignedAt, assignedBy, isActive, notes. It does *not* store aggregated
375
+ * ClinicInfo (like name, photo). Therefore, this method currently has limited use
376
+ * for general clinic info updates. It might be relevant if Clinic.isActive status changes.
377
+ *
378
+ * @param patientIds IDs of patients associated with the clinic (e.g., from PatientProfile.clinicIds).
379
+ * @param clinicInfo The updated ClinicInfo object (primarily for logging/context).
380
+ * @param clinicIsActive The current active status of the updated clinic.
381
+ */
382
+ async updateClinicInfoInPatients(patientIds, clinicInfo, clinicIsActive) {
383
+ if (!patientIds || patientIds.length === 0) {
384
+ console.log(
385
+ "[ClinicAggregationService] No patient IDs provided for clinic info update. Skipping."
386
+ );
387
+ return;
388
+ }
389
+ const clinicId = clinicInfo.id;
390
+ console.warn(
391
+ `[ClinicAggregationService] updateClinicInfoInPatients called for clinic ${clinicId}. Current PatientProfile structure doesn't store full ClinicInfo per patient clinic entry. Consider specific logic if Clinic active status changes or if structure evolves. No direct patient updates performed by this method for info changes. Clinic isActive: ${clinicIsActive}`,
392
+ { patientIds, clinicInfo }
393
+ );
394
+ }
395
+ /**
396
+ * Updates the eventLocation for upcoming calendar events associated with a specific clinic.
397
+ * Uses a collection group query to find relevant events across all potential parent collections.
398
+ *
399
+ * @param clinicId The ID of the clinic whose location might have changed.
400
+ * @param newLocation The new ClinicLocation object.
401
+ */
402
+ async updateClinicLocationInCalendarEvents(clinicId, newLocation) {
403
+ if (!clinicId || !newLocation) {
404
+ console.log(
405
+ "[ClinicAggregationService] Missing clinicId or newLocation for calendar update. Skipping."
406
+ );
407
+ return;
408
+ }
409
+ console.log(
410
+ `[ClinicAggregationService] Querying upcoming calendar events via collection group '${CALENDAR_SUBCOLLECTION_ID}' for clinic ${clinicId} to update location.`
411
+ );
412
+ const now = admin2.firestore.Timestamp.now();
413
+ const calendarEventsQuery = this.db.collectionGroup(CALENDAR_SUBCOLLECTION_ID).where("clinicBranchId", "==", clinicId).where("eventTime.start", ">", now);
414
+ try {
415
+ const snapshot = await calendarEventsQuery.get();
416
+ if (snapshot.empty) {
417
+ console.log(
418
+ `[ClinicAggregationService] No upcoming calendar events found via collection group for clinic ${clinicId}. No location updates needed.`
419
+ );
420
+ return;
421
+ }
422
+ const batch = this.db.batch();
423
+ snapshot.docs.forEach((doc) => {
424
+ console.log(
425
+ `[ClinicAggregationService] Updating location for calendar event ${doc.ref.path}`
426
+ );
427
+ batch.update(doc.ref, {
428
+ eventLocation: newLocation,
429
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
430
+ });
431
+ });
432
+ await batch.commit();
433
+ console.log(
434
+ `[ClinicAggregationService] Successfully updated location in ${snapshot.size} upcoming calendar events via collection group for clinic ${clinicId}.`
435
+ );
436
+ } catch (error) {
437
+ console.error(
438
+ `[ClinicAggregationService] Error updating location in calendar events via collection group for clinic ${clinicId}:`,
439
+ error
440
+ );
441
+ throw error;
442
+ }
443
+ }
444
+ /**
445
+ * Updates clinic info in all upcoming calendar events associated with a specific clinic.
446
+ * @param clinicId The ID of the clinic whose info has been updated.
447
+ * @param clinicInfo The updated ClinicInfo object.
448
+ */
449
+ async updateClinicInfoInCalendarEvents(clinicId, clinicInfo) {
450
+ if (!clinicId || !clinicInfo) {
451
+ console.log(
452
+ "[ClinicAggregationService] Missing clinicId or clinicInfo for calendar update. Skipping."
453
+ );
454
+ return;
455
+ }
456
+ console.log(
457
+ `[ClinicAggregationService] Querying upcoming calendar events for clinic ${clinicId} to update clinic info.`
458
+ );
459
+ const now = admin2.firestore.Timestamp.now();
460
+ const calendarEventsQuery = this.db.collectionGroup(CALENDAR_SUBCOLLECTION_ID).where("clinicBranchId", "==", clinicId).where("eventTime.start", ">", now);
461
+ try {
462
+ const snapshot = await calendarEventsQuery.get();
463
+ if (snapshot.empty) {
464
+ console.log(
465
+ `[ClinicAggregationService] No upcoming calendar events found for clinic ${clinicId}. No clinic info updates needed.`
466
+ );
467
+ return;
468
+ }
469
+ const batch = this.db.batch();
470
+ snapshot.docs.forEach((doc) => {
471
+ console.log(
472
+ `[ClinicAggregationService] Updating clinic info for calendar event ${doc.ref.path}`
473
+ );
474
+ batch.update(doc.ref, {
475
+ clinicInfo,
476
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
477
+ });
478
+ });
479
+ await batch.commit();
480
+ console.log(
481
+ `[ClinicAggregationService] Successfully updated clinic info in ${snapshot.size} upcoming calendar events for clinic ${clinicId}.`
482
+ );
483
+ } catch (error) {
484
+ console.error(
485
+ `[ClinicAggregationService] Error updating clinic info in calendar events for clinic ${clinicId}:`,
486
+ error
487
+ );
488
+ throw error;
489
+ }
490
+ }
491
+ /**
492
+ * Removes clinic from practitioners when a clinic is deleted.
493
+ * @param practitionerIds IDs of practitioners associated with the clinic.
494
+ * @param clinicId The ID of the deleted clinic.
495
+ */
496
+ async removeClinicFromPractitioners(practitionerIds, clinicId) {
497
+ if (!practitionerIds || practitionerIds.length === 0) {
498
+ console.log(
499
+ "[ClinicAggregationService] No practitioner IDs provided for clinic removal. Skipping."
500
+ );
501
+ return;
502
+ }
503
+ const batch = this.db.batch();
504
+ console.log(
505
+ `[ClinicAggregationService] Starting batch removal of Clinic (ID: ${clinicId}) from ${practitionerIds.length} practitioners.`
506
+ );
507
+ for (const practitionerId of practitionerIds) {
508
+ const practitionerRef = this.db.collection(PRACTITIONERS_COLLECTION).doc(practitionerId);
509
+ batch.update(practitionerRef, {
510
+ clinicIds: admin2.firestore.FieldValue.arrayRemove(clinicId),
511
+ // Remove all clinic info objects where id matches the clinic ID
512
+ clinicsInfo: admin2.firestore.FieldValue.arrayRemove({ id: clinicId }),
513
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
514
+ });
515
+ }
516
+ try {
517
+ await batch.commit();
518
+ console.log(
519
+ `[ClinicAggregationService] Successfully removed Clinic (ID: ${clinicId}) from ${practitionerIds.length} practitioners.`
520
+ );
521
+ } catch (error) {
522
+ console.error(
523
+ `[ClinicAggregationService] Error committing batch removal for Clinic (ID: ${clinicId}) from practitioners:`,
524
+ error
525
+ );
526
+ throw error;
527
+ }
528
+ }
529
+ /**
530
+ * Inactivates all procedures associated with a deleted clinic
531
+ * @param procedureIds IDs of procedures associated with the clinic
532
+ */
533
+ async inactivateProceduresForClinic(procedureIds) {
534
+ if (!procedureIds || procedureIds.length === 0) {
535
+ console.log(
536
+ "[ClinicAggregationService] No procedure IDs provided for inactivation. Skipping."
537
+ );
538
+ return;
539
+ }
540
+ const batch = this.db.batch();
541
+ console.log(
542
+ `[ClinicAggregationService] Starting inactivation of ${procedureIds.length} procedures.`
543
+ );
544
+ for (const procedureId of procedureIds) {
545
+ const procedureRef = this.db.collection(PROCEDURES_COLLECTION).doc(procedureId);
546
+ batch.update(procedureRef, {
547
+ isActive: false,
548
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
549
+ });
550
+ }
551
+ try {
552
+ await batch.commit();
553
+ console.log(
554
+ `[ClinicAggregationService] Successfully inactivated ${procedureIds.length} procedures.`
555
+ );
556
+ } catch (error) {
557
+ console.error(
558
+ `[ClinicAggregationService] Error committing batch inactivation of procedures:`,
559
+ error
560
+ );
561
+ throw error;
562
+ }
563
+ }
564
+ /**
565
+ * Removes clinic from clinic group when a clinic is deleted
566
+ * @param clinicGroupId ID of the parent clinic group
567
+ * @param clinicId ID of the deleted clinic
568
+ */
569
+ async removeClinicFromClinicGroup(clinicGroupId, clinicId) {
570
+ if (!clinicGroupId) {
571
+ console.log(
572
+ "[ClinicAggregationService] No Clinic Group ID provided for clinic removal. Skipping."
573
+ );
574
+ return;
575
+ }
576
+ const groupRef = this.db.collection(CLINIC_GROUPS_COLLECTION).doc(clinicGroupId);
577
+ console.log(
578
+ `[ClinicAggregationService] Removing Clinic (ID: ${clinicId}) from Clinic Group ${clinicGroupId}.`
579
+ );
580
+ try {
581
+ await groupRef.update({
582
+ clinicIds: admin2.firestore.FieldValue.arrayRemove(clinicId),
583
+ // Remove all clinic info objects where id matches the clinic ID
584
+ clinicsInfo: admin2.firestore.FieldValue.arrayRemove({ id: clinicId }),
585
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
586
+ });
587
+ console.log(
588
+ `[ClinicAggregationService] Successfully removed Clinic (ID: ${clinicId}) from Clinic Group ${clinicGroupId}.`
589
+ );
590
+ } catch (error) {
591
+ console.error(
592
+ `[ClinicAggregationService] Error removing Clinic (ID: ${clinicId}) from Clinic Group ${clinicGroupId}:`,
593
+ error
594
+ );
595
+ throw error;
596
+ }
597
+ }
598
+ /**
599
+ * Removes clinic from patients when a clinic is deleted
600
+ * @param patientIds IDs of patients associated with the clinic
601
+ * @param clinicId ID of the deleted clinic
602
+ */
603
+ async removeClinicFromPatients(patientIds, clinicId) {
604
+ if (!patientIds || patientIds.length === 0) {
605
+ console.log(
606
+ "[ClinicAggregationService] No patient IDs provided for clinic removal. Skipping."
607
+ );
608
+ return;
609
+ }
610
+ const batch = this.db.batch();
611
+ console.log(
612
+ `[ClinicAggregationService] Starting batch removal of Clinic (ID: ${clinicId}) from ${patientIds.length} patients.`
613
+ );
614
+ for (const patientId of patientIds) {
615
+ const patientRef = this.db.collection(PATIENTS_COLLECTION).doc(patientId);
616
+ batch.update(patientRef, {
617
+ clinicIds: admin2.firestore.FieldValue.arrayRemove(clinicId),
618
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
619
+ });
620
+ }
621
+ try {
622
+ await batch.commit();
623
+ console.log(
624
+ `[ClinicAggregationService] Successfully removed Clinic (ID: ${clinicId}) from ${patientIds.length} patients.`
625
+ );
626
+ } catch (error) {
627
+ console.error(
628
+ `[ClinicAggregationService] Error committing batch removal for Clinic (ID: ${clinicId}) from patients:`,
629
+ error
630
+ );
631
+ throw error;
632
+ }
633
+ }
634
+ /**
635
+ * Cancels all upcoming calendar events associated with a deleted clinic
636
+ * @param clinicId ID of the deleted clinic
637
+ */
638
+ async cancelUpcomingCalendarEventsForClinic(clinicId) {
639
+ if (!clinicId) {
640
+ console.log(
641
+ "[ClinicAggregationService] No clinic ID provided for canceling calendar events. Skipping."
642
+ );
643
+ return;
644
+ }
645
+ console.log(
646
+ `[ClinicAggregationService] Querying upcoming calendar events for clinic ${clinicId} to cancel.`
647
+ );
648
+ const now = admin2.firestore.Timestamp.now();
649
+ const calendarEventsQuery = this.db.collectionGroup(CALENDAR_SUBCOLLECTION_ID).where("clinicBranchId", "==", clinicId).where("eventTime.start", ">", now);
650
+ try {
651
+ const snapshot = await calendarEventsQuery.get();
652
+ if (snapshot.empty) {
653
+ console.log(
654
+ `[ClinicAggregationService] No upcoming calendar events found for clinic ${clinicId}. No events to cancel.`
655
+ );
656
+ return;
657
+ }
658
+ const batch = this.db.batch();
659
+ snapshot.docs.forEach((doc) => {
660
+ console.log(
661
+ `[ClinicAggregationService] Canceling calendar event ${doc.ref.path}`
662
+ );
663
+ batch.update(doc.ref, {
664
+ status: "CANCELED",
665
+ cancelReason: "Clinic deleted",
666
+ updatedAt: admin2.firestore.FieldValue.serverTimestamp()
667
+ });
668
+ });
669
+ await batch.commit();
670
+ console.log(
671
+ `[ClinicAggregationService] Successfully canceled ${snapshot.size} upcoming calendar events for clinic ${clinicId}.`
672
+ );
673
+ } catch (error) {
674
+ console.error(
675
+ `[ClinicAggregationService] Error canceling calendar events for clinic ${clinicId}:`,
676
+ error
677
+ );
678
+ throw error;
679
+ }
680
+ }
681
+ };
682
+
683
+ // src/admin/aggregation/practitioner/practitioner.aggregation.service.ts
684
+ import * as admin3 from "firebase-admin";
685
+ var CALENDAR_SUBCOLLECTION_ID2 = "calendar";
686
+ var PractitionerAggregationService = class {
687
+ constructor(firestore7) {
688
+ this.db = firestore7 || admin3.firestore();
689
+ }
690
+ /**
691
+ * Adds practitioner information to a clinic when a new practitioner is created
692
+ * @param clinicId - ID of the clinic to update
693
+ * @param doctorInfo - Doctor information to add to the clinic
694
+ * @returns {Promise<void>}
695
+ */
696
+ async addPractitionerToClinic(clinicId, doctorInfo) {
697
+ if (!clinicId || !doctorInfo) {
698
+ console.log(
699
+ "[PractitionerAggregationService] Missing clinicId or doctorInfo for adding practitioner to clinic. Skipping."
700
+ );
701
+ return;
702
+ }
703
+ const practitionerId = doctorInfo.id;
704
+ console.log(
705
+ `[PractitionerAggregationService] Adding practitioner ${practitionerId} to clinic ${clinicId}.`
706
+ );
707
+ const clinicRef = this.db.collection(CLINICS_COLLECTION).doc(clinicId);
708
+ try {
709
+ await clinicRef.update({
710
+ doctors: admin3.firestore.FieldValue.arrayUnion(practitionerId),
711
+ doctorsInfo: admin3.firestore.FieldValue.arrayUnion(doctorInfo),
712
+ updatedAt: admin3.firestore.FieldValue.serverTimestamp()
713
+ });
714
+ console.log(
715
+ `[PractitionerAggregationService] Successfully added practitioner ${practitionerId} to clinic ${clinicId}.`
716
+ );
717
+ } catch (error) {
718
+ console.error(
719
+ `[PractitionerAggregationService] Error adding practitioner ${practitionerId} to clinic ${clinicId}:`,
720
+ error
721
+ );
722
+ throw error;
723
+ }
724
+ }
725
+ /**
726
+ * Updates practitioner information in associated clinics
727
+ * @param clinicIds - IDs of clinics associated with the practitioner
728
+ * @param doctorInfo - Updated doctor information
729
+ * @returns {Promise<void>}
730
+ */
731
+ async updatePractitionerInfoInClinics(clinicIds, doctorInfo) {
732
+ if (!clinicIds || clinicIds.length === 0 || !doctorInfo) {
733
+ console.log(
734
+ "[PractitionerAggregationService] Missing clinicIds or doctorInfo for updating practitioner in clinics. Skipping."
735
+ );
736
+ return;
737
+ }
738
+ const batch = this.db.batch();
739
+ const practitionerId = doctorInfo.id;
740
+ console.log(
741
+ `[PractitionerAggregationService] Starting batch update of practitioner ${practitionerId} in ${clinicIds.length} clinics.`
742
+ );
743
+ for (const clinicId of clinicIds) {
744
+ const clinicRef = this.db.collection(CLINICS_COLLECTION).doc(clinicId);
745
+ batch.update(clinicRef, {
746
+ doctorsInfo: admin3.firestore.FieldValue.arrayRemove({
747
+ id: practitionerId
748
+ }),
749
+ updatedAt: admin3.firestore.FieldValue.serverTimestamp()
750
+ });
751
+ batch.update(clinicRef, {
752
+ doctorsInfo: admin3.firestore.FieldValue.arrayUnion(doctorInfo),
753
+ updatedAt: admin3.firestore.FieldValue.serverTimestamp()
754
+ });
755
+ }
756
+ try {
757
+ await batch.commit();
758
+ console.log(
759
+ `[PractitionerAggregationService] Successfully updated practitioner ${practitionerId} info in ${clinicIds.length} clinics.`
760
+ );
761
+ } catch (error) {
762
+ console.error(
763
+ `[PractitionerAggregationService] Error updating practitioner ${practitionerId} info in clinics:`,
764
+ error
765
+ );
766
+ throw error;
767
+ }
768
+ }
769
+ /**
770
+ * Updates practitioner information in associated procedures
771
+ * @param procedureIds - IDs of procedures associated with the practitioner
772
+ * @param doctorInfo - Updated doctor information
773
+ * @returns {Promise<void>}
774
+ */
775
+ async updatePractitionerInfoInProcedures(procedureIds, doctorInfo) {
776
+ if (!procedureIds || procedureIds.length === 0 || !doctorInfo) {
777
+ console.log(
778
+ "[PractitionerAggregationService] Missing procedureIds or doctorInfo for updating practitioner in procedures. Skipping."
779
+ );
780
+ return;
781
+ }
782
+ const batch = this.db.batch();
783
+ const practitionerId = doctorInfo.id;
784
+ console.log(
785
+ `[PractitionerAggregationService] Starting batch update of practitioner ${practitionerId} in ${procedureIds.length} procedures.`
786
+ );
787
+ for (const procedureId of procedureIds) {
788
+ const procedureRef = this.db.collection(PROCEDURES_COLLECTION).doc(procedureId);
789
+ batch.update(procedureRef, {
790
+ doctorInfo,
791
+ updatedAt: admin3.firestore.FieldValue.serverTimestamp()
792
+ });
793
+ }
794
+ try {
795
+ await batch.commit();
796
+ console.log(
797
+ `[PractitionerAggregationService] Successfully updated practitioner ${practitionerId} info in ${procedureIds.length} procedures.`
798
+ );
799
+ } catch (error) {
800
+ console.error(
801
+ `[PractitionerAggregationService] Error updating practitioner ${practitionerId} info in procedures:`,
802
+ error
803
+ );
804
+ throw error;
805
+ }
806
+ }
807
+ /**
808
+ * Updates practitioner information in calendar events
809
+ * @param practitionerId - ID of the practitioner
810
+ * @param practitionerInfo - Updated practitioner information
811
+ * @returns {Promise<void>}
812
+ */
813
+ async updatePractitionerInfoInCalendarEvents(practitionerId, practitionerInfo) {
814
+ if (!practitionerId || !practitionerInfo) {
815
+ console.log(
816
+ "[PractitionerAggregationService] Missing practitionerId or practitionerInfo for calendar update. Skipping."
817
+ );
818
+ return;
819
+ }
820
+ console.log(
821
+ `[PractitionerAggregationService] Querying upcoming calendar events for practitioner ${practitionerId} to update practitioner info.`
822
+ );
823
+ const now = admin3.firestore.Timestamp.now();
824
+ const calendarEventsQuery = this.db.collectionGroup(CALENDAR_SUBCOLLECTION_ID2).where("practitionerId", "==", practitionerId).where("eventTime.start", ">", now);
825
+ try {
826
+ const snapshot = await calendarEventsQuery.get();
827
+ if (snapshot.empty) {
828
+ console.log(
829
+ `[PractitionerAggregationService] No upcoming calendar events found for practitioner ${practitionerId}. No doctor info updates needed.`
830
+ );
831
+ return;
832
+ }
833
+ const batch = this.db.batch();
834
+ snapshot.docs.forEach((doc) => {
835
+ console.log(
836
+ `[PractitionerAggregationService] Updating practitioner info for calendar event ${doc.ref.path}`
837
+ );
838
+ batch.update(doc.ref, {
839
+ practitionerInfo,
840
+ updatedAt: admin3.firestore.FieldValue.serverTimestamp()
841
+ });
842
+ });
843
+ await batch.commit();
844
+ console.log(
845
+ `[PractitionerAggregationService] Successfully updated practitioner info in ${snapshot.size} upcoming calendar events for practitioner ${practitionerId}.`
846
+ );
847
+ } catch (error) {
848
+ console.error(
849
+ `[PractitionerAggregationService] Error updating practitioner info in calendar events for practitioner ${practitionerId}:`,
850
+ error
851
+ );
852
+ throw error;
853
+ }
854
+ }
855
+ /**
856
+ * Removes practitioner from clinics when a practitioner is deleted
857
+ * @param clinicIds - IDs of clinics associated with the practitioner
858
+ * @param practitionerId - ID of the deleted practitioner
859
+ * @returns {Promise<void>}
860
+ */
861
+ async removePractitionerFromClinics(clinicIds, practitionerId) {
862
+ if (!clinicIds || clinicIds.length === 0 || !practitionerId) {
863
+ console.log(
864
+ "[PractitionerAggregationService] Missing clinicIds or practitionerId for removing practitioner from clinics. Skipping."
865
+ );
866
+ return;
867
+ }
868
+ const batch = this.db.batch();
869
+ console.log(
870
+ `[PractitionerAggregationService] Starting batch removal of practitioner ${practitionerId} from ${clinicIds.length} clinics.`
871
+ );
872
+ for (const clinicId of clinicIds) {
873
+ const clinicRef = this.db.collection(CLINICS_COLLECTION).doc(clinicId);
874
+ batch.update(clinicRef, {
875
+ doctors: admin3.firestore.FieldValue.arrayRemove(practitionerId),
876
+ // Remove all doctor info objects where id matches the practitioner ID
877
+ doctorsInfo: admin3.firestore.FieldValue.arrayRemove({
878
+ id: practitionerId
879
+ }),
880
+ updatedAt: admin3.firestore.FieldValue.serverTimestamp()
881
+ });
882
+ }
883
+ try {
884
+ await batch.commit();
885
+ console.log(
886
+ `[PractitionerAggregationService] Successfully removed practitioner ${practitionerId} from ${clinicIds.length} clinics.`
887
+ );
888
+ } catch (error) {
889
+ console.error(
890
+ `[PractitionerAggregationService] Error removing practitioner ${practitionerId} from clinics:`,
891
+ error
892
+ );
893
+ throw error;
894
+ }
895
+ }
896
+ /**
897
+ * Cancels all upcoming calendar events for a deleted practitioner
898
+ * @param practitionerId - ID of the deleted practitioner
899
+ * @returns {Promise<void>}
900
+ */
901
+ async cancelUpcomingCalendarEventsForPractitioner(practitionerId) {
902
+ if (!practitionerId) {
903
+ console.log(
904
+ "[PractitionerAggregationService] Missing practitionerId for canceling calendar events. Skipping."
905
+ );
906
+ return;
907
+ }
908
+ console.log(
909
+ `[PractitionerAggregationService] Querying upcoming calendar events for practitioner ${practitionerId} to cancel.`
910
+ );
911
+ const now = admin3.firestore.Timestamp.now();
912
+ const calendarEventsQuery = this.db.collectionGroup(CALENDAR_SUBCOLLECTION_ID2).where("practitionerId", "==", practitionerId).where("eventTime.start", ">", now);
913
+ try {
914
+ const snapshot = await calendarEventsQuery.get();
915
+ if (snapshot.empty) {
916
+ console.log(
917
+ `[PractitionerAggregationService] No upcoming calendar events found for practitioner ${practitionerId}. No events to cancel.`
918
+ );
919
+ return;
920
+ }
921
+ const batch = this.db.batch();
922
+ snapshot.docs.forEach((doc) => {
923
+ console.log(
924
+ `[PractitionerAggregationService] Canceling calendar event ${doc.ref.path}`
925
+ );
926
+ batch.update(doc.ref, {
927
+ status: "CANCELED",
928
+ cancelReason: "Practitioner deleted",
929
+ updatedAt: admin3.firestore.FieldValue.serverTimestamp()
930
+ });
931
+ });
932
+ await batch.commit();
933
+ console.log(
934
+ `[PractitionerAggregationService] Successfully canceled ${snapshot.size} upcoming calendar events for practitioner ${practitionerId}.`
935
+ );
936
+ } catch (error) {
937
+ console.error(
938
+ `[PractitionerAggregationService] Error canceling calendar events for practitioner ${practitionerId}:`,
939
+ error
940
+ );
941
+ throw error;
942
+ }
943
+ }
944
+ /**
945
+ * Removes practitioner from patients when a practitioner is deleted
946
+ * @param patientIds - IDs of patients associated with the practitioner
947
+ * @param practitionerId - ID of the deleted practitioner
948
+ * @returns {Promise<void>}
949
+ */
950
+ async removePractitionerFromPatients(patientIds, practitionerId) {
951
+ if (!patientIds || patientIds.length === 0 || !practitionerId) {
952
+ console.log(
953
+ "[PractitionerAggregationService] Missing patientIds or practitionerId for removing practitioner from patients. Skipping."
954
+ );
955
+ return;
956
+ }
957
+ const batch = this.db.batch();
958
+ console.log(
959
+ `[PractitionerAggregationService] Starting batch removal of practitioner ${practitionerId} from ${patientIds.length} patients.`
960
+ );
961
+ for (const patientId of patientIds) {
962
+ const patientRef = this.db.collection(PATIENTS_COLLECTION).doc(patientId);
963
+ batch.update(patientRef, {
964
+ doctorIds: admin3.firestore.FieldValue.arrayRemove(practitionerId),
965
+ updatedAt: admin3.firestore.FieldValue.serverTimestamp()
966
+ });
967
+ }
968
+ try {
969
+ await batch.commit();
970
+ console.log(
971
+ `[PractitionerAggregationService] Successfully removed practitioner ${practitionerId} from ${patientIds.length} patients.`
972
+ );
973
+ } catch (error) {
974
+ console.error(
975
+ `[PractitionerAggregationService] Error removing practitioner ${practitionerId} from patients:`,
976
+ error
977
+ );
978
+ throw error;
979
+ }
980
+ }
981
+ /**
982
+ * Inactivates all procedures associated with a deleted practitioner
983
+ * @param procedureIds - IDs of procedures provided by the practitioner
984
+ * @returns {Promise<void>}
985
+ */
986
+ async inactivateProceduresForPractitioner(procedureIds) {
987
+ if (!procedureIds || procedureIds.length === 0) {
988
+ console.log(
989
+ "[PractitionerAggregationService] No procedure IDs provided for inactivation. Skipping."
990
+ );
991
+ return;
992
+ }
993
+ const batch = this.db.batch();
994
+ console.log(
995
+ `[PractitionerAggregationService] Starting inactivation of ${procedureIds.length} procedures.`
996
+ );
997
+ for (const procedureId of procedureIds) {
998
+ const procedureRef = this.db.collection(PROCEDURES_COLLECTION).doc(procedureId);
999
+ batch.update(procedureRef, {
1000
+ isActive: false,
1001
+ updatedAt: admin3.firestore.FieldValue.serverTimestamp()
1002
+ });
1003
+ }
1004
+ try {
1005
+ await batch.commit();
1006
+ console.log(
1007
+ `[PractitionerAggregationService] Successfully inactivated ${procedureIds.length} procedures.`
1008
+ );
1009
+ } catch (error) {
1010
+ console.error(
1011
+ `[PractitionerAggregationService] Error committing batch inactivation of procedures:`,
1012
+ error
1013
+ );
1014
+ throw error;
1015
+ }
1016
+ }
1017
+ };
1018
+
1019
+ // src/admin/aggregation/procedure/procedure.aggregation.service.ts
1020
+ import * as admin4 from "firebase-admin";
1021
+ var CALENDAR_SUBCOLLECTION_ID3 = "calendar";
1022
+ var ProcedureAggregationService = class {
1023
+ constructor(firestore7) {
1024
+ this.db = firestore7 || admin4.firestore();
1025
+ }
1026
+ /**
1027
+ * Adds procedure information to a practitioner when a new procedure is created
1028
+ * @param practitionerId - ID of the practitioner who performs the procedure
1029
+ * @param procedureSummary - Summary information about the procedure
1030
+ * @returns {Promise<void>}
1031
+ */
1032
+ async addProcedureToPractitioner(practitionerId, procedureSummary) {
1033
+ if (!practitionerId || !procedureSummary) {
1034
+ console.log(
1035
+ "[ProcedureAggregationService] Missing practitionerId or procedureSummary for adding procedure to practitioner. Skipping."
1036
+ );
1037
+ return;
1038
+ }
1039
+ const procedureId = procedureSummary.id;
1040
+ console.log(
1041
+ `[ProcedureAggregationService] Adding procedure ${procedureId} to practitioner ${practitionerId}.`
1042
+ );
1043
+ const practitionerRef = this.db.collection(PRACTITIONERS_COLLECTION).doc(practitionerId);
1044
+ try {
1045
+ await practitionerRef.update({
1046
+ procedureIds: admin4.firestore.FieldValue.arrayUnion(procedureId),
1047
+ proceduresInfo: admin4.firestore.FieldValue.arrayUnion(procedureSummary),
1048
+ updatedAt: admin4.firestore.FieldValue.serverTimestamp()
1049
+ });
1050
+ console.log(
1051
+ `[ProcedureAggregationService] Successfully added procedure ${procedureId} to practitioner ${practitionerId}.`
1052
+ );
1053
+ } catch (error) {
1054
+ console.error(
1055
+ `[ProcedureAggregationService] Error adding procedure ${procedureId} to practitioner ${practitionerId}:`,
1056
+ error
1057
+ );
1058
+ throw error;
1059
+ }
1060
+ }
1061
+ /**
1062
+ * Adds procedure information to a clinic when a new procedure is created
1063
+ * @param clinicId - ID of the clinic where the procedure is performed
1064
+ * @param procedureSummary - Summary information about the procedure
1065
+ * @returns {Promise<void>}
1066
+ */
1067
+ async addProcedureToClinic(clinicId, procedureSummary) {
1068
+ if (!clinicId || !procedureSummary) {
1069
+ console.log(
1070
+ "[ProcedureAggregationService] Missing clinicId or procedureSummary for adding procedure to clinic. Skipping."
1071
+ );
1072
+ return;
1073
+ }
1074
+ const procedureId = procedureSummary.id;
1075
+ console.log(
1076
+ `[ProcedureAggregationService] Adding procedure ${procedureId} to clinic ${clinicId}.`
1077
+ );
1078
+ const clinicRef = this.db.collection(CLINICS_COLLECTION).doc(clinicId);
1079
+ try {
1080
+ await clinicRef.update({
1081
+ procedures: admin4.firestore.FieldValue.arrayUnion(procedureId),
1082
+ proceduresInfo: admin4.firestore.FieldValue.arrayUnion(procedureSummary),
1083
+ updatedAt: admin4.firestore.FieldValue.serverTimestamp()
1084
+ });
1085
+ console.log(
1086
+ `[ProcedureAggregationService] Successfully added procedure ${procedureId} to clinic ${clinicId}.`
1087
+ );
1088
+ } catch (error) {
1089
+ console.error(
1090
+ `[ProcedureAggregationService] Error adding procedure ${procedureId} to clinic ${clinicId}:`,
1091
+ error
1092
+ );
1093
+ throw error;
1094
+ }
1095
+ }
1096
+ /**
1097
+ * Updates procedure information in a practitioner document
1098
+ * @param practitionerId - ID of the practitioner who performs the procedure
1099
+ * @param procedureSummary - Updated summary information about the procedure
1100
+ * @returns {Promise<void>}
1101
+ */
1102
+ async updateProcedureInfoInPractitioner(practitionerId, procedureSummary) {
1103
+ if (!practitionerId || !procedureSummary) {
1104
+ console.log(
1105
+ "[ProcedureAggregationService] Missing practitionerId or procedureSummary for updating procedure in practitioner. Skipping."
1106
+ );
1107
+ return;
1108
+ }
1109
+ const procedureId = procedureSummary.id;
1110
+ console.log(
1111
+ `[ProcedureAggregationService] Updating procedure ${procedureId} info in practitioner ${practitionerId}.`
1112
+ );
1113
+ const practitionerRef = this.db.collection(PRACTITIONERS_COLLECTION).doc(practitionerId);
1114
+ try {
1115
+ await this.db.runTransaction(async (transaction) => {
1116
+ const practitionerDoc = await transaction.get(practitionerRef);
1117
+ if (!practitionerDoc.exists) {
1118
+ throw new Error(
1119
+ `Practitioner ${practitionerId} does not exist for procedure update`
1120
+ );
1121
+ }
1122
+ const practitionerData = practitionerDoc.data();
1123
+ if (!practitionerData) {
1124
+ throw new Error(
1125
+ `Practitioner ${practitionerId} data is empty for procedure update`
1126
+ );
1127
+ }
1128
+ const proceduresInfo = practitionerData.proceduresInfo || [];
1129
+ const updatedProceduresInfo = proceduresInfo.filter(
1130
+ (p) => p.id !== procedureId
1131
+ );
1132
+ updatedProceduresInfo.push(procedureSummary);
1133
+ transaction.update(practitionerRef, {
1134
+ proceduresInfo: updatedProceduresInfo,
1135
+ updatedAt: admin4.firestore.FieldValue.serverTimestamp()
1136
+ });
1137
+ });
1138
+ console.log(
1139
+ `[ProcedureAggregationService] Successfully updated procedure ${procedureId} info in practitioner ${practitionerId}.`
1140
+ );
1141
+ } catch (error) {
1142
+ console.error(
1143
+ `[ProcedureAggregationService] Error updating procedure ${procedureId} info in practitioner ${practitionerId}:`,
1144
+ error
1145
+ );
1146
+ throw error;
1147
+ }
1148
+ }
1149
+ /**
1150
+ * Updates procedure information in a clinic document
1151
+ * @param clinicId - ID of the clinic where the procedure is performed
1152
+ * @param procedureSummary - Updated summary information about the procedure
1153
+ * @returns {Promise<void>}
1154
+ */
1155
+ async updateProcedureInfoInClinic(clinicId, procedureSummary) {
1156
+ if (!clinicId || !procedureSummary) {
1157
+ console.log(
1158
+ "[ProcedureAggregationService] Missing clinicId or procedureSummary for updating procedure in clinic. Skipping."
1159
+ );
1160
+ return;
1161
+ }
1162
+ const procedureId = procedureSummary.id;
1163
+ console.log(
1164
+ `[ProcedureAggregationService] Updating procedure ${procedureId} info in clinic ${clinicId}.`
1165
+ );
1166
+ const clinicRef = this.db.collection(CLINICS_COLLECTION).doc(clinicId);
1167
+ try {
1168
+ await this.db.runTransaction(async (transaction) => {
1169
+ const clinicDoc = await transaction.get(clinicRef);
1170
+ if (!clinicDoc.exists) {
1171
+ throw new Error(
1172
+ `Clinic ${clinicId} does not exist for procedure update`
1173
+ );
1174
+ }
1175
+ const clinicData = clinicDoc.data();
1176
+ if (!clinicData) {
1177
+ throw new Error(
1178
+ `Clinic ${clinicId} data is empty for procedure update`
1179
+ );
1180
+ }
1181
+ const proceduresInfo = clinicData.proceduresInfo || [];
1182
+ const updatedProceduresInfo = proceduresInfo.filter(
1183
+ (p) => p.id !== procedureId
1184
+ );
1185
+ updatedProceduresInfo.push(procedureSummary);
1186
+ transaction.update(clinicRef, {
1187
+ proceduresInfo: updatedProceduresInfo,
1188
+ updatedAt: admin4.firestore.FieldValue.serverTimestamp()
1189
+ });
1190
+ });
1191
+ console.log(
1192
+ `[ProcedureAggregationService] Successfully updated procedure ${procedureId} info in clinic ${clinicId}.`
1193
+ );
1194
+ } catch (error) {
1195
+ console.error(
1196
+ `[ProcedureAggregationService] Error updating procedure ${procedureId} info in clinic ${clinicId}:`,
1197
+ error
1198
+ );
1199
+ throw error;
1200
+ }
1201
+ }
1202
+ /**
1203
+ * Updates procedure information in calendar events
1204
+ * @param procedureId - ID of the procedure
1205
+ * @param procedureInfo - Updated procedure information
1206
+ * @returns {Promise<void>}
1207
+ */
1208
+ async updateProcedureInfoInCalendarEvents(procedureId, procedureInfo) {
1209
+ if (!procedureId || !procedureInfo) {
1210
+ console.log(
1211
+ "[ProcedureAggregationService] Missing procedureId or procedureInfo for calendar update. Skipping."
1212
+ );
1213
+ return;
1214
+ }
1215
+ console.log(
1216
+ `[ProcedureAggregationService] Querying upcoming calendar events for procedure ${procedureId} to update procedure info.`
1217
+ );
1218
+ const now = admin4.firestore.Timestamp.now();
1219
+ const calendarEventsQuery = this.db.collectionGroup(CALENDAR_SUBCOLLECTION_ID3).where("procedureId", "==", procedureId).where("eventTime.start", ">", now);
1220
+ try {
1221
+ const snapshot = await calendarEventsQuery.get();
1222
+ if (snapshot.empty) {
1223
+ console.log(
1224
+ `[ProcedureAggregationService] No upcoming calendar events found for procedure ${procedureId}. No procedure info updates needed.`
1225
+ );
1226
+ return;
1227
+ }
1228
+ const batch = this.db.batch();
1229
+ snapshot.docs.forEach((doc) => {
1230
+ console.log(
1231
+ `[ProcedureAggregationService] Updating procedure info for calendar event ${doc.ref.path}`
1232
+ );
1233
+ batch.update(doc.ref, {
1234
+ procedureInfo,
1235
+ updatedAt: admin4.firestore.FieldValue.serverTimestamp()
1236
+ });
1237
+ });
1238
+ await batch.commit();
1239
+ console.log(
1240
+ `[ProcedureAggregationService] Successfully updated procedure info in ${snapshot.size} upcoming calendar events for procedure ${procedureId}.`
1241
+ );
1242
+ } catch (error) {
1243
+ console.error(
1244
+ `[ProcedureAggregationService] Error updating procedure info in calendar events for procedure ${procedureId}:`,
1245
+ error
1246
+ );
1247
+ throw error;
1248
+ }
1249
+ }
1250
+ /**
1251
+ * Cancels all upcoming calendar events for a procedure
1252
+ * @param procedureId - ID of the procedure
1253
+ * @returns {Promise<void>}
1254
+ */
1255
+ async cancelUpcomingCalendarEventsForProcedure(procedureId) {
1256
+ if (!procedureId) {
1257
+ console.log(
1258
+ "[ProcedureAggregationService] Missing procedureId for canceling calendar events. Skipping."
1259
+ );
1260
+ return;
1261
+ }
1262
+ console.log(
1263
+ `[ProcedureAggregationService] Querying upcoming calendar events for procedure ${procedureId} to cancel.`
1264
+ );
1265
+ const now = admin4.firestore.Timestamp.now();
1266
+ const calendarEventsQuery = this.db.collectionGroup(CALENDAR_SUBCOLLECTION_ID3).where("procedureId", "==", procedureId).where("eventTime.start", ">", now);
1267
+ try {
1268
+ const snapshot = await calendarEventsQuery.get();
1269
+ if (snapshot.empty) {
1270
+ console.log(
1271
+ `[ProcedureAggregationService] No upcoming calendar events found for procedure ${procedureId}. No events to cancel.`
1272
+ );
1273
+ return;
1274
+ }
1275
+ const batch = this.db.batch();
1276
+ snapshot.docs.forEach((doc) => {
1277
+ console.log(
1278
+ `[ProcedureAggregationService] Canceling calendar event ${doc.ref.path}`
1279
+ );
1280
+ batch.update(doc.ref, {
1281
+ status: "CANCELED",
1282
+ cancelReason: "Procedure deleted or inactivated",
1283
+ updatedAt: admin4.firestore.FieldValue.serverTimestamp()
1284
+ });
1285
+ });
1286
+ await batch.commit();
1287
+ console.log(
1288
+ `[ProcedureAggregationService] Successfully canceled ${snapshot.size} upcoming calendar events for procedure ${procedureId}.`
1289
+ );
1290
+ } catch (error) {
1291
+ console.error(
1292
+ `[ProcedureAggregationService] Error canceling calendar events for procedure ${procedureId}:`,
1293
+ error
1294
+ );
1295
+ throw error;
1296
+ }
1297
+ }
1298
+ /**
1299
+ * Removes procedure from a practitioner when a procedure is deleted or inactivated
1300
+ * @param practitionerId - ID of the practitioner who performs the procedure
1301
+ * @param procedureId - ID of the procedure
1302
+ * @returns {Promise<void>}
1303
+ */
1304
+ async removeProcedureFromPractitioner(practitionerId, procedureId) {
1305
+ if (!practitionerId || !procedureId) {
1306
+ console.log(
1307
+ "[ProcedureAggregationService] Missing practitionerId or procedureId for removing procedure from practitioner. Skipping."
1308
+ );
1309
+ return;
1310
+ }
1311
+ console.log(
1312
+ `[ProcedureAggregationService] Removing procedure ${procedureId} from practitioner ${practitionerId}.`
1313
+ );
1314
+ const practitionerRef = this.db.collection(PRACTITIONERS_COLLECTION).doc(practitionerId);
1315
+ try {
1316
+ await this.db.runTransaction(async (transaction) => {
1317
+ const practitionerDoc = await transaction.get(practitionerRef);
1318
+ if (!practitionerDoc.exists) {
1319
+ throw new Error(
1320
+ `Practitioner ${practitionerId} does not exist for procedure removal`
1321
+ );
1322
+ }
1323
+ const practitionerData = practitionerDoc.data();
1324
+ if (!practitionerData) {
1325
+ throw new Error(
1326
+ `Practitioner ${practitionerId} data is empty for procedure removal`
1327
+ );
1328
+ }
1329
+ const proceduresInfo = practitionerData.proceduresInfo || [];
1330
+ const updatedProceduresInfo = proceduresInfo.filter(
1331
+ (p) => p.id !== procedureId
1332
+ );
1333
+ transaction.update(practitionerRef, {
1334
+ procedureIds: admin4.firestore.FieldValue.arrayRemove(procedureId),
1335
+ proceduresInfo: updatedProceduresInfo,
1336
+ updatedAt: admin4.firestore.FieldValue.serverTimestamp()
1337
+ });
1338
+ });
1339
+ console.log(
1340
+ `[ProcedureAggregationService] Successfully removed procedure ${procedureId} from practitioner ${practitionerId}.`
1341
+ );
1342
+ } catch (error) {
1343
+ console.error(
1344
+ `[ProcedureAggregationService] Error removing procedure ${procedureId} from practitioner ${practitionerId}:`,
1345
+ error
1346
+ );
1347
+ throw error;
1348
+ }
1349
+ }
1350
+ /**
1351
+ * Removes procedure from a clinic when a procedure is deleted or inactivated
1352
+ * @param clinicId - ID of the clinic where the procedure is performed
1353
+ * @param procedureId - ID of the procedure
1354
+ * @returns {Promise<void>}
1355
+ */
1356
+ async removeProcedureFromClinic(clinicId, procedureId) {
1357
+ if (!clinicId || !procedureId) {
1358
+ console.log(
1359
+ "[ProcedureAggregationService] Missing clinicId or procedureId for removing procedure from clinic. Skipping."
1360
+ );
1361
+ return;
1362
+ }
1363
+ console.log(
1364
+ `[ProcedureAggregationService] Removing procedure ${procedureId} from clinic ${clinicId}.`
1365
+ );
1366
+ const clinicRef = this.db.collection(CLINICS_COLLECTION).doc(clinicId);
1367
+ try {
1368
+ await this.db.runTransaction(async (transaction) => {
1369
+ const clinicDoc = await transaction.get(clinicRef);
1370
+ if (!clinicDoc.exists) {
1371
+ throw new Error(
1372
+ `Clinic ${clinicId} does not exist for procedure removal`
1373
+ );
1374
+ }
1375
+ const clinicData = clinicDoc.data();
1376
+ if (!clinicData) {
1377
+ throw new Error(
1378
+ `Clinic ${clinicId} data is empty for procedure removal`
1379
+ );
1380
+ }
1381
+ const proceduresInfo = clinicData.proceduresInfo || [];
1382
+ const updatedProceduresInfo = proceduresInfo.filter(
1383
+ (p) => p.id !== procedureId
1384
+ );
1385
+ transaction.update(clinicRef, {
1386
+ procedures: admin4.firestore.FieldValue.arrayRemove(procedureId),
1387
+ proceduresInfo: updatedProceduresInfo,
1388
+ updatedAt: admin4.firestore.FieldValue.serverTimestamp()
1389
+ });
1390
+ });
1391
+ console.log(
1392
+ `[ProcedureAggregationService] Successfully removed procedure ${procedureId} from clinic ${clinicId}.`
1393
+ );
1394
+ } catch (error) {
1395
+ console.error(
1396
+ `[ProcedureAggregationService] Error removing procedure ${procedureId} from clinic ${clinicId}:`,
1397
+ error
1398
+ );
1399
+ throw error;
1400
+ }
1401
+ }
1402
+ };
1403
+
1404
+ // src/admin/aggregation/patient/patient.aggregation.service.ts
1405
+ import * as admin5 from "firebase-admin";
1406
+ var CALENDAR_SUBCOLLECTION_ID4 = "calendar";
1407
+ var PatientAggregationService = class {
1408
+ constructor(firestore7) {
1409
+ this.db = firestore7 || admin5.firestore();
1410
+ }
1411
+ // --- Methods for Patient Creation --- >
1412
+ // No specific aggregations defined for patient creation in the plan.
1413
+ // --- Methods for Patient Update --- >
1414
+ /**
1415
+ * Updates patient information in calendar events
1416
+ * @param patientId - ID of the patient
1417
+ * @param patientInfo - Updated patient information
1418
+ * @returns {Promise<void>}
1419
+ */
1420
+ async updatePatientInfoInCalendarEvents(patientId, patientInfo) {
1421
+ if (!patientId || !patientInfo) {
1422
+ console.log(
1423
+ "[PatientAggregationService] Missing patientId or patientInfo for calendar update. Skipping."
1424
+ );
1425
+ return;
1426
+ }
1427
+ console.log(
1428
+ `[PatientAggregationService] Querying upcoming calendar events for patient ${patientId} to update patient info.`
1429
+ );
1430
+ const now = admin5.firestore.Timestamp.now();
1431
+ const calendarEventsQuery = this.db.collectionGroup(CALENDAR_SUBCOLLECTION_ID4).where("patientId", "==", patientId).where("eventTime.start", ">", now);
1432
+ try {
1433
+ const snapshot = await calendarEventsQuery.get();
1434
+ if (snapshot.empty) {
1435
+ console.log(
1436
+ `[PatientAggregationService] No upcoming calendar events found for patient ${patientId}. No patient info updates needed.`
1437
+ );
1438
+ return;
1439
+ }
1440
+ const batch = this.db.batch();
1441
+ snapshot.docs.forEach((doc) => {
1442
+ console.log(
1443
+ `[PatientAggregationService] Updating patient info for calendar event ${doc.ref.path}`
1444
+ );
1445
+ batch.update(doc.ref, {
1446
+ patientInfo,
1447
+ updatedAt: admin5.firestore.FieldValue.serverTimestamp()
1448
+ });
1449
+ });
1450
+ await batch.commit();
1451
+ console.log(
1452
+ `[PatientAggregationService] Successfully updated patient info in ${snapshot.size} upcoming calendar events for patient ${patientId}.`
1453
+ );
1454
+ } catch (error) {
1455
+ console.error(
1456
+ `[PatientAggregationService] Error updating patient info in calendar events for patient ${patientId}:`,
1457
+ error
1458
+ );
1459
+ throw error;
1460
+ }
1461
+ }
1462
+ // --- Methods for Patient Deletion --- >
1463
+ /**
1464
+ * Cancels all upcoming calendar events associated with a deleted patient
1465
+ * @param patientId - ID of the deleted patient
1466
+ * @returns {Promise<void>}
1467
+ */
1468
+ async cancelUpcomingCalendarEventsForPatient(patientId) {
1469
+ if (!patientId) {
1470
+ console.log(
1471
+ "[PatientAggregationService] Missing patientId for canceling calendar events. Skipping."
1472
+ );
1473
+ return;
1474
+ }
1475
+ console.log(
1476
+ `[PatientAggregationService] Querying upcoming calendar events for patient ${patientId} to cancel.`
1477
+ );
1478
+ const now = admin5.firestore.Timestamp.now();
1479
+ const calendarEventsQuery = this.db.collectionGroup(CALENDAR_SUBCOLLECTION_ID4).where("patientId", "==", patientId).where("eventTime.start", ">", now);
1480
+ try {
1481
+ const snapshot = await calendarEventsQuery.get();
1482
+ if (snapshot.empty) {
1483
+ console.log(
1484
+ `[PatientAggregationService] No upcoming calendar events found for patient ${patientId}. No events to cancel.`
1485
+ );
1486
+ return;
1487
+ }
1488
+ const batch = this.db.batch();
1489
+ snapshot.docs.forEach((doc) => {
1490
+ console.log(
1491
+ `[PatientAggregationService] Canceling calendar event ${doc.ref.path}`
1492
+ );
1493
+ batch.update(doc.ref, {
1494
+ status: "CANCELED",
1495
+ cancelReason: "Patient deleted",
1496
+ updatedAt: admin5.firestore.FieldValue.serverTimestamp()
1497
+ });
1498
+ });
1499
+ await batch.commit();
1500
+ console.log(
1501
+ `[PatientAggregationService] Successfully canceled ${snapshot.size} upcoming calendar events for patient ${patientId}.`
1502
+ );
1503
+ } catch (error) {
1504
+ console.error(
1505
+ `[PatientAggregationService] Error canceling calendar events for patient ${patientId}:`,
1506
+ error
1507
+ );
1508
+ throw error;
1509
+ }
1510
+ }
1511
+ };
1512
+
1513
+ // src/admin/mailing/base.mailing.service.ts
1514
+ import * as admin6 from "firebase-admin";
1515
+ var BaseMailingService = class {
1516
+ // Removed config property as it's no longer managed here
1517
+ // protected config: MailgunConfig;
1518
+ /**
1519
+ * Constructor for BaseMailingService
1520
+ * @param firestore Firestore instance provided by the caller
1521
+ * @param mailgunClient Mailgun client instance provided by the caller
1522
+ */
1523
+ constructor(firestore7, mailgunClient) {
1524
+ this.db = firestore7;
1525
+ this.mailgunClient = mailgunClient;
1526
+ }
1527
+ /**
1528
+ * Sends an email using Mailgun
1529
+ * @param data Email data to send, including the 'from' address
1530
+ * @returns Promise with the sending result
1531
+ */
1532
+ async sendEmail(data) {
1533
+ try {
1534
+ if (!data.from) {
1535
+ throw new Error(
1536
+ "Email 'from' address must be provided in sendEmail data."
1537
+ );
1538
+ }
1539
+ return await new Promise(
1540
+ (resolve, reject) => {
1541
+ this.mailgunClient.messages().send(data, (error, body) => {
1542
+ if (error) {
1543
+ console.error("[BaseMailingService] Error sending email:", error);
1544
+ reject(error);
1545
+ } else {
1546
+ console.log(
1547
+ "[BaseMailingService] Email sent successfully:",
1548
+ body
1549
+ );
1550
+ resolve(body);
1551
+ }
1552
+ });
1553
+ }
1554
+ );
1555
+ } catch (error) {
1556
+ console.error("[BaseMailingService] Error in sendEmail:", error);
1557
+ throw error;
1558
+ }
1559
+ }
1560
+ /**
1561
+ * Logs email sending attempt to Firestore for tracking
1562
+ * @param emailData Email data that was sent
1563
+ * @param success Whether the email was sent successfully
1564
+ * @param error Error object if the email failed to send
1565
+ */
1566
+ async logEmailAttempt(emailData, success, error) {
1567
+ try {
1568
+ const emailLogRef = this.db.collection("email_logs").doc();
1569
+ await emailLogRef.set({
1570
+ to: emailData.to,
1571
+ subject: emailData.subject,
1572
+ templateName: emailData.templateName,
1573
+ success,
1574
+ error: error ? JSON.stringify(error) : null,
1575
+ sentAt: admin6.firestore.FieldValue.serverTimestamp()
1576
+ });
1577
+ } catch (logError) {
1578
+ console.error(
1579
+ "[BaseMailingService] Error logging email attempt:",
1580
+ logError
1581
+ );
1582
+ }
1583
+ }
1584
+ /**
1585
+ * Renders a simple HTML email template with variables
1586
+ * @param template HTML template string
1587
+ * @param variables Key-value pairs to replace in the template
1588
+ * @returns Rendered HTML string
1589
+ */
1590
+ renderTemplate(template, variables) {
1591
+ let rendered = template;
1592
+ Object.entries(variables).forEach(([key, value]) => {
1593
+ const regex = new RegExp(`{{\\s*${key}\\s*}}`, "g");
1594
+ rendered = rendered.replace(regex, value);
1595
+ });
1596
+ return rendered;
1597
+ }
1598
+ };
1599
+
1600
+ // src/admin/mailing/practitionerInvite/templates/invitation.template.ts
1601
+ var practitionerInvitationTemplate = `
1602
+ <!DOCTYPE html>
1603
+ <html>
1604
+ <head>
1605
+ <meta charset="UTF-8">
1606
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1607
+ <title>Join {{clinicName}} as a Practitioner</title>
1608
+ <style>
1609
+ body {
1610
+ font-family: Arial, sans-serif;
1611
+ line-height: 1.6;
1612
+ color: #333;
1613
+ margin: 0;
1614
+ padding: 0;
1615
+ }
1616
+ .container {
1617
+ max-width: 600px;
1618
+ margin: 0 auto;
1619
+ padding: 20px;
1620
+ }
1621
+ .header {
1622
+ background-color: #4A90E2;
1623
+ padding: 20px;
1624
+ text-align: center;
1625
+ color: white;
1626
+ }
1627
+ .content {
1628
+ padding: 20px;
1629
+ background-color: #f9f9f9;
1630
+ }
1631
+ .footer {
1632
+ padding: 20px;
1633
+ text-align: center;
1634
+ font-size: 12px;
1635
+ color: #888;
1636
+ }
1637
+ .button {
1638
+ display: inline-block;
1639
+ background-color: #4A90E2;
1640
+ color: white;
1641
+ text-decoration: none;
1642
+ padding: 12px 24px;
1643
+ border-radius: 4px;
1644
+ margin: 20px 0;
1645
+ font-weight: bold;
1646
+ }
1647
+ .token {
1648
+ font-size: 24px;
1649
+ font-weight: bold;
1650
+ color: #4A90E2;
1651
+ padding: 10px;
1652
+ background-color: #e9f0f9;
1653
+ border-radius: 4px;
1654
+ display: inline-block;
1655
+ letter-spacing: 2px;
1656
+ margin: 10px 0;
1657
+ }
1658
+ </style>
1659
+ </head>
1660
+ <body>
1661
+ <div class="container">
1662
+ <div class="header">
1663
+ <h1>You've Been Invited</h1>
1664
+ </div>
1665
+ <div class="content">
1666
+ <p>Hello {{practitionerName}},</p>
1667
+
1668
+ <p>You have been invited to join <strong>{{clinicName}}</strong> as a healthcare practitioner.</p>
1669
+
1670
+ <p>Your profile has been created and is ready for you to claim. Please use the following token to register:</p>
1671
+
1672
+ <div style="text-align: center;">
1673
+ <span class="token">{{inviteToken}}</span>
1674
+ </div>
1675
+
1676
+ <p>This token will expire on <strong>{{expirationDate}}</strong>.</p>
1677
+
1678
+ <p>To create your account:</p>
1679
+ <ol>
1680
+ <li>Visit {{registrationUrl}}</li>
1681
+ <li>Enter your email and create a password</li>
1682
+ <li>When prompted, enter the token above</li>
1683
+ </ol>
1684
+
1685
+ <div style="text-align: center;">
1686
+ <a href="{{registrationUrl}}" class="button">Create Your Account</a>
1687
+ </div>
1688
+
1689
+ <p>If you have any questions, please contact {{contactName}} at {{contactEmail}}.</p>
1690
+ </div>
1691
+ <div class="footer">
1692
+ <p>This is an automated message from {{clinicName}}. Please do not reply to this email.</p>
1693
+ <p>&copy; {{currentYear}} {{clinicName}}. All rights reserved.</p>
1694
+ </div>
1695
+ </div>
1696
+ </body>
1697
+ </html>
1698
+ `;
1699
+
1700
+ // src/admin/mailing/practitionerInvite/practitionerInvite.mailing.ts
1701
+ var PractitionerInviteMailingService = class extends BaseMailingService {
1702
+ /**
1703
+ * Constructor for PractitionerInviteMailingService
1704
+ * @param firestore Firestore instance provided by the caller
1705
+ * @param mailgunClient Mailgun client instance provided by the caller
1706
+ */
1707
+ constructor(firestore7, mailgunClient) {
1708
+ super(firestore7, mailgunClient);
1709
+ this.DEFAULT_REGISTRATION_URL = "https://app.medclinic.com/register";
1710
+ this.DEFAULT_SUBJECT = "You've Been Invited to Join as a Practitioner";
1711
+ this.DEFAULT_FROM_ADDRESS = "MedClinic <no-reply@your-domain.com>";
1712
+ }
1713
+ /**
1714
+ * Sends a practitioner invitation email
1715
+ * @param data The practitioner invitation data
1716
+ * @returns Promise resolved when email is sent
1717
+ */
1718
+ async sendInvitationEmail(data) {
1719
+ var _a, _b, _c, _d;
1720
+ try {
1721
+ console.log(
1722
+ "[PractitionerInviteMailingService] Sending invitation email to",
1723
+ data.token.email
1724
+ );
1725
+ const expirationDate = data.token.expiresAt.toDate().toLocaleDateString("en-US", {
1726
+ weekday: "long",
1727
+ year: "numeric",
1728
+ month: "long",
1729
+ day: "numeric"
1730
+ });
1731
+ const registrationUrl = ((_a = data.options) == null ? void 0 : _a.registrationUrl) || this.DEFAULT_REGISTRATION_URL;
1732
+ const contactName = data.clinic.contactName || "Clinic Administrator";
1733
+ const contactEmail = data.clinic.contactEmail;
1734
+ const subject = ((_b = data.options) == null ? void 0 : _b.customSubject) || this.DEFAULT_SUBJECT;
1735
+ const fromAddress = ((_c = data.options) == null ? void 0 : _c.fromAddress) || this.DEFAULT_FROM_ADDRESS;
1736
+ const currentYear = (/* @__PURE__ */ new Date()).getFullYear().toString();
1737
+ const practitionerName = `${data.practitioner.firstName} ${data.practitioner.lastName}`;
1738
+ const templateVariables = {
1739
+ clinicName: data.clinic.name,
1740
+ practitionerName,
1741
+ inviteToken: data.token.token,
1742
+ expirationDate,
1743
+ registrationUrl,
1744
+ contactName,
1745
+ contactEmail,
1746
+ currentYear
1747
+ };
1748
+ const html = this.renderTemplate(
1749
+ practitionerInvitationTemplate,
1750
+ templateVariables
1751
+ );
1752
+ const emailData = {
1753
+ to: data.token.email,
1754
+ from: fromAddress,
1755
+ subject,
1756
+ html
1757
+ };
1758
+ const result = await this.sendEmail(emailData);
1759
+ await this.logEmailAttempt(
1760
+ {
1761
+ to: data.token.email,
1762
+ subject,
1763
+ templateName: "practitioner_invitation"
1764
+ },
1765
+ true
1766
+ );
1767
+ return result;
1768
+ } catch (error) {
1769
+ console.error(
1770
+ "[PractitionerInviteMailingService] Error sending invitation email:",
1771
+ error
1772
+ );
1773
+ await this.logEmailAttempt(
1774
+ {
1775
+ to: data.token.email,
1776
+ subject: ((_d = data.options) == null ? void 0 : _d.customSubject) || this.DEFAULT_SUBJECT,
1777
+ templateName: "practitioner_invitation"
1778
+ },
1779
+ false,
1780
+ error
1781
+ );
1782
+ throw error;
1783
+ }
1784
+ }
1785
+ /**
1786
+ * Handles the practitioner token creation event from Cloud Functions
1787
+ * Fetches necessary data using defined types and collection constants,
1788
+ * and sends the invitation email.
1789
+ * @param tokenData The fully typed token object including its id
1790
+ * @param fromAddress The 'from' email address to use, obtained from config
1791
+ * @returns Promise resolved when the email is sent
1792
+ */
1793
+ async handleTokenCreationEvent(tokenData, fromAddress) {
1794
+ try {
1795
+ console.log(
1796
+ "[PractitionerInviteMailingService] Handling token creation event for token:",
1797
+ tokenData.id
1798
+ );
1799
+ const practitionerRef = this.db.collection(PRACTITIONERS_COLLECTION).doc(tokenData.practitionerId);
1800
+ const practitionerDoc = await practitionerRef.get();
1801
+ if (!practitionerDoc.exists) {
1802
+ throw new Error(`Practitioner ${tokenData.practitionerId} not found`);
1803
+ }
1804
+ const practitionerData = practitionerDoc.data();
1805
+ const clinicRef = this.db.collection(CLINICS_COLLECTION).doc(tokenData.clinicId);
1806
+ const clinicDoc = await clinicRef.get();
1807
+ if (!clinicDoc.exists) {
1808
+ throw new Error(`Clinic ${tokenData.clinicId} not found`);
1809
+ }
1810
+ const clinicData = clinicDoc.data();
1811
+ const emailData = {
1812
+ token: {
1813
+ id: tokenData.id,
1814
+ token: tokenData.token,
1815
+ practitionerId: tokenData.practitionerId,
1816
+ email: tokenData.email,
1817
+ clinicId: tokenData.clinicId,
1818
+ expiresAt: tokenData.expiresAt
1819
+ },
1820
+ practitioner: {
1821
+ firstName: practitionerData.basicInfo.firstName || "",
1822
+ lastName: practitionerData.basicInfo.lastName || ""
1823
+ },
1824
+ clinic: {
1825
+ name: clinicData.name || "Medical Clinic",
1826
+ contactEmail: clinicData.contactInfo.email || "contact@medclinic.com"
1827
+ },
1828
+ options: {
1829
+ fromAddress
1830
+ }
1831
+ };
1832
+ await this.sendInvitationEmail(emailData);
1833
+ console.log(
1834
+ "[PractitionerInviteMailingService] Invitation email sent successfully"
1835
+ );
1836
+ } catch (error) {
1837
+ console.error(
1838
+ "[PractitionerInviteMailingService] Error handling token creation event:",
1839
+ error
1840
+ );
1841
+ throw error;
1842
+ }
1843
+ }
1844
+ };
1845
+
189
1846
  // src/types/index.ts
190
1847
  var UserRole = /* @__PURE__ */ ((UserRole2) => {
191
1848
  UserRole2["PATIENT"] = "patient";
@@ -194,10 +1851,19 @@ var UserRole = /* @__PURE__ */ ((UserRole2) => {
194
1851
  UserRole2["CLINIC_ADMIN"] = "clinic_admin";
195
1852
  return UserRole2;
196
1853
  })(UserRole || {});
1854
+
1855
+ // src/admin/index.ts
1856
+ console.log("[Admin Module] Initialized and services exported.");
197
1857
  export {
1858
+ BaseMailingService,
1859
+ ClinicAggregationService,
198
1860
  NOTIFICATIONS_COLLECTION,
199
1861
  NotificationStatus,
200
1862
  NotificationType,
201
1863
  NotificationsAdmin,
1864
+ PatientAggregationService,
1865
+ PractitionerAggregationService,
1866
+ PractitionerInviteMailingService,
1867
+ ProcedureAggregationService,
202
1868
  UserRole
203
1869
  };