@blackcode_sa/metaestetics-api 1.14.29 → 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.
@@ -382,6 +382,15 @@ var PATIENT_MEDICAL_INFO_COLLECTION = "medical_info";
382
382
  var PATIENTS_COLLECTION = "patients";
383
383
  var PATIENT_SENSITIVE_INFO_COLLECTION = "sensitive-info";
384
384
 
385
+ // src/types/patient/token.types.ts
386
+ var INVITE_TOKENS_COLLECTION = "inviteTokens";
387
+ var PatientTokenStatus = /* @__PURE__ */ ((PatientTokenStatus2) => {
388
+ PatientTokenStatus2["ACTIVE"] = "active";
389
+ PatientTokenStatus2["USED"] = "used";
390
+ PatientTokenStatus2["EXPIRED"] = "expired";
391
+ return PatientTokenStatus2;
392
+ })(PatientTokenStatus || {});
393
+
385
394
  // src/types/clinic/practitioner-invite.types.ts
386
395
  var PractitionerInviteStatus = /* @__PURE__ */ ((PractitionerInviteStatus2) => {
387
396
  PractitionerInviteStatus2["PENDING"] = "pending";
@@ -13073,6 +13082,378 @@ var ExistingPractitionerInviteMailingService = class extends BaseMailingService
13073
13082
  }
13074
13083
  };
13075
13084
 
