Files
calendar/packages/features/ee/workflows/lib/reminders/utils.ts
T
Udit TakkarGitHubUdit Takkarunknown <>Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>Udit Takkar
4081d11fbe feat: workflow auto translation (#27087)
* feat: workflow auto translation

* tests: add unit tests

* refactor: tests and workflow

* fix: type err

* fix: type err

* fix: remove redundant index on WorkflowStepTranslation

The @@index on [workflowStepId, field, targetLocale] duplicates the @@unique
constraint on the same columns. A unique index already provides efficient
lookups, so the separate @@index adds storage overhead and write latency
without benefit.

Addresses Cubic AI review feedback (confidence 9/10).

Co-Authored-By: unknown <>

* fix: correct locale mapping when translation API returns null

Map translations with their corresponding locales before filtering to
preserve correct locale-to-translation associations. Previously, filtering
out null translations would reindex the array, causing incorrect locale
mappings when any translation in the batch failed.

Also fixes pre-existing lint warnings:
- Move exports to end of file
- Add explicit return type to processTranslations
- Replace ternary with if-else for upsertMany selection

Co-Authored-By: udit@cal.com <udit222001@gmail.com>

* fix: address review feedback for workflow auto-translation

- Add change detection before creating translation tasks
- Rename userLocale to sourceLocale in task props for clarity
- Show source language in UI with new translation key
- Extract SUPPORTED_LOCALES to shared translationConstants.ts
- Fix locale mapping bug in translateEventTypeData.ts
- Add WhatsApp translation support
- Abstract translation lookup into shared translationLookup.ts helper
- Restore if-else readability for SCANNING_WORKFLOW_STEPS

Co-authored-by: Udit Takkar <udit.takkar@cal.com>
Co-Authored-By: unknown <>

* fix: update test to use sourceLocale instead of userLocale

Co-Authored-By: unknown <>

* refactor: feedback

* fix: handle first time

* fix: tests

* fix: tests

* fix: address Cubic AI review feedback (confidence 9/10 issues)

- WhatsApp translation: Apply variable substitution using getSMSMessageWithVariables
  and clear contentSid when using translated body to ensure Twilio uses the
  translated text instead of the original template

- update.handler.ts: Change sourceLocale assignment from ?? to || for consistency
  with tasker payload behavior (line 481)

- ITranslationService.ts: Rename methods from plural to singular naming:
  - getWorkflowStepTranslations -> getWorkflowStepTranslation
  - getEventTypeTranslations -> getEventTypeTranslation
  Updated all call sites and tests accordingly

Co-Authored-By: unknown <>

* fix: address Cubic AI review feedback (confidence 9/10+ issues)

- Fix getSMSMessageWithVariables to handle WHATSAPP_ATTENDEE action for
  locale and timezone (confidence 9/10)
- Remove WhatsApp translation feature that set contentSid to undefined
  since Twilio ignores body parameter for WhatsApp and requires
  pre-approved Message Templates (confidence 10/10)

Co-Authored-By: unknown <>

* fix: translatio

* Add tests: packages/features/eventTypeTranslation/repositories/EventTypeTranslationRepository.test.ts

Generated by Paragon from proposal for PR #27087

* Add tests: packages/features/tasker/tasks/translateWorkflowStepData.test.ts

Generated by Paragon from proposal for PR #27087

* chore: nit

* chore: verfied atg

* fix: set sourceLocale for new steps, add shouldDirty to checkbox, remove spec docs

- Set sourceLocale fallback in addedSteps mapping to fix stale detection mismatch
- Add { shouldDirty: true } to autoTranslateEnabled checkbox onChange
- Remove specs/workflow-translation/ directory (planning docs, not for repo)

Co-authored-by: Udit Takkar <udit.07.takkar@gmail.com>
Co-Authored-By: unknown <>

* chore: add specs back

* fix: type error

* fix: type error

* fix: type err

* fix: tests

* refactor: feedback

* fix: type err

* refactor

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <udit.takkar@cal.com>
Co-authored-by: Udit Takkar <udit.07.takkar@gmail.com>
2026-02-25 01:03:55 +05:30

137 lines
4.8 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 "../types";
import type { VariablesType } from "./templates/customTemplate";
import customTemplate, { transformBookingResponsesToVariableFormat } 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 || action === WorkflowActions.WHATSAPP_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: transformBookingResponsesToVariableFormat(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 || action === WorkflowActions.WHATSAPP_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;
};