@blackcode_sa/metaestetics-api 1.14.29 → 1.14.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,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 - MetaEsthetics";
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
+ `MetaEsthetics <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 = `MetaEsthetics <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,105 @@
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: #4A90E2;
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
+ .token {
41
+ font-size: 24px;
42
+ font-weight: bold;
43
+ color: #4A90E2;
44
+ padding: 10px;
45
+ background-color: #e9f0f9;
46
+ border-radius: 4px;
47
+ display: inline-block;
48
+ letter-spacing: 2px;
49
+ margin: 10px 0;
50
+ }
51
+ .info-box {
52
+ background-color: #fff;
53
+ border-left: 4px solid #4A90E2;
54
+ padding: 15px;
55
+ margin: 20px 0;
56
+ }
57
+ </style>
58
+ </head>
59
+ <body>
60
+ <div class="container">
61
+ <div class="header">
62
+ <h1>Welcome to MetaEsthetics</h1>
63
+ </div>
64
+ <div class="content">
65
+ <p>Hello {{patientName}},</p>
66
+
67
+ <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>
68
+
69
+ <div class="info-box">
70
+ <p><strong>What you'll get access to:</strong></p>
71
+ <ul>
72
+ <li>Your complete treatment history</li>
73
+ <li>Upcoming appointment details</li>
74
+ <li>Pre and post-treatment instructions</li>
75
+ <li>Direct messaging with your clinic</li>
76
+ </ul>
77
+ </div>
78
+
79
+ <p>To claim your profile, use this registration token:</p>
80
+
81
+ <div style="text-align: center;">
82
+ <span class="token">{{inviteToken}}</span>
83
+ </div>
84
+
85
+ <p><strong>Important:</strong> This token will expire on <strong>{{expirationDate}}</strong>.</p>
86
+
87
+ <p>To create your account:</p>
88
+ <ol>
89
+ <li>Download the <strong>MetaEsthetics</strong> app from the App Store (iOS) or Google Play Store (Android)</li>
90
+ <li>Open the app and create an account using your email address</li>
91
+ <li>When prompted, enter the token shown above</li>
92
+ <li>Your profile will be automatically linked to your new account</li>
93
+ </ol>
94
+
95
+ <p>If you have any questions or didn't expect this email, please contact {{contactName}} at {{contactEmail}}.</p>
96
+ </div>
97
+ <div class="footer">
98
+ <p>This is an automated message from {{clinicName}}. Please do not reply to this email.</p>
99
+ <p>&copy; {{currentYear}} MetaEsthetics. All rights reserved.</p>
100
+ </div>
101
+ </div>
102
+ </body>
103
+ </html>
104
+ `;
105
+
@@ -644,8 +644,11 @@ export class AnalyticsService extends BaseService {
644
644
  }
645
645
  }
646
646
 
647
- // Fall back to calculation
648
- const appointments = await this.fetchAppointments(undefined, dateRange);
647
+ // Fall back to calculation - filter by clinic if specified
648
+ const filters: AnalyticsFilters | undefined = options?.clinicBranchId
649
+ ? { clinicBranchId: options.clinicBranchId }
650
+ : undefined;
651
+ const appointments = await this.fetchAppointments(filters, dateRange);
649
652
  const canceled = getCanceledAppointments(appointments);
650
653
 
651
654
  if (groupBy === 'clinic') {
@@ -941,8 +944,11 @@ export class AnalyticsService extends BaseService {
941
944
  }
942
945
  }
943
946
 
944
- // Fall back to calculation
945
- const appointments = await this.fetchAppointments(undefined, dateRange);
947
+ // Fall back to calculation - filter by clinic if specified
948
+ const filters: AnalyticsFilters | undefined = options?.clinicBranchId
949
+ ? { clinicBranchId: options.clinicBranchId }
950
+ : undefined;
951
+ const appointments = await this.fetchAppointments(filters, dateRange);
946
952
  const noShow = getNoShowAppointments(appointments);
947
953
 
948
954
  if (groupBy === 'clinic') {