@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.
@@ -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";
@@ -11115,17 +11124,27 @@ var BookingAdmin = class {
11115
11124
  startTime: start.toDate().toISOString(),
11116
11125
  endTime: end.toDate().toISOString()
11117
11126
  });
11118
- const MAX_EVENT_DURATION_MS = 24 * 60 * 60 * 1e3;
11127
+ const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1e3;
11119
11128
  const queryStart = admin16.firestore.Timestamp.fromMillis(
11120
11129
  start.toMillis() - MAX_EVENT_DURATION_MS
11121
11130
  );
11122
- const eventsRef = this.db.collection(`clinics/${clinicId}/calendar`).where("eventTime.start", ">=", queryStart).where("eventTime.start", "<", end).orderBy("eventTime.start");
11131
+ const eventsRef = this.db.collection(`clinics/${clinicId}/calendar`).where("eventTime.start", ">=", queryStart).where("eventTime.start", "<=", end).orderBy("eventTime.start");
11123
11132
  const snapshot = await eventsRef.get();
11124
11133
  const events = snapshot.docs.map((doc3) => ({
11125
11134
  ...doc3.data(),
11126
11135
  id: doc3.id
11127
11136
  })).filter((event) => {
11128
- return event.eventTime.end.toMillis() > start.toMillis();
11137
+ const overlaps = event.eventTime.end.toMillis() > start.toMillis();
11138
+ if (!overlaps) {
11139
+ Logger.debug("[BookingAdmin] Filtered out non-overlapping event", {
11140
+ eventId: event.id,
11141
+ eventStart: event.eventTime.start.toDate().toISOString(),
11142
+ eventEnd: event.eventTime.end.toDate().toISOString(),
11143
+ queryStart: start.toDate().toISOString(),
11144
+ queryEnd: end.toDate().toISOString()
11145
+ });
11146
+ }
11147
+ return overlaps;
11129
11148
  });
