@blackcode_sa/metaestetics-api 1.14.28 → 1.14.32

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.
@@ -46,6 +46,50 @@ Sends email invitations to practitioners when they are invited to join a clinic.
46
46
  2. The function uses the `PractitionerInviteMailingService` to send an invitation email to the practitioner.
47
47
  3. The email contains the token needed to claim their profile and instructions for registration.
48
48
 
49
+ ### Patient Invitation Service
50
+
51
+ Sends email invitations to patients when a clinic admin creates their profile and generates an invitation token.
52
+
53
+ #### How it works:
54
+
55
+ 1. When a new patient invitation token is created in the Firestore database (`patients/{patientId}/inviteTokens/{tokenId}`), the `onPatientTokenCreated` cloud function is triggered.
56
+ 2. The function uses the `PatientInviteMailingService` to send an invitation email to the patient.
57
+ 3. The email contains the token needed to claim their profile and instructions for registering in the patient app.
58
+
59
+ #### Example Usage in Code:
60
+
61
+ ```typescript
62
+ import { PatientInviteMailingService } from "./admin/mailing";
63
+
64
+ // Create a new instance of the service
65
+ const mailingService = new PatientInviteMailingService(firestoreClient, mailgunClient);
66
+
67
+ // Send an invitation email
68
+ await mailingService.sendInvitationEmail({
69
+ token: {
70
+ id: "token-id",
71
+ token: "ABC123",
72
+ patientId: "patient-id",
73
+ email: "patient@example.com",
74
+ clinicId: "clinic-id",
75
+ expiresAt: admin.firestore.Timestamp.fromDate(new Date()),
76
+ },
77
+ patient: {
78
+ firstName: "Jane",
79
+ lastName: "Doe",
80
+ },
81
+ clinic: {
82
+ name: "Example Clinic",
83
+ contactEmail: "admin@example.com",
84
+ contactName: "Clinic Admin",
85
+ },
86
+ options: {
87
+ registrationUrl: "https://your-app.com/patient/register",
88
+ customSubject: "Claim Your Patient Profile",
89
+ },
90
+ });
91
+ ```
92
+
49
93
  #### Example Usage in Code:
50
94
 
