* wip * wip * feature: Booking Tasker without DI yet * feature: Booking Tasker with DI * fix type check 1 * fix type check 2 * fix * comment booking tasker for now * fix: DI regularBookingService api v2 * fix: convert trigger.dev SDK imports to dynamic imports to fix unit tests The unit tests were failing because BookingEmailAndSmsTriggerTasker.ts had static imports of trigger files that depend on @trigger.dev/sdk. This caused Vitest to try to resolve the SDK at module load time, even though it should be optional. Changed all imports in BookingEmailAndSmsTriggerTasker.ts from static to dynamic (using await import()) so the trigger files are only loaded when the tasker methods are actually called, not at module load time during tests. This fixes the 'Failed to load url @trigger.dev/sdk' errors that were causing 28+ test failures. Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix unit tests * keep inline smsAndEmailHandler.send calls * chore: add team feature flag * add satisfies ModuleLoader * fix type check app flags * move trigger in feature * fix: add trigger.dev prisma generator * fix: email app statuses * fix: CalEvtBuilder unit test * chore: improvements, schema, config, retry * fixup! chore: improvements, schema, config, retry * chore: cleanup code * chore: cleanup code * chore: clean code and give full payload * remove log * add booking notifications queue * add attendee phone number for sms * bump trigger to 4.1.0 * add missing booking seat data in attendee * update config * fix logger regular booking service * fix: prisma as external deps of trigger * fix yarn.lock * revert change to example app booking page * fix: resolve circular dependencies and improve cold start performance in trigger tasks - Convert BookingRepository import to type-only in CalendarEventBuilder.ts to eliminate circular dependency risk - Convert EventNameObjectType, CalendarEvent, and JsonObject imports to type-only in BookingEmailAndSmsTaskService.ts - Use dynamic imports in all trigger notification tasks (confirm, request, reschedule, rr-reschedule) to reduce cold start time - Move heavy imports (BookingEmailSmsHandler, BookingRepository, prisma, TriggerDevLogger, BookingEmailAndSmsTaskService) inside run functions - Eliminates module-level prisma import which violates repo guidelines and adds cold start overhead - Reduces initial module dependency graph by deferring heavy imports (email templates, workflows, large repositories) until task execution Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: improve cold start performance in reminderScheduler with dynamic imports - Remove module-level prisma import (violates 'No prisma outside repositories' guideline) - Use dynamic imports for UserRepository (1,168 lines) - only loaded when needed in EMAIL_ATTENDEE action - Use dynamic imports for twilio provider (386 lines) - only loaded in cancelScheduledMessagesAndScheduleEmails - Use dynamic imports for all manager functions by action type: - scheduleSMSReminder (387 lines) - loaded only for SMS actions - scheduleEmailReminder (459 lines) - loaded only for Email actions - scheduleWhatsappReminder (266 lines) - loaded only for WhatsApp actions - scheduleAIPhoneCall (478 lines) - loaded only for AI phone call actions - Use dynamic imports for sendOrScheduleWorkflowEmails in cancelScheduledMessagesAndScheduleEmails - Significantly reduces cold start time by deferring heavy module loading until execution paths need them - Eliminates module-level prisma import that violated repository pattern guidelines Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: improve cold start performance in BookingEmailSmsHandler with dynamic imports - Remove module-level imports of all email-manager functions (653 LOC + 30+ email templates) - Add dynamic imports in each method (_handleRescheduled, _handleRoundRobinRescheduled, _handleConfirmed, _handleRequested, handleAddGuests) - Defer heavy email-manager loading until method execution - Verified no circular dependencies between email-manager and bookings - Significantly reduces cold start time for RegularBookingService and BookingEmailAndSmsTaskService Co-Authored-By: morgan@cal.com <morgan@cal.com> * fix: use dynamic imports * update yarn lock * code review * trigger config project ref in env * update yarn lock * add .env.example trigger variables * add .env.example trigger variables * fix: cleanup error handling and loggin * fix: trigger config from env * fix: small typo fix * fix: ai review comments * fix: ai review comments * ai review * Add `create` on `WorkflowReminderRepository` * `sendWorkflowEmails` tasker to accept lazy payload * Add `scheduleLazyEmailWorkflow` to `WorkflowService * Process scheduled date in `scheduleLazyEmailWorkflow` * Type fixes * Use `WorkflowService` to schedule * Refactor `scheduleEmailReminderForEvt` to use `WorkflowService.processWorkflowScheduledDate` * Pass seat reference to lazy scheduled workflow reminder * Refactor `WorkflowReminderRepository` to accept prisma as constructor * Abstract `FormSubmissionData` type * Abstract select statement and add get by uid to `BookingRepository` * Add `FormSubmissionData` type * Add `findByIdIncludeStepAndWorkflow` to `WorkflowReminderRepository` * Tasker payload to accept `workflowReminderId` * Create `BookingSeatRepository` * Write `workflowReminderId` to tasker payload * Add `generateCommonScheduleFunctionParams` to `WorkflowService` * Init * Use services in tasker * Abstract types * In reminderScheduler use workflowService to generate common params * Type fix * Return params from emailWorkflowService.generateParametersToBuildEmailWorkflowContent * Use emailWorkflowService to generate params * Abstract types * Generate email content and send in EmailWorkflowService * Move check to caller * Use EmailWorkflowService to generate email payload in emailReminderManager * Fix initalizing repository * Use evt.videoCallData first before the booking metadata * Only get non-deleted references to build calendar event * Remove check for videoCallData.id * Dynamic import credit service * BookingRepository.getByUid to only return what we need from attendee * Type fixes * test: Add comprehensive tests for lazy email workflow generation and fix broken tests - Fix prisma mocks in sms-manager.test.ts and outOfOfficeCreateOrUpdate.handler.test.ts to export both 'default' and named 'prisma' exports - Add EmailWorkflowService.test.ts with 4 tests for error handling paths - Add sendWorkflowEmails.test.ts with 7 tests for schema validation and email sending - Add tests to WorkflowService.test.ts for scheduleLazyEmailWorkflow, processWorkflowScheduledDate, and generateCommonScheduleFunctionParams methods Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com> * Write `seatReferenceUid` * Return promise * Fix log * Change to `Promise.allSettled` * Type fix * Fix failing test * fix: reorder workflow step checks to fix test failure The test 'should throw error if workflow step not found on reminder' was failing because the code checked workflowStep.verifiedAt before checking if workflowStep exists. When workflowStep is null, this caused the error message to include 'undefined' instead of the expected workflow step id. Fixed by reordering the checks: 1. First check if workflowStep exists 2. Then check if workflowStep.verifiedAt exists Also updated the test expectation to match the correct error message. Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com> --------- Co-authored-by: cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Co-authored-by: hbjORbj <sldisek783@gmail.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Alex van Andel <me@alexvanandel.com>
352 lines
12 KiB
TypeScript
352 lines
12 KiB
TypeScript
import dayjs from "@calcom/dayjs";
|
|
import {
|
|
getAttendeeToBeUsedInSMS,
|
|
getSMSMessageWithVariables,
|
|
shouldUseTwilio,
|
|
} from "@calcom/ee/workflows/lib/reminders/utils";
|
|
import type { CreditCheckFn } from "@calcom/features/ee/billing/credit-service";
|
|
import { getSubmitterEmail } from "@calcom/features/tasker/tasks/triggerFormSubmittedNoEvent/formSubmissionValidation";
|
|
import { SENDER_ID } from "@calcom/lib/constants";
|
|
import logger from "@calcom/lib/logger";
|
|
import { safeStringify } from "@calcom/lib/safeStringify";
|
|
import { getTranslation } from "@calcom/lib/server/i18n";
|
|
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
|
import type { PrismaClient } from "@calcom/prisma";
|
|
import prisma from "@calcom/prisma";
|
|
import { WorkflowTemplates, WorkflowActions, WorkflowMethods } from "@calcom/prisma/enums";
|
|
import { WorkflowTriggerEvents } from "@calcom/prisma/enums";
|
|
|
|
import { isAttendeeAction } from "../actionHelperFunctions";
|
|
import { getSenderId } from "../alphanumericSenderIdSupport";
|
|
import { IMMEDIATE_WORKFLOW_TRIGGER_EVENTS } from "../constants";
|
|
import { WorkflowOptOutContactRepository } from "../repository/workflowOptOutContact";
|
|
import { WorkflowOptOutService } from "../service/workflowOptOutService";
|
|
import type { FormSubmissionData, BookingInfo } from "../types";
|
|
import type { ScheduleReminderArgs } from "./emailReminderManager";
|
|
import { scheduleSmsOrFallbackEmail, sendSmsOrFallbackEmail } from "./messageDispatcher";
|
|
import * as twilio from "./providers/twilioProvider";
|
|
import customTemplate, { transformRoutingFormResponsesToVariableFormat } from "./templates/customTemplate";
|
|
import smsReminderTemplate from "./templates/smsReminderTemplate";
|
|
|
|
export enum timeUnitLowerCase {
|
|
DAY = "day",
|
|
MINUTE = "minute",
|
|
YEAR = "year",
|
|
}
|
|
const log = logger.getSubLogger({ prefix: ["[smsReminderManager]"] });
|
|
|
|
export type ScheduleTextReminderAction = Extract<
|
|
WorkflowActions,
|
|
"SMS_ATTENDEE" | "SMS_NUMBER" | "WHATSAPP_ATTENDEE" | "WHATSAPP_NUMBER"
|
|
>;
|
|
export type ScheduleTextReminderArgs = ScheduleReminderArgs & {
|
|
reminderPhone: string | null;
|
|
message: string;
|
|
action: ScheduleTextReminderAction;
|
|
userId?: number | null;
|
|
teamId?: number | null;
|
|
isVerificationPending?: boolean;
|
|
prisma?: PrismaClient;
|
|
verifiedAt: Date | null;
|
|
creditCheckFn: CreditCheckFn;
|
|
};
|
|
|
|
export type ScheduleTextReminderArgsWithRequiredFields = Omit<
|
|
ScheduleTextReminderArgs,
|
|
"reminderPhone" | "sender"
|
|
> & {
|
|
reminderPhone: string; // Required, not nullable
|
|
sender: string; // Required, not nullable
|
|
};
|
|
|
|
export const scheduleSMSReminder = async (args: ScheduleTextReminderArgs) => {
|
|
const { reminderPhone, sender, verifiedAt, workflowStepId, action, userId, teamId, isVerificationPending } =
|
|
args;
|
|
if (!verifiedAt) {
|
|
log.warn(`Workflow step ${workflowStepId} not yet verified`);
|
|
return;
|
|
}
|
|
|
|
if (!reminderPhone) {
|
|
log.warn(`No phone number provided for WhatsApp reminder in workflow step ${workflowStepId}`);
|
|
return;
|
|
}
|
|
|
|
if (await WorkflowOptOutContactRepository.isOptedOut(reminderPhone)) {
|
|
log.warn(`Phone number opted out of SMS workflows`, safeStringify({ workflowStep: workflowStepId }));
|
|
return;
|
|
}
|
|
|
|
const senderID = getSenderId(reminderPhone, sender || SENDER_ID);
|
|
const params: ScheduleTextReminderArgs = {
|
|
...args,
|
|
sender: senderID,
|
|
};
|
|
|
|
//SMS_ATTENDEE action does not need to be verified
|
|
//isVerificationPending is from all already existing workflows (once they edit their workflow, they will also have to verify the number)
|
|
async function getIsNumberVerified() {
|
|
if (action === WorkflowActions.SMS_ATTENDEE) return true;
|
|
const verifiedNumber = await prisma.verifiedNumber.findFirst({
|
|
where: {
|
|
OR: [{ userId }, { teamId }],
|
|
phoneNumber: reminderPhone || "",
|
|
},
|
|
});
|
|
if (verifiedNumber) return true;
|
|
return isVerificationPending;
|
|
}
|
|
|
|
const isNumberVerified = await getIsNumberVerified();
|
|
|
|
if (!isNumberVerified) {
|
|
log.warn(`Phone number not verified`, safeStringify({ reminderPhone, isNumberVerified }));
|
|
return;
|
|
}
|
|
|
|
if (params.evt) {
|
|
await scheduleSMSReminderForEvt(
|
|
params as ScheduleTextReminderArgsWithRequiredFields & { evt: BookingInfo }
|
|
);
|
|
} else {
|
|
await scheduleSMSReminderForForm(
|
|
params as ScheduleTextReminderArgsWithRequiredFields & {
|
|
formData: FormSubmissionData;
|
|
}
|
|
);
|
|
}
|
|
};
|
|
|
|
const scheduleSMSReminderForEvt = async (
|
|
args: ScheduleTextReminderArgsWithRequiredFields & { evt: BookingInfo }
|
|
) => {
|
|
const {
|
|
evt,
|
|
reminderPhone,
|
|
triggerEvent,
|
|
action,
|
|
timeSpan,
|
|
message = "",
|
|
workflowStepId,
|
|
template,
|
|
sender,
|
|
userId,
|
|
teamId,
|
|
seatReferenceUid,
|
|
creditCheckFn,
|
|
} = args;
|
|
|
|
const { startTime, endTime } = evt;
|
|
const uid = evt.uid as string;
|
|
const timeUnit: timeUnitLowerCase | undefined = timeSpan.timeUnit?.toLocaleLowerCase() as timeUnitLowerCase;
|
|
let scheduledDate = null;
|
|
|
|
if (triggerEvent === WorkflowTriggerEvents.BEFORE_EVENT) {
|
|
scheduledDate = timeSpan.time && timeUnit ? dayjs(startTime).subtract(timeSpan.time, timeUnit) : null;
|
|
} else if (triggerEvent === WorkflowTriggerEvents.AFTER_EVENT) {
|
|
scheduledDate = timeSpan.time && timeUnit ? dayjs(endTime).add(timeSpan.time, timeUnit) : null;
|
|
}
|
|
|
|
const useTwilio = shouldUseTwilio(triggerEvent, scheduledDate);
|
|
if (useTwilio) {
|
|
const attendeeToBeUsedInSMS = getAttendeeToBeUsedInSMS(action, evt, reminderPhone);
|
|
|
|
const name = action === WorkflowActions.SMS_ATTENDEE ? attendeeToBeUsedInSMS.name : "";
|
|
const attendeeName =
|
|
action === WorkflowActions.SMS_ATTENDEE ? evt.organizer.name : attendeeToBeUsedInSMS.name;
|
|
const timeZone =
|
|
action === WorkflowActions.SMS_ATTENDEE ? attendeeToBeUsedInSMS.timeZone : evt.organizer.timeZone;
|
|
|
|
let smsMessage = message;
|
|
|
|
if (smsMessage) {
|
|
smsMessage = await getSMSMessageWithVariables(smsMessage, evt, attendeeToBeUsedInSMS, action);
|
|
} else if (template === WorkflowTemplates.REMINDER) {
|
|
smsMessage =
|
|
smsReminderTemplate(
|
|
false,
|
|
evt.organizer.language.locale,
|
|
action,
|
|
evt.organizer.timeFormat,
|
|
evt.startTime,
|
|
evt.title,
|
|
timeZone,
|
|
attendeeName,
|
|
name
|
|
) || message;
|
|
}
|
|
|
|
if (smsMessage.trim().length > 0) {
|
|
const smsMessageWithoutOptOut = await WorkflowOptOutService.addOptOutMessage(
|
|
smsMessage,
|
|
evt.organizer.language.locale
|
|
);
|
|
|
|
// Allows debugging generated email content without waiting for sendgrid to send emails
|
|
log.debug(`Sending sms for trigger ${triggerEvent}`, smsMessage);
|
|
|
|
if (IMMEDIATE_WORKFLOW_TRIGGER_EVENTS.includes(triggerEvent)) {
|
|
try {
|
|
await sendSmsOrFallbackEmail({
|
|
twilioData: {
|
|
phoneNumber: reminderPhone,
|
|
body: smsMessage,
|
|
sender,
|
|
bodyWithoutOptOut: smsMessageWithoutOptOut,
|
|
bookingUid: evt.uid,
|
|
userId,
|
|
teamId,
|
|
},
|
|
fallbackData: isAttendeeAction(action)
|
|
? {
|
|
email: evt.attendees[0].email,
|
|
t: await getTranslation(evt.attendees[0].language.locale, "common"),
|
|
replyTo: evt.organizer.email,
|
|
}
|
|
: undefined,
|
|
creditCheckFn,
|
|
});
|
|
} catch (error) {
|
|
log.error(`Error sending SMS with error ${error}`);
|
|
}
|
|
}
|
|
|
|
if (
|
|
(triggerEvent === WorkflowTriggerEvents.BEFORE_EVENT ||
|
|
triggerEvent === WorkflowTriggerEvents.AFTER_EVENT) &&
|
|
scheduledDate
|
|
) {
|
|
try {
|
|
// schedule at least 15 minutes in advance and at most 2 hours in advance
|
|
const scheduledNotification = await scheduleSmsOrFallbackEmail({
|
|
twilioData: {
|
|
phoneNumber: reminderPhone,
|
|
body: smsMessage,
|
|
scheduledDate: scheduledDate.toDate(),
|
|
sender,
|
|
bookingUid: evt.uid,
|
|
userId,
|
|
teamId,
|
|
},
|
|
fallbackData: isAttendeeAction(action)
|
|
? {
|
|
email: evt.attendees[0].email,
|
|
t: await getTranslation(evt.attendees[0].language.locale, "common"),
|
|
replyTo: evt.organizer.email,
|
|
workflowStepId,
|
|
}
|
|
: undefined,
|
|
creditCheckFn,
|
|
});
|
|
|
|
if (scheduledNotification?.sid) {
|
|
await prisma.workflowReminder.create({
|
|
data: {
|
|
bookingUid: uid,
|
|
workflowStepId: workflowStepId,
|
|
method: WorkflowMethods.SMS,
|
|
scheduledDate: scheduledDate.toDate(),
|
|
scheduled: true,
|
|
referenceId: scheduledNotification.sid,
|
|
seatReferenceId: seatReferenceUid,
|
|
},
|
|
});
|
|
}
|
|
} catch (error) {
|
|
log.error(`Error scheduling SMS with error ${error}`);
|
|
}
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (!useTwilio && scheduledDate) {
|
|
// Write to DB and send to CRON if scheduled reminder date is past 2 hours from now
|
|
await prisma.workflowReminder.create({
|
|
data: {
|
|
bookingUid: uid,
|
|
workflowStepId: workflowStepId,
|
|
method: WorkflowMethods.SMS,
|
|
scheduledDate: scheduledDate.toDate(),
|
|
scheduled: false,
|
|
seatReferenceId: seatReferenceUid,
|
|
},
|
|
});
|
|
}
|
|
};
|
|
|
|
// sends all immediately, no scheduling needed
|
|
const scheduleSMSReminderForForm = async (
|
|
args: ScheduleTextReminderArgsWithRequiredFields & {
|
|
formData: FormSubmissionData;
|
|
}
|
|
) => {
|
|
const { message, triggerEvent, reminderPhone, sender, userId, teamId, action, formData, creditCheckFn } =
|
|
args;
|
|
|
|
let smsMessage = message;
|
|
|
|
if (smsMessage && formData.responses) {
|
|
const timeFormat = getTimeFormatStringFromUserTimeFormat(formData.user.timeFormat);
|
|
|
|
const variables = {
|
|
responses: transformRoutingFormResponsesToVariableFormat(formData.responses),
|
|
};
|
|
|
|
const processedMessage = customTemplate(smsMessage, variables, formData.user.locale, timeFormat);
|
|
smsMessage = processedMessage.text;
|
|
}
|
|
|
|
if (smsMessage.trim().length > 0) {
|
|
const smsMessageWithoutOptOut = await WorkflowOptOutService.addOptOutMessage(
|
|
smsMessage,
|
|
formData.user.locale
|
|
);
|
|
|
|
// Allows debugging generated email content without waiting for sendgrid to send emails
|
|
log.debug(`Sending sms for trigger ${triggerEvent}`, smsMessage);
|
|
|
|
try {
|
|
const submitterEmail = getSubmitterEmail(formData.responses);
|
|
|
|
await sendSmsOrFallbackEmail({
|
|
twilioData: {
|
|
phoneNumber: reminderPhone,
|
|
body: smsMessage,
|
|
sender,
|
|
bodyWithoutOptOut: smsMessageWithoutOptOut,
|
|
userId,
|
|
teamId,
|
|
},
|
|
fallbackData:
|
|
isAttendeeAction(action) && submitterEmail
|
|
? {
|
|
email: submitterEmail,
|
|
t: await getTranslation(formData.user.locale, "common"),
|
|
replyTo: formData.user.email,
|
|
}
|
|
: undefined,
|
|
creditCheckFn,
|
|
});
|
|
} catch (error) {
|
|
log.error(`Error sending SMS with error ${error}`);
|
|
}
|
|
}
|
|
};
|
|
|
|
export const deleteScheduledSMSReminder = async (reminderId: number, referenceId: string | null) => {
|
|
try {
|
|
if (referenceId) {
|
|
await twilio.cancelSMS(referenceId);
|
|
}
|
|
|
|
await prisma.workflowReminder.delete({
|
|
where: {
|
|
id: reminderId,
|
|
},
|
|
});
|
|
} catch (error) {
|
|
log.error(`Error canceling reminder with error ${error}`);
|
|
}
|
|
};
|