11130
11149
  Logger.debug("[BookingAdmin] Retrieved clinic calendar events", {
11131
11150
  clinicId,
@@ -11161,17 +11180,27 @@ var BookingAdmin = class {
11161
11180
  startTime: start.toDate().toISOString(),
11162
11181
  endTime: end.toDate().toISOString()
11163
11182
  });
11164
- const MAX_EVENT_DURATION_MS = 24 * 60 * 60 * 1e3;
11183
+ const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1e3;
11165
11184
  const queryStart = admin16.firestore.Timestamp.fromMillis(
11166
11185
  start.toMillis() - MAX_EVENT_DURATION_MS
11167
11186
  );
11168
- const eventsRef = this.db.collection(`practitioners/${practitionerId}/calendar`).where("eventTime.start", ">=", queryStart).where("eventTime.start", "<", end).orderBy("eventTime.start");
11187
+ const eventsRef = this.db.collection(`practitioners/${practitionerId}/calendar`).where("eventTime.start", ">=", queryStart).where("eventTime.start", "<=", end).orderBy("eventTime.start");
11169
11188
  const snapshot = await eventsRef.get();
11170
11189
  const events = snapshot.docs.map((doc3) => ({
11171
11190
  ...doc3.data(),
11172
11191
  id: doc3.id
11173
11192
  })).filter((event) => {
11174
- return event.eventTime.end.toMillis() > start.toMillis();
11193
+ const overlaps = event.eventTime.end.toMillis() > start.toMillis();
11194
+ if (!overlaps) {
11195
+ Logger.debug("[BookingAdmin] Filtered out non-overlapping practitioner event", {
11196
+ eventId: event.id,
11197
+ eventStart: event.eventTime.start.toDate().toISOString(),
11198
+ eventEnd: event.eventTime.end.toDate().toISOString(),
11199
+ queryStart: start.toDate().toISOString(),
11200
+ queryEnd: end.toDate().toISOString()
11201
+ });
11202
+ }
11203
+ return overlaps;
11175
11204
  });
11176
11205
  Logger.debug("[BookingAdmin] Retrieved practitioner calendar events", {
11177
11206
  practitionerId,
@@ -13053,6 +13082,378 @@ var ExistingPractitionerInviteMailingService = class extends BaseMailingService
13053
13082
  }
13054
13083
  };
13055
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
+
13056
13457
  // src/admin/users/user-profile.admin.ts
13057
13458
  import * as admin18 from "firebase-admin";
13058
13459
  var UserProfileAdminService = class {
@@ -13358,6 +13759,7 @@ export {
13358
13759
  DocumentManagerAdminService,
13359
13760
  ExistingPractitionerInviteMailingService,
13360
13761
  FilledFormsAggregationService,
13762
+ INVITE_TOKENS_COLLECTION,
13361
13763
  Logger,
13362
13764
  NOTIFICATIONS_COLLECTION,
13363
13765
  NO_SHOW_ANALYTICS_SUBCOLLECTION,
@@ -13371,8 +13773,10 @@ export {
13371
13773
  PROCEDURE_ANALYTICS_SUBCOLLECTION,
13372
13774
  PatientAggregationService,
13373
13775
  PatientInstructionStatus,
13776
+ PatientInviteMailingService,
13374
13777
  PatientRequirementOverallStatus,
13375
13778
  PatientRequirementsAdminService,
13779
+ PatientTokenStatus,
13376
13780
  PractitionerAggregationService,
13377
13781
  PractitionerInviteAggregationService,
13378
13782
  PractitionerInviteMailingService,
package/dist/index.js CHANGED
@@ -16780,15 +16780,37 @@ async function searchCalendarEventsUtil(db, params) {
16780
16780
  constraints.push((0, import_firestore45.where)("eventType", "==", filters.eventType));
16781
16781
  }
16782
16782
  if (filters.dateRange) {
16783
- constraints.push((0, import_firestore45.where)("eventTime.start", ">=", filters.dateRange.start));
16783
+ const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1e3;
16784
+ const extendedStart = import_firestore45.Timestamp.fromMillis(
16785
+ filters.dateRange.start.toMillis() - MAX_EVENT_DURATION_MS
16786
+ );
16787
+ constraints.push((0, import_firestore45.where)("eventTime.start", ">=", extendedStart));
16784
16788
  constraints.push((0, import_firestore45.where)("eventTime.start", "<=", filters.dateRange.end));
16785
16789
  }
16786
16790
  try {
16787
16791
  const finalQuery = (0, import_firestore45.query)(collectionRef, ...constraints);
16788
16792
  const querySnapshot = await (0, import_firestore45.getDocs)(finalQuery);
16789
- const events = querySnapshot.docs.map(
16793
+ let events = querySnapshot.docs.map(
16790
16794
  (doc47) => ({ id: doc47.id, ...doc47.data() })
16791
16795
  );
16796
+ if (filters.dateRange) {
16797
+ events = events.filter((event) => {
16798
+ const overlaps = event.eventTime.end.toMillis() > filters.dateRange.start.toMillis();
16799
+ if (!overlaps) {
16800
+ console.debug(
16801
+ `[searchCalendarEventsUtil] Filtered out non-overlapping event:`,
16802
+ {
16803
+ eventId: event.id,
16804
+ eventStart: event.eventTime.start.toDate().toISOString(),
16805
+ eventEnd: event.eventTime.end.toDate().toISOString(),
16806
+ queryStart: filters.dateRange.start.toDate().toISOString(),
16807
+ queryEnd: filters.dateRange.end.toDate().toISOString()
16808
+ }
16809
+ );
16810
+ }
16811
+ return overlaps;
16812
+ });
16813
+ }
16792
16814
  return events;
16793
16815
  } catch (error) {
16794
16816
  console.error("Error searching calendar events:", error);
package/dist/index.mjs CHANGED
@@ -16926,15 +16926,37 @@ async function searchCalendarEventsUtil(db, params) {
16926
16926
  constraints.push(where25("eventType", "==", filters.eventType));
16927
16927
  }
16928
16928
  if (filters.dateRange) {
16929
- constraints.push(where25("eventTime.start", ">=", filters.dateRange.start));
16929
+ const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1e3;
16930
+ const extendedStart = Timestamp26.fromMillis(
16931
+ filters.dateRange.start.toMillis() - MAX_EVENT_DURATION_MS
16932
+ );
16933
+ constraints.push(where25("eventTime.start", ">=", extendedStart));
16930
16934
  constraints.push(where25("eventTime.start", "<=", filters.dateRange.end));
16931
16935
  }
16932
16936
  try {
16933
16937
  const finalQuery = query25(collectionRef, ...constraints);
16934
16938
  const querySnapshot = await getDocs25(finalQuery);
16935
- const events = querySnapshot.docs.map(
16939
+ let events = querySnapshot.docs.map(
16936
16940
  (doc47) => ({ id: doc47.id, ...doc47.data() })
16937
16941
  );
16942
+ if (filters.dateRange) {
16943
+ events = events.filter((event) => {
16944
+ const overlaps = event.eventTime.end.toMillis() > filters.dateRange.start.toMillis();
16945
+ if (!overlaps) {
16946
+ console.debug(
16947
+ `[searchCalendarEventsUtil] Filtered out non-overlapping event:`,
16948
+ {
16949
+ eventId: event.id,
16950
+ eventStart: event.eventTime.start.toDate().toISOString(),
16951
+ eventEnd: event.eventTime.end.toDate().toISOString(),
16952
+ queryStart: filters.dateRange.start.toDate().toISOString(),
16953
+ queryEnd: filters.dateRange.end.toDate().toISOString()
16954
+ }
16955
+ );
16956
+ }
16957
+ return overlaps;
16958
+ });
16959
+ }
16938
16960
  return events;
16939
16961
  } catch (error) {
16940
16962
  console.error("Error searching calendar events:", error);
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.28",
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",
@@ -339,26 +339,44 @@ export class BookingAdmin {
339
339
  endTime: end.toDate().toISOString(),
340
340
  });
341
341
 
342
- const MAX_EVENT_DURATION_MS = 24 * 60 * 60 * 1000;
342
+ // Increased to 30 days to handle long blocking events (e.g., holidays, extended time off)
343
+ // This ensures we catch blocking events that start before our query range but overlap with it
344
+ const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
343
345
  const queryStart = admin.firestore.Timestamp.fromMillis(
344
346
  start.toMillis() - MAX_EVENT_DURATION_MS
345
347
  );
346
348
 
349
+ // Query for events that:
350
+ // 1. Start before or during our query range (eventTime.start < end)
351
+ // 2. We'll post-filter to ensure they overlap (eventTime.end > start)
347
352
  const eventsRef = this.db
348
353
  .collection(`clinics/${clinicId}/calendar`)
349
354
  .where("eventTime.start", ">=", queryStart)
350
- .where("eventTime.start", "<", end)
355
+ .where("eventTime.start", "<=", end)
351
356
  .orderBy("eventTime.start");
352
357
 
353
358
  const snapshot = await eventsRef.get();
354
359
 
360
+ // Post-filter to ensure events actually overlap with our query range
361
+ // An event overlaps if: eventTime.start < queryEnd AND eventTime.end > queryStart
355
362
  const events = snapshot.docs
356
363
  .map((doc) => ({
357
364
  ...doc.data(),
358
365
  id: doc.id,
359
366
  }))
360
367
  .filter((event: any) => {
361
- return event.eventTime.end.toMillis() > start.toMillis();
368
+ // Event overlaps if it ends after our start time
369
+ const overlaps = event.eventTime.end.toMillis() > start.toMillis();
370
+ if (!overlaps) {
371
+ Logger.debug("[BookingAdmin] Filtered out non-overlapping event", {
372
+ eventId: event.id,
373
+ eventStart: event.eventTime.start.toDate().toISOString(),
374
+ eventEnd: event.eventTime.end.toDate().toISOString(),
375
+ queryStart: start.toDate().toISOString(),
376
+ queryEnd: end.toDate().toISOString(),
377
+ });
378
+ }
379
+ return overlaps;
362
380
  });
363
381
 
364
382
  Logger.debug("[BookingAdmin] Retrieved clinic calendar events", {
@@ -403,26 +421,44 @@ export class BookingAdmin {
403
421
  endTime: end.toDate().toISOString(),
404
422
  });
405
423
 
406
- const MAX_EVENT_DURATION_MS = 24 * 60 * 60 * 1000;
424
+ // Increased to 30 days to handle long blocking events (e.g., holidays, extended time off)
425
+ // This ensures we catch blocking events that start before our query range but overlap with it
426
+ const MAX_EVENT_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
407
427
  const queryStart = admin.firestore.Timestamp.fromMillis(
408
428
  start.toMillis() - MAX_EVENT_DURATION_MS
409
429
  );
410
430
 
431
+ // Query for events that:
432
+ // 1. Start before or during our query range (eventTime.start <= end)
433
+ // 2. We'll post-filter to ensure they overlap (eventTime.end > start)
411
434
  const eventsRef = this.db
412
435
  .collection(`practitioners/${practitionerId}/calendar`)
413
436
  .where("eventTime.start", ">=", queryStart)
414
- .where("eventTime.start", "<", end)
437
+ .where("eventTime.start", "<=", end)
415
438
  .orderBy("eventTime.start");
416
439
 
417
440
  const snapshot = await eventsRef.get();
418
441
 
442
+ // Post-filter to ensure events actually overlap with our query range
443
+ // An event overlaps if: eventTime.start < queryEnd AND eventTime.end > queryStart
419
444
  const events = snapshot.docs
420
445
  .map((doc) => ({
421
446
  ...doc.data(),
422
447
  id: doc.id,
423
448
  }))
424
449
  .filter((event: any) => {
425
- return event.eventTime.end.toMillis() > start.toMillis();
450
+ // Event overlaps if it ends after our start time
451
+ const overlaps = event.eventTime.end.toMillis() > start.toMillis();
452
+ if (!overlaps) {
453
+ Logger.debug("[BookingAdmin] Filtered out non-overlapping practitioner event", {
454
+ eventId: event.id,
455
+ eventStart: event.eventTime.start.toDate().toISOString(),
456
+ eventEnd: event.eventTime.end.toDate().toISOString(),
457
+ queryStart: start.toDate().toISOString(),
458
+ queryEnd: end.toDate().toISOString(),
459
+ });
460
+ }
461
+ return overlaps;
426
462
  });
427
463
 
428
464
  Logger.debug("[BookingAdmin] Retrieved practitioner calendar events", {
@@ -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';