13085
+ // src/admin/mailing/patientInvite/templates/invitation.template.ts
13086
+ var patientInvitationTemplate = `
13087
+ <!DOCTYPE html>
13088
+ <html>
13089
+ <head>
13090
+ <meta charset="UTF-8">
13091
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
13092
+ <title>Claim Your Patient Profile at {{clinicName}}</title>
13093
+ <style>
13094
+ body {
13095
+ font-family: Arial, sans-serif;
13096
+ line-height: 1.6;
13097
+ color: #333;
13098
+ margin: 0;
13099
+ padding: 0;
13100
+ }
13101
+ .container {
13102
+ max-width: 600px;
13103
+ margin: 0 auto;
13104
+ padding: 20px;
13105
+ }
13106
+ .header {
13107
+ background-color: #2C8E99;
13108
+ padding: 20px;
13109
+ text-align: center;
13110
+ color: white;
13111
+ }
13112
+ .content {
13113
+ padding: 20px;
13114
+ background-color: #f9f9f9;
13115
+ }
13116
+ .footer {
13117
+ padding: 20px;
13118
+ text-align: center;
13119
+ font-size: 12px;
13120
+ color: #888;
13121
+ }
13122
+ .button {
13123
+ display: inline-block;
13124
+ background-color: #2C8E99;
13125
+ color: white;
13126
+ text-decoration: none;
13127
+ padding: 12px 24px;
13128
+ border-radius: 4px;
13129
+ margin: 20px 0;
13130
+ font-weight: bold;
13131
+ }
13132
+ .token {
13133
+ font-size: 28px;
13134
+ font-weight: bold;
13135
+ color: #2C8E99;
13136
+ padding: 15px 25px;
13137
+ background-color: #e0f4f6;
13138
+ border-radius: 8px;
13139
+ display: inline-block;
13140
+ letter-spacing: 4px;
13141
+ margin: 15px 0;
13142
+ font-family: monospace;
13143
+ }
13144
+ .info-box {
13145
+ background-color: #fff;
13146
+ border-left: 4px solid #2C8E99;
13147
+ padding: 15px;
13148
+ margin: 20px 0;
13149
+ }
13150
+ </style>
13151
+ </head>
13152
+ <body>
13153
+ <div class="container">
13154
+ <div class="header">
13155
+ <h1>Welcome to MetaEstetics</h1>
13156
+ </div>
13157
+ <div class="content">
13158
+ <p>Hello {{patientName}},</p>
13159
+
13160
+ <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>
13161
+
13162
+ <div class="info-box">
13163
+ <p><strong>What you'll get access to:</strong></p>
13164
+ <ul>
13165
+ <li>Your complete treatment history</li>
13166
+ <li>Upcoming appointment details</li>
13167
+ <li>Pre and post-treatment instructions</li>
13168
+ <li>Direct messaging with your clinic</li>
13169
+ </ul>
13170
+ </div>
13171
+
13172
+ <p>To claim your profile, use this registration token:</p>
13173
+
13174
+ <div style="text-align: center;">
13175
+ <span class="token">{{inviteToken}}</span>
13176
+ </div>
13177
+
13178
+ <p><strong>Important:</strong> This token will expire on <strong>{{expirationDate}}</strong>.</p>
13179
+
13180
+ <p>To create your account:</p>
13181
+ <ol>
13182
+ <li>Download the MetaEstetics Patient app or visit {{registrationUrl}}</li>
13183
+ <li>Create an account using your email address</li>
13184
+ <li>When prompted, enter the token shown above</li>
13185
+ <li>Your profile will be automatically linked to your new account</li>
13186
+ </ol>
13187
+
13188
+ <div style="text-align: center;">
13189
+ <a href="{{registrationUrl}}" class="button">Create Your Account</a>
13190
+ </div>
13191
+
13192
+ <p>If you have any questions or didn't expect this email, please contact {{contactName}} at {{contactEmail}}.</p>
13193
+ </div>
13194
+ <div class="footer">
13195
+ <p>This is an automated message from {{clinicName}}. Please do not reply to this email.</p>
13196
+ <p>&copy; {{currentYear}} MetaEstetics. All rights reserved.</p>
13197
+ </div>
13198
+ </div>
13199
+ </body>
13200
+ </html>
13201
+ `;
13202
+
13203
+ // src/admin/mailing/patientInvite/patientInvite.mailing.ts
13204
+ var PatientInviteMailingService = class extends BaseMailingService {
13205
+ /**
13206
+ * Constructor for PatientInviteMailingService
13207
+ * @param firestore - Firestore instance provided by the caller
13208
+ * @param mailgunClient - Mailgun client instance (mailgun.js v10+) provided by the caller
13209
+ */
13210
+ constructor(firestore19, mailgunClient) {
13211
+ super(firestore19, mailgunClient);
13212
+ this.DEFAULT_REGISTRATION_URL = "https://metaesthetics.net/patient/register";
13213
+ this.DEFAULT_SUBJECT = "Claim Your Patient Profile - MetaEstetics";
13214
+ this.DEFAULT_MAILGUN_DOMAIN = "mg.metaesthetics.net";
13215
+ }
13216
+ /**
13217
+ * Sends a patient invitation email
13218
+ * @param data - The patient invitation data
13219
+ * @returns Promise resolved when email is sent
13220
+ */
13221
+ async sendInvitationEmail(data) {
13222
+ var _a, _b, _c, _d, _e, _f;
13223
+ try {
13224
+ Logger.info(
13225
+ "[PatientInviteMailingService] Sending invitation email to",
13226
+ data.token.email
13227
+ );
13228
+ const expirationDate = data.token.expiresAt.toDate().toLocaleDateString("en-US", {
13229
+ weekday: "long",
13230
+ year: "numeric",
13231
+ month: "long",
13232
+ day: "numeric"
13233
+ });
13234
+ const registrationUrl = ((_a = data.options) == null ? void 0 : _a.registrationUrl) || this.DEFAULT_REGISTRATION_URL;
13235
+ const contactName = data.clinic.contactName || "Clinic Administrator";
13236
+ const contactEmail = data.clinic.contactEmail;
13237
+ const subject = ((_b = data.options) == null ? void 0 : _b.customSubject) || this.DEFAULT_SUBJECT;
13238
+ const fromAddress = ((_c = data.options) == null ? void 0 : _c.fromAddress) || `MetaEstetics <no-reply@${((_d = data.options) == null ? void 0 : _d.mailgunDomain) || this.DEFAULT_MAILGUN_DOMAIN}>`;
13239
+ const currentYear = (/* @__PURE__ */ new Date()).getFullYear().toString();
13240
+ const patientName = `${data.patient.firstName} ${data.patient.lastName}`;
13241
+ const templateVariables = {
13242
+ clinicName: data.clinic.name,
13243
+ patientName,
13244
+ inviteToken: data.token.token,
13245
+ expirationDate,
13246
+ registrationUrl,
13247
+ contactName,
13248
+ contactEmail,
13249
+ currentYear
13250
+ };
13251
+ Logger.info("[PatientInviteMailingService] Template variables:", {
13252
+ clinicName: templateVariables.clinicName,
13253
+ patientName: templateVariables.patientName,
13254
+ expirationDate: templateVariables.expirationDate,
13255
+ registrationUrl: templateVariables.registrationUrl,
13256
+ contactName: templateVariables.contactName,
13257
+ contactEmail: templateVariables.contactEmail,
13258
+ hasInviteToken: !!templateVariables.inviteToken
13259
+ });
13260
+ const html = this.renderTemplate(
13261
+ patientInvitationTemplate,
13262
+ templateVariables
13263
+ );
13264
+ const mailgunSendData = {
13265
+ to: data.token.email,
13266
+ from: fromAddress,
13267
+ subject,
13268
+ html
13269
+ };
13270
+ const domainToSendFrom = ((_e = data.options) == null ? void 0 : _e.mailgunDomain) || this.DEFAULT_MAILGUN_DOMAIN;
13271
+ Logger.info("[PatientInviteMailingService] Sending email with data:", {
13272
+ domain: domainToSendFrom,
13273
+ to: mailgunSendData.to,
13274
+ from: mailgunSendData.from,
13275
+ subject: mailgunSendData.subject,
13276
+ hasHtml: !!mailgunSendData.html
13277
+ });
13278
+ const result = await this.sendEmail(domainToSendFrom, mailgunSendData);
13279
+ await this.logEmailAttempt(
13280
+ {
13281
+ to: data.token.email,
13282
+ subject,
13283
+ templateName: "patient_invitation"
13284
+ },
13285
+ true
13286
+ );
13287
+ return result;
13288
+ } catch (error) {
13289
+ Logger.error(
13290
+ "[PatientInviteMailingService] Error sending invitation email:",
13291
+ {
13292
+ errorMessage: error.message,
13293
+ errorDetails: error.details,
13294
+ errorStatus: error.status,
13295
+ stack: error.stack
13296
+ }
13297
+ );
13298
+ await this.logEmailAttempt(
13299
+ {
13300
+ to: data.token.email,
13301
+ subject: ((_f = data.options) == null ? void 0 : _f.customSubject) || this.DEFAULT_SUBJECT,
13302
+ templateName: "patient_invitation"
13303
+ },
13304
+ false,
13305
+ error
13306
+ );
13307
+ throw error;
13308
+ }
13309
+ }
13310
+ /**
13311
+ * Handles the patient token creation event from Cloud Functions.
13312
+ * Fetches necessary data and sends the invitation email.
13313
+ * @param tokenData - The fully typed token object including its id
13314
+ * @param mailgunConfig - Mailgun configuration (from, domain, optional registrationUrl)
13315
+ * @returns Promise resolved when the email is sent
13316
+ */
13317
+ async handleTokenCreationEvent(tokenData, mailgunConfig) {
13318
+ try {
13319
+ Logger.info(
13320
+ "[PatientInviteMailingService] Handling token creation event for token:",
13321
+ tokenData.id
13322
+ );
13323
+ if (!tokenData || !tokenData.id || !tokenData.token || !tokenData.email) {
13324
+ throw new Error(
13325
+ `Invalid token data: Missing required properties. Token ID: ${tokenData == null ? void 0 : tokenData.id}`
13326
+ );
13327
+ }
13328
+ if (!tokenData.patientId) {
13329
+ throw new Error(
13330
+ `Token ${tokenData.id} is missing patientId reference`
13331
+ );
13332
+ }
13333
+ if (!tokenData.clinicId) {
13334
+ throw new Error(`Token ${tokenData.id} is missing clinicId reference`);
13335
+ }
13336
+ if (!tokenData.expiresAt) {
13337
+ throw new Error(`Token ${tokenData.id} is missing expiration date`);
13338
+ }
13339
+ if (tokenData.status !== "active" /* ACTIVE */ && String(tokenData.status).toLowerCase() !== "active") {
13340
+ Logger.warn(
13341
+ "[PatientInviteMailingService] Token is not active, skipping email.",
13342
+ { tokenId: tokenData.id, status: tokenData.status }
13343
+ );
13344
+ return;
13345
+ }
13346
+ Logger.info(
13347
+ `[PatientInviteMailingService] Token status validation:`,
13348
+ {
13349
+ tokenId: tokenData.id,
13350
+ status: tokenData.status,
13351
+ statusType: typeof tokenData.status
13352
+ }
13353
+ );
13354
+ Logger.info(
13355
+ `[PatientInviteMailingService] Fetching patient data: ${tokenData.patientId}`
13356
+ );
13357
+ const patientRef = this.db.collection(PATIENTS_COLLECTION).doc(tokenData.patientId);
13358
+ const patientDoc = await patientRef.get();
13359
+ if (!patientDoc.exists) {
13360
+ throw new Error(`Patient ${tokenData.patientId} not found`);
13361
+ }
13362
+ const patientData = patientDoc.data();
13363
+ if (!patientData) {
13364
+ throw new Error(
13365
+ `Patient ${tokenData.patientId} has invalid data structure`
13366
+ );
13367
+ }
13368
+ const sensitiveInfoRef = patientRef.collection(PATIENT_SENSITIVE_INFO_COLLECTION).doc(tokenData.patientId);
13369
+ const sensitiveInfoDoc = await sensitiveInfoRef.get();
13370
+ let firstName = "Patient";
13371
+ let lastName = "";
13372
+ if (sensitiveInfoDoc.exists) {
13373
+ const sensitiveInfo = sensitiveInfoDoc.data();
13374
+ firstName = (sensitiveInfo == null ? void 0 : sensitiveInfo.firstName) || "Patient";
13375
+ lastName = (sensitiveInfo == null ? void 0 : sensitiveInfo.lastName) || "";
13376
+ } else {
13377
+ Logger.warn(
13378
+ `[PatientInviteMailingService] No sensitive info found for patient ${tokenData.patientId}, using displayName`
13379
+ );
13380
+ const displayNameParts = (patientData.displayName || "Patient").split(" ");
13381
+ firstName = displayNameParts[0] || "Patient";
13382
+ lastName = displayNameParts.slice(1).join(" ") || "";
13383
+ }
13384
+ Logger.info(
13385
+ `[PatientInviteMailingService] Patient found: ${firstName} ${lastName}`
13386
+ );
13387
+ Logger.info(
13388
+ `[PatientInviteMailingService] Fetching clinic data: ${tokenData.clinicId}`
13389
+ );
13390
+ const clinicRef = this.db.collection(CLINICS_COLLECTION).doc(tokenData.clinicId);
13391
+ const clinicDoc = await clinicRef.get();
13392
+ if (!clinicDoc.exists) {
13393
+ throw new Error(`Clinic ${tokenData.clinicId} not found`);
13394
+ }
13395
+ const clinicData = clinicDoc.data();
13396
+ if (!clinicData || !clinicData.contactInfo) {
13397
+ throw new Error(
13398
+ `Clinic ${tokenData.clinicId} has invalid data structure`
13399
+ );
13400
+ }
13401
+ Logger.info(
13402
+ `[PatientInviteMailingService] Clinic found: ${clinicData.name}`
13403
+ );
13404
+ if (!mailgunConfig.fromAddress) {
13405
+ Logger.warn(
13406
+ "[PatientInviteMailingService] No fromAddress provided, using default"
13407
+ );
13408
+ mailgunConfig.fromAddress = `MetaEstetics <no-reply@${this.DEFAULT_MAILGUN_DOMAIN}>`;
13409
+ }
13410
+ const emailData = {
13411
+ token: {
13412
+ id: tokenData.id,
13413
+ token: tokenData.token,
13414
+ patientId: tokenData.patientId,
13415
+ email: tokenData.email,
13416
+ clinicId: tokenData.clinicId,
13417
+ expiresAt: tokenData.expiresAt
13418
+ },
13419
+ patient: {
13420
+ firstName,
13421
+ lastName
13422
+ },
13423
+ clinic: {
13424
+ name: clinicData.name || "Medical Clinic",
13425
+ contactEmail: clinicData.contactInfo.email || "contact@clinic.com",
13426
+ contactName: "Clinic Admin"
13427
+ },
13428
+ options: {
13429
+ fromAddress: mailgunConfig.fromAddress,
13430
+ mailgunDomain: mailgunConfig.domain,
13431
+ registrationUrl: mailgunConfig.registrationUrl
13432
+ }
13433
+ };
13434
+ Logger.info(
13435
+ "[PatientInviteMailingService] Email data prepared, sending invitation"
13436
+ );
13437
+ await this.sendInvitationEmail(emailData);
13438
+ Logger.info(
13439
+ "[PatientInviteMailingService] Invitation email sent successfully"
13440
+ );
13441
+ } catch (error) {
13442
+ Logger.error(
13443
+ "[PatientInviteMailingService] Error handling token creation event:",
13444
+ {
13445
+ errorMessage: error.message,
13446
+ errorDetails: error.details,
13447
+ errorStatus: error.status,
13448
+ stack: error.stack,
13449
+ tokenId: tokenData == null ? void 0 : tokenData.id
13450
+ }
13451
+ );
13452
+ throw error;
13453
+ }
13454
+ }
13455
+ };
13456
+
13076
13457
  // src/admin/users/user-profile.admin.ts
