Files
calendar/packages/features/ee/workflows/lib/reminders/utils.ts
T
Amit SharmaGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>Carina Wollendorfer
3bbba9c6cb feat: add 5 new workflow triggers for booking events (#23068)
* feat: add 5 new workflow triggers for booking events

- Add BOOKING_REJECTED, BOOKING_REQUESTED, BOOKING_PAYMENT_INITIATED, BOOKING_PAID, BOOKING_NO_SHOW_UPDATED to WorkflowTriggerEvents enum
- Update workflow constants to include new trigger options
- Implement workflow trigger logic for booking rejected and requested events
- Add translations for new workflow triggers following {enum}_trigger format
- Generate updated Prisma types for new schema changes

Co-Authored-By: amit@cal.com <samit91848@gmail.com>

* fix: type check, remove as any

* feat: add workflow trigger for BOOKING_REQUESTED in handleNewBooking.ts

- Add WorkflowTriggerEvents import to handleNewBooking.ts
- Implement workflow trigger logic for BOOKING_REQUESTED in else block
- Filter workflows by BOOKING_REQUESTED trigger and call scheduleWorkflowReminders
- Use proper calendar event object construction without type casting
- Add error handling for workflow reminder scheduling

Co-Authored-By: amit@cal.com <samit91848@gmail.com>

* fix: resolve type errors in workflow trigger implementations

- Add proper database includes for user information in handleConfirmation.ts
- Fix ExtendedCalendarEvent type structure with correct hosts mapping
- Add missing properties to calendar event objects in handleMarkNoShow.ts
- Ensure all workflow triggers follow proper type patterns

Co-Authored-By: amit@cal.com <samit91848@gmail.com>

* feat: add workflow test configurations for new booking triggers

- Add workflow configurations for BOOKING_REQUESTED and BOOKING_PAYMENT_INITIATED in fresh-booking.test.ts
- Add workflow configuration for BOOKING_REJECTED in confirm.handler.test.ts
- Enable previously skipped confirm.handler.test.ts
- Remove workflow test assertions temporarily until triggers are fully functional
- Maintain webhook test coverage while adding workflow test infrastructure

Co-Authored-By: amit@cal.com <samit91848@gmail.com>

* fix: add missing mockSuccessfulVideoMeetingCreation import to confirm.handler.test.ts

- Import mockSuccessfulVideoMeetingCreation from bookingScenario utils
- Add mock call to BOOKING_REJECTED workflow test case
- Resolves ReferenceError that was causing unit test CI failure

Co-Authored-By: amit@cal.com <samit91848@gmail.com>

* refactor: improve _scheduleWorkflowReminders readability and add missing booking trigger events

- Extract complex conditional logic into helper functions (isImmediateTrigger, isTimeBased, shouldProcessWorkflow)
- Add missing workflow trigger events with immediate execution logic
- Update test workflows to use different actions (EMAIL_ATTENDEE, SMS_ATTENDEE) for better differentiation
- Fix translation function mock in confirm.handler.test.ts using mockNoTranslations utility
- Maintain existing functionality while improving code maintainability

Co-Authored-By: amit@cal.com <samit91848@gmail.com>

* filter outside scheduleWorkflowReminder

* fix type check

* chore: add more tests

* test: add comprehensive unit tests for handleMarkNoShow with webhook and workflow coverage

- Create handleMarkNoShow.test.ts following confirm.handler.test.ts pattern
- Add expectBookingNoShowUpdatedWebhookToHaveBeenFired utility function
- Test both webhook and workflow triggers for BOOKING_NO_SHOW_UPDATED
- Cover attendee/host no-show scenarios, multiple attendees, and error cases
- All 6 unit tests pass with proper mocking of external dependencies

Co-Authored-By: amit@cal.com <samit91848@gmail.com>

* Revert "test: add comprehensive unit tests for handleMarkNoShow with webhook and workflow coverage"

This reverts commit 764299220279f0c012392dec24d3150246bfc4ad.

* fix: add new workflow triggers to api/v2

* update swagger docs

* fix: e2e

* fix type check

* fix tests, add test for before after events

* fix unit tests

* revert confirm.handler.test

* fix: unit tests

* review fixes

* refactor WorkflowService

* remove logs

* remove unused

* fix: type check

* fix: missed before after events for recurring

* fix: calendarEvent handleMarkNoShow

* fix error message

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* review fixes

* add missing BOOKING_PAID workflow trigger

* fix pathname

* fix: test for BOOKING_REQUESTED

* review fixes

* Update packages/features/bookings/lib/handleSeats/handleSeats.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com>
2025-09-04 16:55:09 +05:30

135 lines
4.6 KiB
TypeScript

import dayjs from "@calcom/dayjs";
import { dub } from "@calcom/features/auth/lib/dub";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { WorkflowActions, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
import { IMMEDIATE_WORKFLOW_TRIGGER_EVENTS } from "../constants";
import { getWorkflowRecipientEmail } from "../getWorkflowReminders";
import type { AttendeeInBookingInfo, BookingInfo } from "./smsReminderManager";
import type { VariablesType } from "./templates/customTemplate";
import customTemplate from "./templates/customTemplate";
export const bulkShortenLinks = async (links: string[]) => {
if (!process.env.DUB_API_KEY) {
return links.map((link) => ({ shortLink: link }));
}
const linksToShorten = links.filter((link) => link);
const results = await dub.links.createMany(
linksToShorten.map((link) => ({
domain: "sms.cal.com",
url: link,
folderId: "fold_wx3NZDKQYbLDbncSubeMu0ss",
}))
);
return links.map((link) => {
const createdLink = results.find(
(result): result is Extract<typeof result, { url: string }> =>
!("error" in result) && result.url === link
);
if (createdLink) {
return { shortLink: createdLink.shortLink };
} else {
return { shortLink: link };
}
});
};
export const getSMSMessageWithVariables = async (
smsMessage: string,
evt: BookingInfo,
attendeeToBeUsedInSMS: AttendeeInBookingInfo,
action: WorkflowActions
) => {
const recipientEmail = getWorkflowRecipientEmail({
action,
attendeeEmail: attendeeToBeUsedInSMS.email,
});
const urls = {
meetingUrl: bookingMetadataSchema.parse(evt.metadata || {})?.videoCallUrl || "",
cancelLink: `${evt.bookerUrl ?? WEBSITE_URL}/booking/${evt.uid}?cancel=true${
recipientEmail ? `&cancelledBy=${recipientEmail}` : ""
}`,
rescheduleLink: `${evt.bookerUrl ?? WEBSITE_URL}/reschedule/${evt.uid}${
recipientEmail ? `?rescheduledBy=${recipientEmail}` : ""
}`,
};
const [{ shortLink: meetingUrl }, { shortLink: cancelLink }, { shortLink: rescheduleLink }] =
await bulkShortenLinks([urls.meetingUrl, urls.cancelLink, urls.rescheduleLink]);
const timeZone =
action === WorkflowActions.SMS_ATTENDEE ? attendeeToBeUsedInSMS.timeZone : evt.organizer.timeZone;
const variables: VariablesType = {
eventName: evt.title,
organizerName: evt.organizer.name,
attendeeName: attendeeToBeUsedInSMS.name,
attendeeFirstName: attendeeToBeUsedInSMS.firstName,
attendeeLastName: attendeeToBeUsedInSMS.lastName,
attendeeEmail: attendeeToBeUsedInSMS.email,
eventDate: dayjs(evt.startTime).tz(timeZone),
eventEndTime: dayjs(evt.endTime).tz(timeZone),
timeZone: timeZone,
location: evt.location,
additionalNotes: evt.additionalNotes,
responses: evt.responses,
meetingUrl,
cancelLink,
rescheduleLink,
cancelReason: evt.cancellationReason,
rescheduleReason: evt.rescheduleReason,
attendeeTimezone: evt.attendees[0].timeZone,
eventTimeInAttendeeTimezone: dayjs(evt.startTime).tz(evt.attendees[0].timeZone),
eventEndTimeInAttendeeTimezone: dayjs(evt.endTime).tz(evt.attendees[0].timeZone),
};
const locale =
action === WorkflowActions.SMS_ATTENDEE
? attendeeToBeUsedInSMS.language?.locale
: evt.organizer.language.locale;
const customMessage = customTemplate(smsMessage, variables, locale, evt.organizer.timeFormat);
smsMessage = customMessage.text;
return smsMessage;
};
export const getAttendeeToBeUsedInSMS = (
action: WorkflowActions,
evt: BookingInfo,
reminderPhone: string | null
) => {
let attendeeToBeUsedInSMS: AttendeeInBookingInfo | null = null;
if (action === WorkflowActions.SMS_ATTENDEE) {
const attendeeWithReminderPhoneAsSMSReminderNumber =
reminderPhone && evt.attendees.find((attendee) => attendee.email === evt.responses?.email?.value);
attendeeToBeUsedInSMS = attendeeWithReminderPhoneAsSMSReminderNumber
? attendeeWithReminderPhoneAsSMSReminderNumber
: evt.attendees[0];
} else {
attendeeToBeUsedInSMS = evt.attendees[0];
}
return attendeeToBeUsedInSMS;
};
export const shouldUseTwilio = (trigger: WorkflowTriggerEvents, scheduledDate: dayjs.Dayjs | null) => {
if (IMMEDIATE_WORKFLOW_TRIGGER_EVENTS.includes(trigger)) {
return true;
}
if (trigger === WorkflowTriggerEvents.BEFORE_EVENT || trigger === WorkflowTriggerEvents.AFTER_EVENT) {
const currentDate = dayjs();
if (
scheduledDate &&
currentDate.isBefore(scheduledDate.subtract(15, "minute")) &&
!scheduledDate.isAfter(currentDate.add(2, "hour"))
) {
return true;
}
}
return false;
};