51
95
  ```typescript
@@ -1,3 +1,4 @@
1
1
  export * from "./base.mailing.service";
2
2
  export * from "./practitionerInvite";
3
+ export * from "./patientInvite";
3
4
  export * from "./appointment";
@@ -0,0 +1,2 @@
1
+ export * from "./patientInvite.mailing";
2
+
@@ -0,0 +1,415 @@
1
+ import * as admin from "firebase-admin";
2
+ import { BaseMailingService } from "../base.mailing.service";
3
+ import { patientInvitationTemplate } from "./templates/invitation.template";
4
+ import { Logger } from "../../logger";
5
+ import {
6
+ PatientProfile,
7
+ PatientSensitiveInfo,
8
+ PATIENTS_COLLECTION,
9
+ PATIENT_SENSITIVE_INFO_COLLECTION,
10
+ } from "../../../types/patient";
11
+ import {
12
+ PatientToken,
13
+ PatientTokenStatus,
14
+ INVITE_TOKENS_COLLECTION,
15
+ } from "../../../types/patient/token.types";
16
+ import { Clinic, CLINICS_COLLECTION } from "../../../types/clinic";
17
+
18
+ /**
19
+ * Minimal interface for the mailgun.js client if not importing full types
20
+ */
21
+ interface NewMailgunMessagesAPI {
22
+ create(domain: string, data: any): Promise<any>;
23
+ }
24
+ interface NewMailgunClient {
25
+ messages: NewMailgunMessagesAPI;
26
+ }
27
+
28
+ /**
29
+ * Interface for the data required to send a patient invitation email
30
+ */
31
+ export interface PatientInviteEmailData {
32
+ /** The token object from the patient service */
33
+ token: {
34
+ id: string;
35
+ token: string;
36
+ patientId: string;
37
+ email: string;
38
+ clinicId: string;
39
+ expiresAt: admin.firestore.Timestamp;
40
+ };
41
+
42
+ /** Patient basic info */
43
+ patient: {
44
+ firstName: string;
45
+ lastName: string;
46
+ };
47
+
48
+ /** Clinic info */
49
+ clinic: {
50
+ name: string;
51
+ contactEmail: string;
52
+ contactName?: string;
53
+ };
54
+
55
+ /** Config options */
56
+ options?: {
57
+ registrationUrl?: string;
58
+ customSubject?: string;
59
+ fromAddress?: string;
60
+ mailgunDomain?: string;
61
+ };
62
+ }
63
+
64
+ /**
65
+ * Service for sending patient invitation emails
66
+ * Follows the same pattern as PractitionerInviteMailingService
67
+ */
68
+ export class PatientInviteMailingService extends BaseMailingService {
69
+ private readonly DEFAULT_REGISTRATION_URL =
70
+ "https://metaesthetics.net/patient/register";
71
+ private readonly DEFAULT_SUBJECT =
72
+ "Claim Your Patient Profile - MetaEstetics";
73
+ private readonly DEFAULT_MAILGUN_DOMAIN = "mg.metaesthetics.net";
74
+
75
+ /**
76
+ * Constructor for PatientInviteMailingService
77
+ * @param firestore - Firestore instance provided by the caller
78
+ * @param mailgunClient - Mailgun client instance (mailgun.js v10+) provided by the caller
79
+ */
80
+ constructor(
81
+ firestore: FirebaseFirestore.Firestore,
82
+ mailgunClient: NewMailgunClient
83
+ ) {
84
+ super(firestore, mailgunClient);
85
+ }
86
+
87
+ /**
88
+ * Sends a patient invitation email
89
+ * @param data - The patient invitation data
90
+ * @returns Promise resolved when email is sent
91
+ */
92
+ async sendInvitationEmail(data: PatientInviteEmailData): Promise<any> {
93
+ try {
94
+ Logger.info(
95
+ "[PatientInviteMailingService] Sending invitation email to",
96
+ data.token.email
97
+ );
98
+
99
+ // Format expiration date
100
+ const expirationDate = data.token.expiresAt
101
+ .toDate()
102
+ .toLocaleDateString("en-US", {
103
+ weekday: "long",
104
+ year: "numeric",
105
+ month: "long",
106
+ day: "numeric",
107
+ });
108
+
109
+ // Registration URL
110
+ const registrationUrl =
111
+ data.options?.registrationUrl || this.DEFAULT_REGISTRATION_URL;
112
+
113
+ // Contact information
114
+ const contactName = data.clinic.contactName || "Clinic Administrator";
115
+ const contactEmail = data.clinic.contactEmail;
116
+
117
+ // Subject line
118
+ const subject = data.options?.customSubject || this.DEFAULT_SUBJECT;
119
+
120
+ // Determine 'from' address
121
+ const fromAddress =
122
+ data.options?.fromAddress ||
123
+ `MetaEstetics <no-reply@${
124
+ data.options?.mailgunDomain || this.DEFAULT_MAILGUN_DOMAIN
125
+ }>`;
126
+
127
+ // Current year for copyright
128
+ const currentYear = new Date().getFullYear().toString();
129
+
130
+ // Patient full name
131
+ const patientName = `${data.patient.firstName} ${data.patient.lastName}`;
132
+
133
+ // Prepare template variables
134
+ const templateVariables = {
135
+ clinicName: data.clinic.name,
136
+ patientName,
137
+ inviteToken: data.token.token,
138
+ expirationDate,
139
+ registrationUrl,
140
+ contactName,
141
+ contactEmail,
142
+ currentYear,
143
+ };
144
+
145
+ // Debug log for template variables (excluding token for security)
146
+ Logger.info("[PatientInviteMailingService] Template variables:", {
147
+ clinicName: templateVariables.clinicName,
148
+ patientName: templateVariables.patientName,
149
+ expirationDate: templateVariables.expirationDate,
150
+ registrationUrl: templateVariables.registrationUrl,
151
+ contactName: templateVariables.contactName,
152
+ contactEmail: templateVariables.contactEmail,
153
+ hasInviteToken: !!templateVariables.inviteToken,
154
+ });
155
+
156
+ // Render HTML email
157
+ const html = this.renderTemplate(
158
+ patientInvitationTemplate,
159
+ templateVariables
160
+ );
161
+
162
+ // Data for the sendEmail method
163
+ const mailgunSendData = {
164
+ to: data.token.email,
165
+ from: fromAddress,
166
+ subject,
167
+ html,
168
+ };
169
+
170
+ // Determine the domain to use for sending
171
+ const domainToSendFrom =
172
+ data.options?.mailgunDomain || this.DEFAULT_MAILGUN_DOMAIN;
173
+
174
+ Logger.info("[PatientInviteMailingService] Sending email with data:", {
175
+ domain: domainToSendFrom,
176
+ to: mailgunSendData.to,
177
+ from: mailgunSendData.from,
178
+ subject: mailgunSendData.subject,
179
+ hasHtml: !!mailgunSendData.html,
180
+ });
181
+
182
+ // Call the sendEmail method from BaseMailingService
183
+ const result = await this.sendEmail(domainToSendFrom, mailgunSendData);
184
+
185
+ // Log success
186
+ await this.logEmailAttempt(
187
+ {
188
+ to: data.token.email,
189
+ subject,
190
+ templateName: "patient_invitation",
191
+ },
192
+ true
193
+ );
194
+
195
+ return result;
196
+ } catch (error: any) {
197
+ Logger.error(
198
+ "[PatientInviteMailingService] Error sending invitation email:",
199
+ {
200
+ errorMessage: error.message,
201
+ errorDetails: error.details,
202
+ errorStatus: error.status,
203
+ stack: error.stack,
204
+ }
205
+ );
206
+
207
+ // Log failure
208
+ await this.logEmailAttempt(
209
+ {
210
+ to: data.token.email,
211
+ subject: data.options?.customSubject || this.DEFAULT_SUBJECT,
212
+ templateName: "patient_invitation",
213
+ },
214
+ false,
215
+ error
216
+ );
217
+
218
+ throw error;
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Handles the patient token creation event from Cloud Functions.
224
+ * Fetches necessary data and sends the invitation email.
225
+ * @param tokenData - The fully typed token object including its id
226
+ * @param mailgunConfig - Mailgun configuration (from, domain, optional registrationUrl)
227
+ * @returns Promise resolved when the email is sent
228
+ */
229
+ async handleTokenCreationEvent(
230
+ tokenData: PatientToken,
231
+ mailgunConfig: {
232
+ fromAddress: string;
233
+ domain: string;
234
+ registrationUrl?: string;
235
+ }
236
+ ): Promise<void> {
237
+ try {
238
+ Logger.info(
239
+ "[PatientInviteMailingService] Handling token creation event for token:",
240
+ tokenData.id
241
+ );
242
+
243
+ // Validate token data
244
+ if (!tokenData || !tokenData.id || !tokenData.token || !tokenData.email) {
245
+ throw new Error(
246
+ `Invalid token data: Missing required properties. Token ID: ${tokenData?.id}`
247
+ );
248
+ }
249
+
250
+ if (!tokenData.patientId) {
251
+ throw new Error(
252
+ `Token ${tokenData.id} is missing patientId reference`
253
+ );
254
+ }
255
+
256
+ if (!tokenData.clinicId) {
257
+ throw new Error(`Token ${tokenData.id} is missing clinicId reference`);
258
+ }
259
+
260
+ if (!tokenData.expiresAt) {
261
+ throw new Error(`Token ${tokenData.id} is missing expiration date`);
262
+ }
263
+
264
+ // Validate token status (handle both enum and string values)
265
+ if (
266
+ tokenData.status !== PatientTokenStatus.ACTIVE &&
267
+ String(tokenData.status).toLowerCase() !== "active"
268
+ ) {
269
+ Logger.warn(
270
+ "[PatientInviteMailingService] Token is not active, skipping email.",
271
+ { tokenId: tokenData.id, status: tokenData.status }
272
+ );
273
+ return;
274
+ }
275
+
276
+ Logger.info(
277
+ `[PatientInviteMailingService] Token status validation:`,
278
+ {
279
+ tokenId: tokenData.id,
280
+ status: tokenData.status,
281
+ statusType: typeof tokenData.status,
282
+ }
283
+ );
284
+
285
+ // Get patient profile data
286
+ Logger.info(
287
+ `[PatientInviteMailingService] Fetching patient data: ${tokenData.patientId}`
288
+ );
289
+ const patientRef = this.db
290
+ .collection(PATIENTS_COLLECTION)
291
+ .doc(tokenData.patientId);
292
+ const patientDoc = await patientRef.get();
293
+
294
+ if (!patientDoc.exists) {
295
+ throw new Error(`Patient ${tokenData.patientId} not found`);
296
+ }
297
+
298
+ const patientData = patientDoc.data() as PatientProfile;
299
+ if (!patientData) {
300
+ throw new Error(
301
+ `Patient ${tokenData.patientId} has invalid data structure`
302
+ );
303
+ }
304
+
305
+ // Get patient sensitive info for name
306
+ const sensitiveInfoRef = patientRef
307
+ .collection(PATIENT_SENSITIVE_INFO_COLLECTION)
308
+ .doc(tokenData.patientId);
309
+ const sensitiveInfoDoc = await sensitiveInfoRef.get();
310
+
311
+ let firstName = "Patient";
312
+ let lastName = "";
313
+
314
+ if (sensitiveInfoDoc.exists) {
315
+ const sensitiveInfo = sensitiveInfoDoc.data() as PatientSensitiveInfo;
316
+ firstName = sensitiveInfo?.firstName || "Patient";
317
+ lastName = sensitiveInfo?.lastName || "";
318
+ } else {
319
+ // Fall back to displayName if no sensitive info
320
+ Logger.warn(
321
+ `[PatientInviteMailingService] No sensitive info found for patient ${tokenData.patientId}, using displayName`
322
+ );
323
+ const displayNameParts = (patientData.displayName || "Patient").split(" ");
324
+ firstName = displayNameParts[0] || "Patient";
325
+ lastName = displayNameParts.slice(1).join(" ") || "";
326
+ }
327
+
328
+ Logger.info(
329
+ `[PatientInviteMailingService] Patient found: ${firstName} ${lastName}`
330
+ );
331
+
332
+ // Get clinic data
333
+ Logger.info(
334
+ `[PatientInviteMailingService] Fetching clinic data: ${tokenData.clinicId}`
335
+ );
336
+ const clinicRef = this.db
337
+ .collection(CLINICS_COLLECTION)
338
+ .doc(tokenData.clinicId);
339
+ const clinicDoc = await clinicRef.get();
340
+
341
+ if (!clinicDoc.exists) {
342
+ throw new Error(`Clinic ${tokenData.clinicId} not found`);
343
+ }
344
+
345
+ const clinicData = clinicDoc.data() as Clinic;
346
+ if (!clinicData || !clinicData.contactInfo) {
347
+ throw new Error(
348
+ `Clinic ${tokenData.clinicId} has invalid data structure`
349
+ );
350
+ }
351
+
352
+ Logger.info(
353
+ `[PatientInviteMailingService] Clinic found: ${clinicData.name}`
354
+ );
355
+
356
+ // Validate fromAddress
357
+ if (!mailgunConfig.fromAddress) {
358
+ Logger.warn(
359
+ "[PatientInviteMailingService] No fromAddress provided, using default"
360
+ );
361
+ mailgunConfig.fromAddress = `MetaEstetics <no-reply@${this.DEFAULT_MAILGUN_DOMAIN}>`;
362
+ }
363
+
364
+ // Prepare email data
365
+ const emailData: PatientInviteEmailData = {
366
+ token: {
367
+ id: tokenData.id,
368
+ token: tokenData.token,
369
+ patientId: tokenData.patientId,
370
+ email: tokenData.email,
371
+ clinicId: tokenData.clinicId,
372
+ expiresAt: tokenData.expiresAt as unknown as admin.firestore.Timestamp,
373
+ },
374
+ patient: {
375
+ firstName,
376
+ lastName,
377
+ },
378
+ clinic: {
379
+ name: clinicData.name || "Medical Clinic",
380
+ contactEmail: clinicData.contactInfo.email || "contact@clinic.com",
381
+ contactName: "Clinic Admin",
382
+ },
383
+ options: {
384
+ fromAddress: mailgunConfig.fromAddress,
385
+ mailgunDomain: mailgunConfig.domain,
386
+ registrationUrl: mailgunConfig.registrationUrl,
387
+ },
388
+ };
389
+
390
+ Logger.info(
391
+ "[PatientInviteMailingService] Email data prepared, sending invitation"
392
+ );
393
+
394
+ // Send the invitation email
395
+ await this.sendInvitationEmail(emailData);
396
+
397
+ Logger.info(
398
+ "[PatientInviteMailingService] Invitation email sent successfully"
399
+ );
400
+ } catch (error: any) {
401
+ Logger.error(
402
+ "[PatientInviteMailingService] Error handling token creation event:",
403
+ {
404
+ errorMessage: error.message,
405
+ errorDetails: error.details,
406
+ errorStatus: error.status,
407
+ stack: error.stack,
408
+ tokenId: tokenData?.id,
409
+ }
410
+ );
411
+ throw error;
412
+ }
413
+ }
414
+ }
415
+
@@ -0,0 +1,120 @@
1
+ /**
2
+ * HTML email template for patient invitation to claim their profile
3
+ */
4
+ export const patientInvitationTemplate = `
5
+ <!DOCTYPE html>
6
+ <html>
7
+ <head>
8
+ <meta charset="UTF-8">
9
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
10
+ <title>Claim Your Patient Profile at {{clinicName}}</title>
11
+ <style>
12
+ body {
13
+ font-family: Arial, sans-serif;
14
+ line-height: 1.6;
15
+ color: #333;
16
+ margin: 0;
17
+ padding: 0;
18
+ }
19
+ .container {
20
+ max-width: 600px;
21
+ margin: 0 auto;
22
+ padding: 20px;
23
+ }
24
+ .header {
25
+ background-color: #2C8E99;
26
+ padding: 20px;
27
+ text-align: center;
28
+ color: white;
29
+ }
30
+ .content {
31
+ padding: 20px;
32
+ background-color: #f9f9f9;
33
+ }
34
+ .footer {
35
+ padding: 20px;
36
+ text-align: center;
37
+ font-size: 12px;
38
+ color: #888;
39
+ }
40
+ .button {
41
+ display: inline-block;
42
+ background-color: #2C8E99;
43
+ color: white;
44
+ text-decoration: none;
45
+ padding: 12px 24px;
46
+ border-radius: 4px;
47
+ margin: 20px 0;
48
+ font-weight: bold;
49
+ }
50
+ .token {
51
+ font-size: 28px;
52
+ font-weight: bold;
53
+ color: #2C8E99;
54
+ padding: 15px 25px;
55
+ background-color: #e0f4f6;
56
+ border-radius: 8px;
57
+ display: inline-block;
58
+ letter-spacing: 4px;
59
+ margin: 15px 0;
60
+ font-family: monospace;
61
+ }
62
+ .info-box {
63
+ background-color: #fff;
64
+ border-left: 4px solid #2C8E99;
65
+ padding: 15px;
66
+ margin: 20px 0;
67
+ }
68
+ </style>
69
+ </head>
70
+ <body>
71
+ <div class="container">
72
+ <div class="header">
73
+ <h1>Welcome to MetaEstetics</h1>
74
+ </div>
75
+ <div class="content">
76
+ <p>Hello {{patientName}},</p>
77
+
78
+ <p>A patient profile has been created for you at <strong>{{clinicName}}</strong>. You can now claim this profile to access your personal health dashboard and appointment history.</p>
79
+
80
+ <div class="info-box">
81
+ <p><strong>What you'll get access to:</strong></p>
82
+ <ul>
83
+ <li>Your complete treatment history</li>
84
+ <li>Upcoming appointment details</li>
85
+ <li>Pre and post-treatment instructions</li>
86
+ <li>Direct messaging with your clinic</li>
87
+ </ul>
88
+ </div>
89
+
90
+ <p>To claim your profile, use this registration token:</p>
91
+
92
+ <div style="text-align: center;">
93
+ <span class="token">{{inviteToken}}</span>
94
+ </div>
95
+
96
+ <p><strong>Important:</strong> This token will expire on <strong>{{expirationDate}}</strong>.</p>
97
+
98
+ <p>To create your account:</p>
99
+ <ol>
100
+ <li>Download the MetaEstetics Patient app or visit {{registrationUrl}}</li>
101
+ <li>Create an account using your email address</li>
102
+ <li>When prompted, enter the token shown above</li>
103
+ <li>Your profile will be automatically linked to your new account</li>
104
+ </ol>
105
+
106
+ <div style="text-align: center;">
107
+ <a href="{{registrationUrl}}" class="button">Create Your Account</a>
108
+ </div>
109
+
110
+ <p>If you have any questions or didn't expect this email, please contact {{contactName}} at {{contactEmail}}.</p>
111
+ </div>
112
+ <div class="footer">
113
+ <p>This is an automated message from {{clinicName}}. Please do not reply to this email.</p>
114
+ <p>&copy; {{currentYear}} MetaEstetics. All rights reserved.</p>
115
+ </div>
116
+ </div>
117
+ </body>
118
+ </html>
119
+ `;
120
+
@@ -622,7 +622,15 @@ export async function searchCalendarEventsUtil(
622
622
  }
623
623
  if (filters.dateRange) {
624
624
  // Firestore requires range filters on the same field
625
- constraints.push(where("eventTime.start", ">=", filters.dateRange.start));
625
+ // We query for events that start within or before the date range
626
+ // Then post-filter to ensure they overlap (eventTime.end > dateRange.start)
627
+ // To catch events that start before but overlap, we extend the query start backwards
628
+ const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1000; // 30 days for long blocking events
629
+ const extendedStart = Timestamp.fromMillis(
630
+ filters.dateRange.start.toMillis() - MAX_EVENT_DURATION_MS
631
+ );
632
+
633
+ constraints.push(where("eventTime.start", ">=", extendedStart));
626
634
  constraints.push(where("eventTime.start", "<=", filters.dateRange.end));
627
635
  // Note: You might need to order by eventTime.start for range filters to work efficiently
628
636
  // constraints.push(orderBy("eventTime.start"));
@@ -633,10 +641,32 @@ export async function searchCalendarEventsUtil(
633
641
  const finalQuery = query(collectionRef, ...constraints);
634
642
  const querySnapshot = await getDocs(finalQuery);
635
643
 
636
- const events = querySnapshot.docs.map(
644
+ let events = querySnapshot.docs.map(
637
645
  (doc) => ({ id: doc.id, ...doc.data() } as CalendarEvent)
638
646
  );
639
647
 
648
+ // Post-filter to ensure events actually overlap with the date range (if provided)
649
+ // An event overlaps if: eventTime.start < dateRange.end AND eventTime.end > dateRange.start
650
+ if (filters.dateRange) {
651
+ events = events.filter((event) => {
652
+ const overlaps =
653
+ event.eventTime.end.toMillis() > filters.dateRange!.start.toMillis();
654
+ if (!overlaps) {
655
+ console.debug(
656
+ `[searchCalendarEventsUtil] Filtered out non-overlapping event:`,
657
+ {
658
+ eventId: event.id,
659
+ eventStart: event.eventTime.start.toDate().toISOString(),
660
+ eventEnd: event.eventTime.end.toDate().toISOString(),
661
+ queryStart: filters.dateRange!.start.toDate().toISOString(),
662
+ queryEnd: filters.dateRange!.end.toDate().toISOString(),
663
+ }
664
+ );
665
+ }
666
+ return overlaps;
667
+ });
668
+ }
669
+
640
670
  return events;
641
671
  } catch (error) {
642
672
  console.error("Error searching calendar events:", error);