@blackcode_sa/metaestetics-api 1.7.32 → 1.7.34

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,811 @@
1
+ import * as admin from "firebase-admin";
2
+ import {
3
+ PractitionerInvite,
4
+ PractitionerInviteStatus,
5
+ PRACTITIONER_INVITES_COLLECTION,
6
+ } from "../../../types/clinic/practitioner-invite.types";
7
+ import { DoctorInfo } from "../../../types/clinic";
8
+ import {
9
+ Practitioner,
10
+ PRACTITIONERS_COLLECTION,
11
+ PractitionerClinicWorkingHours,
12
+ } from "../../../types/practitioner";
13
+ import { CLINICS_COLLECTION, Clinic } from "../../../types/clinic";
14
+ import { ClinicInfo } from "../../../types/profile";
15
+ import { Logger } from "../../logger";
16
+ import { ExistingPractitionerInviteMailingService } from "../../mailing/practitionerInvite/existing-practitioner-invite.mailing";
17
+
18
+ /**
19
+ * @class PractitionerInviteAggregationService
20
+ * @description Handles aggregation tasks and side effects related to practitioner invite lifecycle events.
21
+ * This service is intended to be used primarily by background functions (e.g., Cloud Functions)
22
+ * triggered by changes in the practitioner-invites collection.
23
+ */
24
+ export class PractitionerInviteAggregationService {
25
+ private db: admin.firestore.Firestore;
26
+ private mailingService?: ExistingPractitionerInviteMailingService;
27
+
28
+ /**
29
+ * Constructor for PractitionerInviteAggregationService.
30
+ * @param firestore Optional Firestore instance. If not provided, it uses the default admin SDK instance.
31
+ * @param mailingService Optional mailing service for sending emails
32
+ */
33
+ constructor(
34
+ firestore?: admin.firestore.Firestore,
35
+ mailingService?: ExistingPractitionerInviteMailingService
36
+ ) {
37
+ this.db = firestore || admin.firestore();
38
+ this.mailingService = mailingService;
39
+ Logger.info("[PractitionerInviteAggregationService] Initialized.");
40
+ }
41
+
42
+ /**
43
+ * Handles side effects when a practitioner invite is first created.
44
+ * This function would typically be called by a Firestore onCreate trigger.
45
+ * @param {PractitionerInvite} invite - The newly created PractitionerInvite object.
46
+ * @param {object} emailConfig - Optional email configuration for sending invite emails
47
+ * @returns {Promise<void>}
48
+ */
49
+ async handleInviteCreate(
50
+ invite: PractitionerInvite,
51
+ emailConfig?: {
52
+ fromAddress: string;
53
+ domain: string;
54
+ acceptUrl: string;
55
+ rejectUrl: string;
56
+ }
57
+ ): Promise<void> {
58
+ Logger.info(
59
+ `[PractitionerInviteAggService] Handling CREATE for invite: ${invite.id}, practitioner: ${invite.practitionerId}, clinic: ${invite.clinicId}, status: ${invite.status}`
60
+ );
61
+
62
+ try {
63
+ // Send invitation email to practitioner if mailing service is available
64
+ if (
65
+ this.mailingService &&
66
+ emailConfig &&
67
+ invite.status === PractitionerInviteStatus.PENDING
68
+ ) {
69
+ Logger.info(
70
+ `[PractitionerInviteAggService] Sending invitation email for invite: ${invite.id}`
71
+ );
72
+
73
+ try {
74
+ await this.mailingService.handleInviteCreationEvent(
75
+ invite,
76
+ emailConfig
77
+ );
78
+ Logger.info(
79
+ `[PractitionerInviteAggService] Successfully sent invitation email for invite: ${invite.id}`
80
+ );
81
+ } catch (emailError) {
82
+ Logger.error(
83
+ `[PractitionerInviteAggService] Error sending invitation email for invite ${invite.id}:`,
84
+ emailError
85
+ );
86
+ // Don't throw - email failure shouldn't break the invite creation
87
+ }
88
+ }
89
+
90
+ Logger.info(
91
+ `[PractitionerInviteAggService] Successfully processed CREATE for invite: ${invite.id}`
92
+ );
93
+ } catch (error) {
94
+ Logger.error(
95
+ `[PractitionerInviteAggService] Error in handleInviteCreate for invite ${invite.id}:`,
96
+ error
97
+ );
98
+ throw error;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Handles side effects when a practitioner invite is updated.
104
+ * This function would typically be called by a Firestore onUpdate trigger.
105
+ * @param {PractitionerInvite} before - The PractitionerInvite object before the update.
106
+ * @param {PractitionerInvite} after - The PractitionerInvite object after the update.
107
+ * @param {object} emailConfig - Optional email configuration for sending notification emails
108
+ * @returns {Promise<void>}
109
+ */
110
+ async handleInviteUpdate(
111
+ before: PractitionerInvite,
112
+ after: PractitionerInvite,
113
+ emailConfig?: {
114
+ fromAddress: string;
115
+ domain: string;
116
+ clinicDashboardUrl: string;
117
+ practitionerProfileUrl?: string;
118
+ findPractitionersUrl?: string;
119
+ }
120
+ ): Promise<void> {
121
+ Logger.info(
122
+ `[PractitionerInviteAggService] Handling UPDATE for invite: ${after.id}. Status ${before.status} -> ${after.status}`
123
+ );
124
+
125
+ try {
126
+ const statusChanged = before.status !== after.status;
127
+
128
+ if (statusChanged) {
129
+ Logger.info(
130
+ `[PractitionerInviteAggService] Status changed for invite ${after.id}: ${before.status} -> ${after.status}`
131
+ );
132
+
133
+ // Handle PENDING -> ACCEPTED
134
+ if (
135
+ before.status === PractitionerInviteStatus.PENDING &&
136
+ after.status === PractitionerInviteStatus.ACCEPTED
137
+ ) {
138
+ Logger.info(
139
+ `[PractitionerInviteAggService] Invite ${after.id} PENDING -> ACCEPTED. Adding practitioner to clinic.`
140
+ );
141
+ await this.handleInviteAccepted(after, emailConfig);
142
+ }
143
+
144
+ // Handle PENDING -> REJECTED
145
+ else if (
146
+ before.status === PractitionerInviteStatus.PENDING &&
147
+ after.status === PractitionerInviteStatus.REJECTED
148
+ ) {
149
+ Logger.info(
150
+ `[PractitionerInviteAggService] Invite ${after.id} PENDING -> REJECTED.`
151
+ );
152
+ await this.handleInviteRejected(after, emailConfig);
153
+ }
154
+
155
+ // Handle PENDING -> CANCELLED
156
+ else if (
157
+ before.status === PractitionerInviteStatus.PENDING &&
158
+ after.status === PractitionerInviteStatus.CANCELLED
159
+ ) {
160
+ Logger.info(
161
+ `[PractitionerInviteAggService] Invite ${after.id} PENDING -> CANCELLED.`
162
+ );
163
+ await this.handleInviteCancelled(after);
164
+ }
165
+ }
166
+
167
+ Logger.info(
168
+ `[PractitionerInviteAggService] Successfully processed UPDATE for invite: ${after.id}`
169
+ );
170
+ } catch (error) {
171
+ Logger.error(
172
+ `[PractitionerInviteAggService] Error in handleInviteUpdate for invite ${after.id}:`,
173
+ error
174
+ );
175
+ throw error;
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Handles side effects when a practitioner invite is deleted.
181
+ * @param deletedInvite - The PractitionerInvite object that was deleted.
182
+ * @returns {Promise<void>}
183
+ */
184
+ async handleInviteDelete(deletedInvite: PractitionerInvite): Promise<void> {
185
+ Logger.info(
186
+ `[PractitionerInviteAggService] Handling DELETE for invite: ${deletedInvite.id}`
187
+ );
188
+
189
+ try {
190
+ // TODO: Add cleanup logic if needed
191
+ // For now, deleting an invite doesn't require additional aggregation actions
192
+ // since the practitioner-clinic relationship would already be established if the invite was accepted
193
+
194
+ Logger.info(
195
+ `[PractitionerInviteAggService] Successfully processed DELETE for invite: ${deletedInvite.id}`
196
+ );
197
+ } catch (error) {
198
+ Logger.error(
199
+ `[PractitionerInviteAggService] Error in handleInviteDelete for invite ${deletedInvite.id}:`,
200
+ error
201
+ );
202
+ throw error;
203
+ }
204
+ }
205
+
206
+ // --- Private Helper Methods ---
207
+
208
+ /**
209
+ * Handles the business logic when a practitioner accepts an invite.
210
+ * This includes adding the practitioner to the clinic and the clinic to the practitioner.
211
+ * @param {PractitionerInvite} invite - The accepted invite
212
+ * @param {object} emailConfig - Optional email configuration for sending notification emails
213
+ * @returns {Promise<void>}
214
+ */
215
+ private async handleInviteAccepted(
216
+ invite: PractitionerInvite,
217
+ emailConfig?: {
218
+ fromAddress: string;
219
+ domain: string;
220
+ clinicDashboardUrl: string;
221
+ practitionerProfileUrl?: string;
222
+ }
223
+ ): Promise<void> {
224
+ Logger.info(
225
+ `[PractitionerInviteAggService] Processing accepted invite ${invite.id} for practitioner ${invite.practitionerId} and clinic ${invite.clinicId}`
226
+ );
227
+
228
+ try {
229
+ // Fetch the current practitioner and clinic data to ensure they exist
230
+ const [practitioner, clinic] = await Promise.all([
231
+ this.fetchPractitionerById(invite.practitionerId),
232
+ this.fetchClinicById(invite.clinicId),
233
+ ]);
234
+
235
+ if (!practitioner) {
236
+ throw new Error(
237
+ `Practitioner ${invite.practitionerId} not found during invite acceptance`
238
+ );
239
+ }
240
+
241
+ if (!clinic) {
242
+ throw new Error(
243
+ `Clinic ${invite.clinicId} not found during invite acceptance`
244
+ );
245
+ }
246
+
247
+ // Create DoctorInfo object for aggregation
248
+ const doctorInfo: DoctorInfo = {
249
+ id: practitioner.id,
250
+ name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
251
+ description: practitioner.basicInfo.bio || undefined,
252
+ photo:
253
+ typeof practitioner.basicInfo.profileImageUrl === "object" &&
254
+ practitioner.basicInfo.profileImageUrl !== null
255
+ ? (practitioner.basicInfo.profileImageUrl as any)?.url || null
256
+ : typeof practitioner.basicInfo.profileImageUrl === "string"
257
+ ? practitioner.basicInfo.profileImageUrl
258
+ : null,
259
+ rating: practitioner.reviewInfo?.averageRating || 0,
260
+ services: practitioner.proceduresInfo?.map((proc) => proc.name) || [], // Use procedure names as services
261
+ };
262
+
263
+ // Create ClinicInfo object for aggregation
264
+ const clinicInfo: ClinicInfo = {
265
+ id: clinic.id,
266
+ featuredPhoto:
267
+ typeof clinic.coverPhoto === "object" && clinic.coverPhoto !== null
268
+ ? (clinic.coverPhoto as any)?.url || ""
269
+ : typeof clinic.coverPhoto === "string"
270
+ ? clinic.coverPhoto
271
+ : "",
272
+ name: clinic.name,
273
+ description: clinic.description || null,
274
+ location: clinic.location,
275
+ contactInfo: clinic.contactInfo,
276
+ };
277
+
278
+ // Check if practitioner is already associated with the clinic
279
+ const isPractitionerInClinic = clinic.doctors.includes(practitioner.id);
280
+ const isClinicInPractitioner = practitioner.clinics.includes(clinic.id);
281
+
282
+ // Add practitioner to clinic if not already there
283
+ if (!isPractitionerInClinic) {
284
+ Logger.info(
285
+ `[PractitionerInviteAggService] Adding practitioner ${practitioner.id} to clinic ${clinic.id}`
286
+ );
287
+ await this.addPractitionerToClinic(clinic.id, doctorInfo);
288
+ } else {
289
+ Logger.info(
290
+ `[PractitionerInviteAggService] Practitioner ${practitioner.id} already in clinic ${clinic.id}, updating info`
291
+ );
292
+ await this.updatePractitionerInfoInClinic(clinic.id, doctorInfo);
293
+ }
294
+
295
+ // Add clinic to practitioner if not already there
296
+ if (!isClinicInPractitioner) {
297
+ Logger.info(
298
+ `[PractitionerInviteAggService] Adding clinic ${clinic.id} to practitioner ${practitioner.id}`
299
+ );
300
+ await this.addClinicToPractitioner(practitioner.id, clinicInfo, invite);
301
+ } else {
302
+ Logger.info(
303
+ `[PractitionerInviteAggService] Clinic ${clinic.id} already in practitioner ${practitioner.id}, updating working hours`
304
+ );
305
+ await this.updatePractitionerWorkingHours(practitioner.id, invite);
306
+ }
307
+
308
+ // Send acceptance notification email to clinic admin if mailing service is available
309
+ if (this.mailingService && emailConfig) {
310
+ Logger.info(
311
+ `[PractitionerInviteAggService] Sending acceptance notification email for invite: ${invite.id}`
312
+ );
313
+
314
+ try {
315
+ await this.sendAcceptanceNotificationEmail(
316
+ invite,
317
+ practitioner,
318
+ clinic,
319
+ emailConfig
320
+ );
321
+ Logger.info(
322
+ `[PractitionerInviteAggService] Successfully sent acceptance notification email for invite: ${invite.id}`
323
+ );
324
+ } catch (emailError) {
325
+ Logger.error(
326
+ `[PractitionerInviteAggService] Error sending acceptance notification email for invite ${invite.id}:`,
327
+ emailError
328
+ );
329
+ // Don't throw - email failure shouldn't break the acceptance logic
330
+ }
331
+ }
332
+
333
+ Logger.info(
334
+ `[PractitionerInviteAggService] Successfully processed accepted invite ${invite.id}`
335
+ );
336
+ } catch (error) {
337
+ Logger.error(
338
+ `[PractitionerInviteAggService] Error processing accepted invite ${invite.id}:`,
339
+ error
340
+ );
341
+ throw error;
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Handles the business logic when a practitioner rejects an invite.
347
+ * @param {PractitionerInvite} invite - The rejected invite
348
+ * @param {object} emailConfig - Optional email configuration for sending notification emails
349
+ * @returns {Promise<void>}
350
+ */
351
+ private async handleInviteRejected(
352
+ invite: PractitionerInvite,
353
+ emailConfig?: {
354
+ fromAddress: string;
355
+ domain: string;
356
+ clinicDashboardUrl: string;
357
+ findPractitionersUrl?: string;
358
+ }
359
+ ): Promise<void> {
360
+ Logger.info(
361
+ `[PractitionerInviteAggService] Processing rejected invite ${invite.id}`
362
+ );
363
+
364
+ try {
365
+ // Send rejection notification email to clinic admin if mailing service is available
366
+ if (this.mailingService && emailConfig) {
367
+ Logger.info(
368
+ `[PractitionerInviteAggService] Sending rejection notification email for invite: ${invite.id}`
369
+ );
370
+
371
+ try {
372
+ const [practitioner, clinic] = await Promise.all([
373
+ this.fetchPractitionerById(invite.practitionerId),
374
+ this.fetchClinicById(invite.clinicId),
375
+ ]);
376
+
377
+ if (practitioner && clinic) {
378
+ await this.sendRejectionNotificationEmail(
379
+ invite,
380
+ practitioner,
381
+ clinic,
382
+ emailConfig
383
+ );
384
+ Logger.info(
385
+ `[PractitionerInviteAggService] Successfully sent rejection notification email for invite: ${invite.id}`
386
+ );
387
+ }
388
+ } catch (emailError) {
389
+ Logger.error(
390
+ `[PractitionerInviteAggService] Error sending rejection notification email for invite ${invite.id}:`,
391
+ emailError
392
+ );
393
+ // Don't throw - email failure shouldn't break the rejection logic
394
+ }
395
+ }
396
+
397
+ Logger.info(
398
+ `[PractitionerInviteAggService] Successfully processed rejected invite ${invite.id}`
399
+ );
400
+ } catch (error) {
401
+ Logger.error(
402
+ `[PractitionerInviteAggService] Error processing rejected invite ${invite.id}:`,
403
+ error
404
+ );
405
+ throw error;
406
+ }
407
+ }
408
+
409
+ /**
410
+ * Handles the business logic when an invite is cancelled by admin.
411
+ * @param {PractitionerInvite} invite - The cancelled invite
412
+ * @returns {Promise<void>}
413
+ */
414
+ private async handleInviteCancelled(
415
+ invite: PractitionerInvite
416
+ ): Promise<void> {
417
+ Logger.info(
418
+ `[PractitionerInviteAggService] Processing cancelled invite ${invite.id}`
419
+ );
420
+
421
+ try {
422
+ // TODO: Add any side effects for cancelled invites
423
+ // For example: Update counters, send notifications, etc.
424
+
425
+ Logger.info(
426
+ `[PractitionerInviteAggService] Successfully processed cancelled invite ${invite.id}`
427
+ );
428
+ } catch (error) {
429
+ Logger.error(
430
+ `[PractitionerInviteAggService] Error processing cancelled invite ${invite.id}:`,
431
+ error
432
+ );
433
+ throw error;
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Adds practitioner information to a clinic when an invite is accepted.
439
+ * @param clinicId - ID of the clinic to update
440
+ * @param doctorInfo - Doctor information to add to the clinic
441
+ * @returns {Promise<void>}
442
+ */
443
+ private async addPractitionerToClinic(
444
+ clinicId: string,
445
+ doctorInfo: DoctorInfo
446
+ ): Promise<void> {
447
+ Logger.info(
448
+ `[PractitionerInviteAggService] Adding practitioner ${doctorInfo.id} to clinic ${clinicId}`
449
+ );
450
+
451
+ try {
452
+ const clinicRef = this.db.collection(CLINICS_COLLECTION).doc(clinicId);
453
+
454
+ await clinicRef.update({
455
+ doctors: admin.firestore.FieldValue.arrayUnion(doctorInfo.id),
456
+ doctorsInfo: admin.firestore.FieldValue.arrayUnion(doctorInfo),
457
+ updatedAt: admin.firestore.FieldValue.serverTimestamp(),
458
+ });
459
+
460
+ Logger.info(
461
+ `[PractitionerInviteAggService] Successfully added practitioner ${doctorInfo.id} to clinic ${clinicId}`
462
+ );
463
+ } catch (error) {
464
+ Logger.error(
465
+ `[PractitionerInviteAggService] Error adding practitioner ${doctorInfo.id} to clinic ${clinicId}:`,
466
+ error
467
+ );
468
+ throw error;
469
+ }
470
+ }
471
+
472
+ /**
473
+ * Updates practitioner information in a clinic.
474
+ * @param clinicId - ID of the clinic to update
475
+ * @param doctorInfo - Updated doctor information
476
+ * @returns {Promise<void>}
477
+ */
478
+ private async updatePractitionerInfoInClinic(
479
+ clinicId: string,
480
+ doctorInfo: DoctorInfo
481
+ ): Promise<void> {
482
+ Logger.info(
483
+ `[PractitionerInviteAggService] Updating practitioner ${doctorInfo.id} info in clinic ${clinicId}`
484
+ );
485
+
486
+ try {
487
+ const clinicRef = this.db.collection(CLINICS_COLLECTION).doc(clinicId);
488
+
489
+ // Get current clinic data to filter doctorsInfo manually
490
+ const clinicDoc = await clinicRef.get();
491
+ if (clinicDoc.exists) {
492
+ const clinicData = clinicDoc.data() as Clinic;
493
+ const currentDoctorsInfo = clinicData?.doctorsInfo || [];
494
+
495
+ // Filter out the doctor info with matching ID
496
+ const filteredDoctorsInfo = currentDoctorsInfo.filter(
497
+ (doctor: any) => doctor.id !== doctorInfo.id
498
+ );
499
+
500
+ // Add the updated doctor info to the filtered array
501
+ const updatedDoctorsInfo = [...filteredDoctorsInfo, doctorInfo];
502
+
503
+ // Update with the complete new array
504
+ await clinicRef.update({
505
+ doctorsInfo: updatedDoctorsInfo,
506
+ updatedAt: admin.firestore.FieldValue.serverTimestamp(),
507
+ });
508
+
509
+ Logger.info(
510
+ `[PractitionerInviteAggService] Successfully updated practitioner ${doctorInfo.id} info in clinic ${clinicId}`
511
+ );
512
+ } else {
513
+ Logger.warn(
514
+ `[PractitionerInviteAggService] Clinic ${clinicId} not found for doctor info update`
515
+ );
516
+ }
517
+ } catch (error) {
518
+ Logger.error(
519
+ `[PractitionerInviteAggService] Error updating practitioner ${doctorInfo.id} info in clinic ${clinicId}:`,
520
+ error
521
+ );
522
+ throw error;
523
+ }
524
+ }
525
+
526
+ /**
527
+ * Adds a clinic to a practitioner's profile with working hours from the invite.
528
+ * @param {string} practitionerId - The practitioner ID
529
+ * @param {ClinicInfo} clinicInfo - The clinic information
530
+ * @param {PractitionerInvite} invite - The accepted invite containing working hours
531
+ * @returns {Promise<void>}
532
+ */
533
+ private async addClinicToPractitioner(
534
+ practitionerId: string,
535
+ clinicInfo: ClinicInfo,
536
+ invite: PractitionerInvite
537
+ ): Promise<void> {
538
+ Logger.info(
539
+ `[PractitionerInviteAggService] Adding clinic ${clinicInfo.id} to practitioner ${practitionerId}`
540
+ );
541
+
542
+ try {
543
+ const practitionerRef = this.db
544
+ .collection(PRACTITIONERS_COLLECTION)
545
+ .doc(practitionerId);
546
+
547
+ // Create working hours object from the invite's proposed working hours
548
+ const workingHours: PractitionerClinicWorkingHours = {
549
+ clinicId: clinicInfo.id,
550
+ workingHours: invite.proposedWorkingHours,
551
+ isActive: true,
552
+ createdAt: admin.firestore.Timestamp.now() as any,
553
+ updatedAt: admin.firestore.Timestamp.now() as any,
554
+ };
555
+
556
+ // Update practitioner document with new clinic and working hours
557
+ await practitionerRef.update({
558
+ clinics: admin.firestore.FieldValue.arrayUnion(clinicInfo.id),
559
+ clinicsInfo: admin.firestore.FieldValue.arrayUnion(clinicInfo),
560
+ clinicWorkingHours: admin.firestore.FieldValue.arrayUnion(workingHours),
561
+ updatedAt: admin.firestore.FieldValue.serverTimestamp(),
562
+ });
563
+
564
+ Logger.info(
565
+ `[PractitionerInviteAggService] Successfully added clinic ${clinicInfo.id} to practitioner ${practitionerId}`
566
+ );
567
+ } catch (error) {
568
+ Logger.error(
569
+ `[PractitionerInviteAggService] Error adding clinic to practitioner:`,
570
+ error
571
+ );
572
+ throw error;
573
+ }
574
+ }
575
+
576
+ /**
577
+ * Updates the working hours for an existing practitioner-clinic relationship.
578
+ * @param {string} practitionerId - The practitioner ID
579
+ * @param {PractitionerInvite} invite - The accepted invite containing new working hours
580
+ * @returns {Promise<void>}
581
+ */
582
+ private async updatePractitionerWorkingHours(
583
+ practitionerId: string,
584
+ invite: PractitionerInvite
585
+ ): Promise<void> {
586
+ Logger.info(
587
+ `[PractitionerInviteAggService] Updating working hours for practitioner ${practitionerId} at clinic ${invite.clinicId}`
588
+ );
589
+
590
+ try {
591
+ const practitionerRef = this.db
592
+ .collection(PRACTITIONERS_COLLECTION)
593
+ .doc(practitionerId);
594
+
595
+ // Get current practitioner data
596
+ const practitionerDoc = await practitionerRef.get();
597
+ if (!practitionerDoc.exists) {
598
+ throw new Error(`Practitioner ${practitionerId} not found`);
599
+ }
600
+
601
+ const practitionerData = practitionerDoc.data() as Practitioner;
602
+ const currentWorkingHours = practitionerData.clinicWorkingHours || [];
603
+
604
+ // Find and update the working hours for this clinic
605
+ const updatedWorkingHours = currentWorkingHours.map((wh) => {
606
+ if (wh.clinicId === invite.clinicId) {
607
+ return {
608
+ ...wh,
609
+ workingHours: invite.proposedWorkingHours,
610
+ isActive: true,
611
+ updatedAt: admin.firestore.Timestamp.now() as any,
612
+ };
613
+ }
614
+ return wh;
615
+ });
616
+
617
+ // If working hours for this clinic don't exist, add them
618
+ if (!updatedWorkingHours.some((wh) => wh.clinicId === invite.clinicId)) {
619
+ updatedWorkingHours.push({
620
+ clinicId: invite.clinicId,
621
+ workingHours: invite.proposedWorkingHours,
622
+ isActive: true,
623
+ createdAt: admin.firestore.Timestamp.now() as any,
624
+ updatedAt: admin.firestore.Timestamp.now() as any,
625
+ });
626
+ }
627
+
628
+ // Update the practitioner document
629
+ await practitionerRef.update({
630
+ clinicWorkingHours: updatedWorkingHours,
631
+ updatedAt: admin.firestore.FieldValue.serverTimestamp(),
632
+ });
633
+
634
+ Logger.info(
635
+ `[PractitionerInviteAggService] Successfully updated working hours for practitioner ${practitionerId} at clinic ${invite.clinicId}`
636
+ );
637
+ } catch (error) {
638
+ Logger.error(
639
+ `[PractitionerInviteAggService] Error updating practitioner working hours:`,
640
+ error
641
+ );
642
+ throw error;
643
+ }
644
+ }
645
+
646
+ // --- Data Fetching Helpers ---
647
+
648
+ /**
649
+ * Fetches a practitioner by ID.
650
+ * @param practitionerId The practitioner ID.
651
+ * @returns {Promise<Practitioner | null>} The practitioner or null if not found.
652
+ */
653
+ private async fetchPractitionerById(
654
+ practitionerId: string
655
+ ): Promise<Practitioner | null> {
656
+ try {
657
+ const doc = await this.db
658
+ .collection(PRACTITIONERS_COLLECTION)
659
+ .doc(practitionerId)
660
+ .get();
661
+ return doc.exists ? (doc.data() as Practitioner) : null;
662
+ } catch (error) {
663
+ Logger.error(
664
+ `[PractitionerInviteAggService] Error fetching practitioner ${practitionerId}:`,
665
+ error
666
+ );
667
+ return null;
668
+ }
669
+ }
670
+
671
+ /**
672
+ * Fetches a clinic by ID.
673
+ * @param clinicId The clinic ID.
674
+ * @returns {Promise<Clinic | null>} The clinic or null if not found.
675
+ */
676
+ private async fetchClinicById(clinicId: string): Promise<Clinic | null> {
677
+ try {
678
+ const doc = await this.db
679
+ .collection(CLINICS_COLLECTION)
680
+ .doc(clinicId)
681
+ .get();
682
+ return doc.exists ? (doc.data() as Clinic) : null;
683
+ } catch (error) {
684
+ Logger.error(
685
+ `[PractitionerInviteAggService] Error fetching clinic ${clinicId}:`,
686
+ error
687
+ );
688
+ return null;
689
+ }
690
+ }
691
+
692
+ // --- Email Helper Methods ---
693
+
694
+ /**
695
+ * Sends acceptance notification email to clinic admin
696
+ * @param invite The accepted invite
697
+ * @param practitioner The practitioner who accepted
698
+ * @param clinic The clinic that sent the invite
699
+ * @param emailConfig Email configuration
700
+ */
701
+ private async sendAcceptanceNotificationEmail(
702
+ invite: PractitionerInvite,
703
+ practitioner: Practitioner,
704
+ clinic: Clinic,
705
+ emailConfig: {
706
+ fromAddress: string;
707
+ domain: string;
708
+ clinicDashboardUrl: string;
709
+ practitionerProfileUrl?: string;
710
+ }
711
+ ): Promise<void> {
712
+ if (!this.mailingService) return;
713
+
714
+ const notificationData = {
715
+ invite,
716
+ practitioner: {
717
+ firstName: practitioner.basicInfo.firstName || "",
718
+ lastName: practitioner.basicInfo.lastName || "",
719
+ specialties:
720
+ practitioner.certification?.specialties?.map(
721
+ (s: any) => s.name || s
722
+ ) || [],
723
+ profileImageUrl:
724
+ typeof practitioner.basicInfo.profileImageUrl === "string"
725
+ ? practitioner.basicInfo.profileImageUrl
726
+ : null,
727
+ experienceYears: undefined, // This would need to be calculated or stored in practitioner data
728
+ },
729
+ clinic: {
730
+ name: clinic.name,
731
+ adminName: undefined, // This would need to be fetched from clinic admin data
732
+ adminEmail: clinic.contactInfo.email,
733
+ },
734
+ context: {
735
+ invitationDate: invite.createdAt.toDate().toLocaleDateString(),
736
+ responseDate:
737
+ invite.acceptedAt?.toDate().toLocaleDateString() ||
738
+ new Date().toLocaleDateString(),
739
+ },
740
+ urls: {
741
+ clinicDashboardUrl: emailConfig.clinicDashboardUrl,
742
+ practitionerProfileUrl: emailConfig.practitionerProfileUrl,
743
+ },
744
+ options: {
745
+ fromAddress: emailConfig.fromAddress,
746
+ mailgunDomain: emailConfig.domain,
747
+ },
748
+ };
749
+
750
+ await this.mailingService.sendAcceptedNotificationEmail(notificationData);
751
+ }
752
+
753
+ /**
754
+ * Sends rejection notification email to clinic admin
755
+ * @param invite The rejected invite
756
+ * @param practitioner The practitioner who rejected
757
+ * @param clinic The clinic that sent the invite
758
+ * @param emailConfig Email configuration
759
+ */
760
+ private async sendRejectionNotificationEmail(
761
+ invite: PractitionerInvite,
762
+ practitioner: Practitioner,
763
+ clinic: Clinic,
764
+ emailConfig: {
765
+ fromAddress: string;
766
+ domain: string;
767
+ clinicDashboardUrl: string;
768
+ findPractitionersUrl?: string;
769
+ }
770
+ ): Promise<void> {
771
+ if (!this.mailingService) return;
772
+
773
+ const notificationData = {
774
+ invite,
775
+ practitioner: {
776
+ firstName: practitioner.basicInfo.firstName || "",
777
+ lastName: practitioner.basicInfo.lastName || "",
778
+ specialties:
779
+ practitioner.certification?.specialties?.map(
780
+ (s: any) => s.name || s
781
+ ) || [],
782
+ profileImageUrl:
783
+ typeof practitioner.basicInfo.profileImageUrl === "string"
784
+ ? practitioner.basicInfo.profileImageUrl
785
+ : null,
786
+ },
787
+ clinic: {
788
+ name: clinic.name,
789
+ adminName: undefined, // This would need to be fetched from clinic admin data
790
+ adminEmail: clinic.contactInfo.email,
791
+ },
792
+ context: {
793
+ invitationDate: invite.createdAt.toDate().toLocaleDateString(),
794
+ responseDate:
795
+ invite.rejectedAt?.toDate().toLocaleDateString() ||
796
+ new Date().toLocaleDateString(),
797
+ rejectionReason: invite.rejectionReason || undefined,
798
+ },
799
+ urls: {
800
+ clinicDashboardUrl: emailConfig.clinicDashboardUrl,
801
+ findPractitionersUrl: emailConfig.findPractitionersUrl,
802
+ },
803
+ options: {
804
+ fromAddress: emailConfig.fromAddress,
805
+ mailgunDomain: emailConfig.domain,
806
+ },
807
+ };
808
+
809
+ await this.mailingService.sendRejectedNotificationEmail(notificationData);
810
+ }
811
+ }