13077
13458
  import * as admin18 from "firebase-admin";
13078
13459
  var UserProfileAdminService = class {
@@ -13378,6 +13759,7 @@ export {
13378
13759
  DocumentManagerAdminService,
13379
13760
  ExistingPractitionerInviteMailingService,
13380
13761
  FilledFormsAggregationService,
13762
+ INVITE_TOKENS_COLLECTION,
13381
13763
  Logger,
13382
13764
  NOTIFICATIONS_COLLECTION,
13383
13765
  NO_SHOW_ANALYTICS_SUBCOLLECTION,
@@ -13391,8 +13773,10 @@ export {
13391
13773
  PROCEDURE_ANALYTICS_SUBCOLLECTION,
13392
13774
  PatientAggregationService,
13393
13775
  PatientInstructionStatus,
13776
+ PatientInviteMailingService,
13394
13777
  PatientRequirementOverallStatus,
13395
13778
  PatientRequirementsAdminService,
13779
+ PatientTokenStatus,
13396
13780
  PractitionerAggregationService,
13397
13781
  PractitionerInviteAggregationService,
13398
13782
  PractitionerInviteMailingService,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@blackcode_sa/metaestetics-api",
3
3
  "private": false,
4
- "version": "1.14.29",
4
+ "version": "1.14.32",
5
5
  "description": "Firebase authentication service with anonymous upgrade support",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist/index.mjs",
@@ -15,6 +15,8 @@ export type { ClinicInfo } from '../types/profile';
15
15
  export type { Practitioner, PractitionerToken } from '../types/practitioner';
16
16
  export type { PractitionerInvite } from '../types/clinic/practitioner-invite.types';
17
17
  export type { DoctorInfo } from '../types/clinic';
18
+ export type { PatientToken } from '../types/patient/token.types';
19
+ export { PatientTokenStatus, INVITE_TOKENS_COLLECTION } from '../types/patient/token.types';
18
20
  export type { Procedure, ProcedureSummaryInfo } from '../types/procedure';
19
21
  export type { PatientProfile as Patient } from '../types/patient';
20
22
  export type { Appointment } from '../types/appointment';
@@ -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
+