* 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>
288 lines
9.2 KiB
TypeScript
288 lines
9.2 KiB
TypeScript
import dayjs from "@calcom/dayjs";
|
|
import logger from "@calcom/lib/logger";
|
|
import { getTranslation } from "@calcom/i18n/server";
|
|
import prisma from "@calcom/prisma";
|
|
import {
|
|
WorkflowActions,
|
|
WorkflowMethods,
|
|
WorkflowTemplates,
|
|
WorkflowTriggerEvents,
|
|
} from "@calcom/prisma/enums";
|
|
|
|
import { isAttendeeAction } from "../actionHelperFunctions";
|
|
import { IMMEDIATE_WORKFLOW_TRIGGER_EVENTS } from "../constants";
|
|
import {
|
|
getContentSidForTemplate,
|
|
getContentVariablesForTemplate,
|
|
} from "../reminders/templates/whatsapp/ContentSidMapping";
|
|
import type { BookingInfo } from "../types";
|
|
import { scheduleSmsOrFallbackEmail, sendSmsOrFallbackEmail } from "./messageDispatcher";
|
|
import type { ScheduleTextReminderArgs, timeUnitLowerCase } from "./smsReminderManager";
|
|
import {
|
|
whatsappEventCancelledTemplate,
|
|
whatsappEventCompletedTemplate,
|
|
whatsappEventRescheduledTemplate,
|
|
whatsappReminderTemplate,
|
|
} from "./templates/whatsapp";
|
|
|
|
const log = logger.getSubLogger({ prefix: ["[whatsappReminderManager]"] });
|
|
|
|
export const scheduleWhatsappReminder = async (args: ScheduleTextReminderArgs & { evt: BookingInfo }) => {
|
|
const {
|
|
evt,
|
|
reminderPhone,
|
|
triggerEvent,
|
|
action,
|
|
timeSpan,
|
|
message = "",
|
|
workflowStepId,
|
|
template,
|
|
userId,
|
|
teamId,
|
|
isVerificationPending = false,
|
|
seatReferenceUid,
|
|
verifiedAt,
|
|
creditCheckFn,
|
|
} = args;
|
|
|
|
if (!verifiedAt) {
|
|
log.warn(`Workflow step ${workflowStepId} not verified`);
|
|
return;
|
|
}
|
|
|
|
const { startTime, endTime } = evt;
|
|
const uid = evt.uid as string;
|
|
const currentDate = dayjs();
|
|
const timeUnit: timeUnitLowerCase | undefined = timeSpan.timeUnit?.toLocaleLowerCase() as timeUnitLowerCase;
|
|
let scheduledDate = null;
|
|
|
|
//WHATSAPP_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.WHATSAPP_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 (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;
|
|
}
|
|
|
|
if (
|
|
scheduledDate &&
|
|
triggerEvent === WorkflowTriggerEvents.BEFORE_EVENT &&
|
|
dayjs(scheduledDate).isBefore(currentDate)
|
|
) {
|
|
log.debug(
|
|
`Skipping reminder for workflow step ${workflowStepId} - scheduled date ${scheduledDate} is in the past`
|
|
);
|
|
return;
|
|
}
|
|
|
|
const name = action === WorkflowActions.WHATSAPP_ATTENDEE ? evt.attendees[0].name : evt.organizer.name;
|
|
const attendeeName =
|
|
action === WorkflowActions.WHATSAPP_ATTENDEE ? evt.organizer.name : evt.attendees[0].name;
|
|
const timeZone =
|
|
action === WorkflowActions.WHATSAPP_ATTENDEE ? evt.attendees[0].timeZone : evt.organizer.timeZone;
|
|
const locale = evt.organizer.language.locale;
|
|
const timeFormat = evt.organizer.timeFormat;
|
|
|
|
let contentSid: string | undefined = getContentSidForTemplate(template);
|
|
const contentVariables = getContentVariablesForTemplate({
|
|
name,
|
|
attendeeName,
|
|
eventName: evt.title,
|
|
eventDate: dayjs(startTime).tz(timeZone).locale(locale).format("YYYY MMM D"),
|
|
startTime: dayjs(startTime)
|
|
.tz(timeZone)
|
|
.locale(locale)
|
|
.format(timeFormat || "h:mma"),
|
|
timeZone,
|
|
});
|
|
let textMessage = message;
|
|
|
|
switch (template) {
|
|
case WorkflowTemplates.REMINDER:
|
|
textMessage =
|
|
whatsappReminderTemplate(
|
|
false,
|
|
locale,
|
|
action,
|
|
timeFormat,
|
|
evt.startTime,
|
|
evt.title,
|
|
timeZone,
|
|
attendeeName,
|
|
name
|
|
) || message;
|
|
break;
|
|
case WorkflowTemplates.CANCELLED:
|
|
textMessage =
|
|
whatsappEventCancelledTemplate(
|
|
false,
|
|
locale,
|
|
action,
|
|
timeFormat,
|
|
evt.startTime,
|
|
evt.title,
|
|
timeZone,
|
|
attendeeName,
|
|
name
|
|
) || message;
|
|
break;
|
|
case WorkflowTemplates.RESCHEDULED:
|
|
textMessage =
|
|
whatsappEventRescheduledTemplate(
|
|
false,
|
|
locale,
|
|
action,
|
|
timeFormat,
|
|
evt.startTime,
|
|
evt.title,
|
|
timeZone,
|
|
attendeeName,
|
|
name
|
|
) || message;
|
|
break;
|
|
case WorkflowTemplates.COMPLETED:
|
|
textMessage =
|
|
whatsappEventCompletedTemplate(
|
|
false,
|
|
locale,
|
|
action,
|
|
timeFormat,
|
|
evt.startTime,
|
|
evt.title,
|
|
timeZone,
|
|
attendeeName,
|
|
name
|
|
) || message;
|
|
break;
|
|
default:
|
|
textMessage =
|
|
whatsappReminderTemplate(
|
|
false,
|
|
locale,
|
|
action,
|
|
timeFormat,
|
|
evt.startTime,
|
|
evt.title,
|
|
timeZone,
|
|
attendeeName,
|
|
name
|
|
) || message;
|
|
}
|
|
|
|
// Note: WhatsApp translation is not currently supported because:
|
|
// 1. WhatsApp Business API requires pre-approved Message Templates (contentSid) for business-initiated messages
|
|
// 2. The Twilio provider only sends contentSid/contentVariables for WhatsApp, ignoring the body parameter
|
|
// 3. Sending free-form text without a template will be rejected by WhatsApp outside the 24-hour service window
|
|
// To enable WhatsApp translation, a generic template with a single variable for the entire body would be needed.
|
|
|
|
// Allows debugging generated whatsapp content without waiting for twilio to send whatsapp messages
|
|
log.debug(`Sending Whatsapp for trigger ${triggerEvent}`, textMessage);
|
|
if (textMessage.length > 0 && reminderPhone && isNumberVerified) {
|
|
//send WHATSAPP when event is booked/cancelled/rescheduled
|
|
if (IMMEDIATE_WORKFLOW_TRIGGER_EVENTS.includes(triggerEvent)) {
|
|
try {
|
|
await sendSmsOrFallbackEmail({
|
|
twilioData: {
|
|
phoneNumber: reminderPhone,
|
|
body: textMessage,
|
|
sender: "",
|
|
bookingUid: evt.uid,
|
|
userId,
|
|
teamId,
|
|
isWhatsapp: true,
|
|
contentSid,
|
|
contentVariables,
|
|
},
|
|
fallbackData: isAttendeeAction(action)
|
|
? {
|
|
email: evt.attendees[0].email,
|
|
t: await getTranslation(evt.attendees[0].language.locale ?? "en", "common"),
|
|
replyTo: evt.organizer.email,
|
|
}
|
|
: undefined,
|
|
creditCheckFn,
|
|
});
|
|
} catch (error) {
|
|
console.log(`Error sending WHATSAPP with error ${error}`);
|
|
}
|
|
} else if (
|
|
(triggerEvent === WorkflowTriggerEvents.BEFORE_EVENT ||
|
|
triggerEvent === WorkflowTriggerEvents.AFTER_EVENT) &&
|
|
scheduledDate
|
|
) {
|
|
// schedule at least 15 minutes in advance and at most 2 hours in advance
|
|
if (
|
|
currentDate.isBefore(scheduledDate.subtract(15, "minute")) &&
|
|
!scheduledDate.isAfter(currentDate.add(2, "hour"))
|
|
) {
|
|
try {
|
|
const scheduledNotification = await scheduleSmsOrFallbackEmail({
|
|
twilioData: {
|
|
phoneNumber: reminderPhone,
|
|
body: textMessage,
|
|
scheduledDate: scheduledDate.toDate(),
|
|
sender: "",
|
|
bookingUid: evt.uid ?? "",
|
|
userId,
|
|
teamId,
|
|
isWhatsapp: true,
|
|
contentSid,
|
|
contentVariables,
|
|
},
|
|
fallbackData: isAttendeeAction(action)
|
|
? {
|
|
email: evt.attendees[0].email,
|
|
t: await getTranslation(evt.attendees[0].language.locale ?? "en", "common"),
|
|
replyTo: evt.organizer.email,
|
|
workflowStepId,
|
|
}
|
|
: undefined,
|
|
creditCheckFn,
|
|
});
|
|
|
|
if (scheduledNotification?.sid) {
|
|
await prisma.workflowReminder.create({
|
|
data: {
|
|
bookingUid: uid,
|
|
workflowStepId: workflowStepId,
|
|
method: WorkflowMethods.WHATSAPP,
|
|
scheduledDate: scheduledDate.toDate(),
|
|
scheduled: true,
|
|
referenceId: scheduledNotification.sid,
|
|
seatReferenceId: seatReferenceUid,
|
|
},
|
|
});
|
|
}
|
|
} catch (error) {
|
|
console.log(`Error scheduling WHATSAPP with error ${error}`);
|
|
}
|
|
} else if (scheduledDate.isAfter(currentDate.add(2, "hour"))) {
|
|
// 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.WHATSAPP,
|
|
scheduledDate: scheduledDate.toDate(),
|
|
scheduled: false,
|
|
seatReferenceId: seatReferenceUid,
|
|
},
|
|
});
|
|
}
|
|
}
|
|
}
|
|
};
|