feat: use form responses as workflow variables (#24716)
* remove add variable dropdown * feat: lang support * fix: type errors * feat: select voice agent * refactor: address feedback * refactor: address feedback * refactor: missing import * fix: types * add getAllWorkflowsFromRoutingForm to WorkflowService * fix error caused by undefined evt * fix type error * fix type error * fix tests * feat: add inbound calls * chore: formatting * chore * feat: finish inbound call * chore: formatting * fix: update bug * fix: types * code clean up * final fixes and clean up * remove console.log * remove template text form from triggers * add routing form repoditory function * refactor: Agent Configuration Sheet (#23930) * refactor: agent configuration sheet * chore: use default phone numbre * refactor: improvements * refactor: improvements * fix: types * fix: feedback * fix bug with key * chore: * fix: feedback * fix: prompt * add comments * fix: review * fix: review * refactor: class * refactor: class * fix test * allow cal ai action on form triggers * move any reusable code to scheduleAIPhoneCall * add missing await * use predefined FormSubmissionData type * add .trim() to sms message * pass contextData instead * finish base setup * add missing trigger in update-workflow.input.ts * allow cal.ai action for form triggers in handler * chore: add support for form workflows on api v2 * fixup! chore: add support for form workflows on api v2 * ai phone call on form submissions (WIP) * use existing type for Option array * pass chosen event type id * refactor: rename * Update apps/web/public/static/locales/en/common.json * Update apps/web/public/static/locales/en/common.json * add missing imports * chore: update set value * fix: remove index * fix: type error * fix: update tetss * use only repository functions in update handler * move all prisma queries from list.handler * review suggestions * fix: use logger * chore: handle workflows api v2 * chore: handle workflows api v2, split in 2 endpoints * fix workflow step creation * remove connect agent and fixes types * add type to workflow * chore: use workflow type in apiv2 WorkflowsOutputService * update worklfow type on update * chore: use workflow type in apiv2 WorkflowsOutputService * fix template body for torm trigger * some UI fixes for email subject/body * resetting email body when changing form triggers * use type field to query workflows * clean up all old active on values * remove responseId from all funciton calls * remove undefined from updateTemplate * refactor: don't use static * fix: type * refactor: split routing form and event-type workflows code * refactor: split routing form and event-type workflows code * fix template text when adding action * chore: don't rename WorkflowActivationDto to avoid ci blocking * refine update schedule to use only allowed actions * fix type error * don't allow whatsapp action with form trigger * fix type error * return early if activeOn array is empty * fix: from step type in BaseFormWorkflowStepDto * fixup! fix: from step type in BaseFormWorkflowStepDto * api v2 updates * move all prisma calls to repository (service/workflows.ts) * use FORM_TRIGGER_WORKFLOW_EVENTS for form queries * use userRepository * use FORM_TRIGGER_WORKFLOW_EVENTS in isFormTrigger * code clean up * code clean up * use repository functions in formSubmissionValidation.ts * fix: schema * refactor: * remove action check in update handler * add event type selection * event type selector improvements * adjust update.handler * set outboundEventTypeId * add back trpc import * fix agent repository functions * clean up * fix bugs caused by merge * pass eventTypeId to updateToolsFromAgentId * add migration for outboundEventTypeId * add SMS actions to allowed form action constants * add cal ai to allowed form actions * pick correct event type for web call * pass correct routed event type id * remove unsued import * fixes for offset api v2 * add missing responseId * fix failing test * fix failing test * improve error message * remove unused imports * chore: handle sms step action for form worklfow in dtos * fix typo * missing missing newStep * minor fixes * remove changes * add routedEventTypeId * fix type error * fix type error * fix typ error in executAPIPhoneCall.tsx * add back inboundEventTypeId * remove console.log * remove outdated code * small fixes * don't throw error for missing phone number * add back filtered triggerOptions * fix eventTypeId in testCall handler * fix type error * update migration * fix trigger is not defined * convert eventTypeId to string * only use outboundEventTypeId for FORM_SUBMITTED trigger * show toast when no event type selected * fix type errors * add missing translation * fix type error * remove callType * fix tests * small fixes * clean up AgentConfigurationSheet * remove EventTypeSelector file * code clean up * clean up * clean up * use resusable function for TestPhoneCallDialog and WebCallDialog * rename result * fix types for event type id * use repository runction in workflowReminder.ts * fix type error * pass eventTypeIds correctly * fix typo * custom variables from form responses * remove comment * Update apps/web/public/static/locales/en/common.json Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com> * use watch instead of getValues * change to z.record(z.unknown()) instead of any() * fix type of eventTypeId * check permissinon for outBoundEventTypeId * add isNaN check * improve function name * add tests * fixes for custom variables * improve test * update tools when outbound agent event type id changes * handle undefined eventDate in customTemplate * add info how to use form responses as variables * rename responses to routingFormResponses * remove cal ai from allowed steps api v2 * remove old migration file --------- Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Udit Takkar <udit222001@gmail.com> Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com> Co-authored-by: Benny Joo <sldisek783@gmail.com> Co-authored-by: cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Co-authored-by: Peer Richelsen <peeroke@gmail.com>
This commit is contained in:
co-authored by
Udit Takkar
CarinaWolli
Udit Takkar
Benny Joo
cal.com
Morgan
Peer Richelsen
parent
1ff5d57ded
commit
d7fc11df5e
@@ -1622,12 +1622,14 @@
|
||||
"example_1": "Example 1",
|
||||
"example_2": "Example 2",
|
||||
"booking_question_identifier": "Booking Question Identifier",
|
||||
"form_field_identifier": "Form Field Identifier",
|
||||
"company_size": "Company size",
|
||||
"what_help_needed": "What do you need help with?",
|
||||
"variable_format": "Variable format",
|
||||
"webhook_subscriber_url_reserved": "Webhook subscriber url is already defined",
|
||||
"custom_input_as_variable_info": "Ignore all special characters of the additional input label (use only letters and numbers), use uppercase for all letters and replace whitespaces with underscores.",
|
||||
"using_booking_questions_as_variables": "How do I use booking questions as variables?",
|
||||
"using_form_responses_as_variables": "How do I use form responses as variables?",
|
||||
"download_desktop_app": "Download desktop app",
|
||||
"set_ping_link": "Set Ping link",
|
||||
"rate_limit_exceeded": "Rate limit exceeded",
|
||||
@@ -1923,6 +1925,7 @@
|
||||
"show_attendees": "Share attendee information between guests",
|
||||
"show_available_seats_count": "Show the number of available seats",
|
||||
"how_booking_questions_as_variables": "How to use booking questions as variables?",
|
||||
"how_form_responses_as_variables": "How to use form responses as variables?",
|
||||
"format": "Format",
|
||||
"questions": "Questions",
|
||||
"all_info_your_booker_provide": "All the info your booker should provide before booking with you.",
|
||||
@@ -1939,6 +1942,7 @@
|
||||
"billing_portal": "Billing portal",
|
||||
"billing_help_cta": "Contact support",
|
||||
"ignore_special_characters_booking_questions": "Ignore special characters in your booking question identifier. Use only letters and numbers",
|
||||
"ignore_special_characters_form_responses": "Ignore special characters in your form field identifier. Use only letters and numbers",
|
||||
"retry": "Retry",
|
||||
"fetching_calendars_error": "There was a problem fetching your calendars. Please <1>try again</1> or reach out to customer support.",
|
||||
"calendar_connection_fail": "Calendar connection failed",
|
||||
|
||||
@@ -123,19 +123,19 @@ const getTimeSectionText = (trigger: WorkflowTriggerEvents, t: TFunction) => {
|
||||
|
||||
const CalAIAgentDataSkeleton = () => {
|
||||
return (
|
||||
<div className="p-4 mt-4 rounded-lg bg-muted">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="bg-muted mt-4 rounded-lg p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<SkeletonText className="w-28 h-5" />
|
||||
<div className="flex gap-2 items-center mt-2">
|
||||
<SkeletonText className="w-4 h-4" />
|
||||
<SkeletonText className="w-32 h-4" />
|
||||
<SkeletonText className="w-12 h-5" />
|
||||
<SkeletonText className="h-5 w-28" />
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<SkeletonText className="h-4 w-4" />
|
||||
<SkeletonText className="h-4 w-32" />
|
||||
<SkeletonText className="h-5 w-12" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-1 items-center">
|
||||
<SkeletonText className="w-24 h-8" />
|
||||
<SkeletonText className="w-8 h-8" />
|
||||
<div className="flex items-center gap-1">
|
||||
<SkeletonText className="h-8 w-24" />
|
||||
<SkeletonText className="h-8 w-8" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -518,7 +518,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="mb-3">
|
||||
<Label className="text-sm leading-none text-default">{t("when")}</Label>
|
||||
<Label className="text-default text-sm leading-none">{t("when")}</Label>
|
||||
<Controller
|
||||
name="trigger"
|
||||
control={form.control}
|
||||
@@ -601,8 +601,8 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
<div>
|
||||
{!!timeSectionText && (
|
||||
<div className="mt-3 mb-3">
|
||||
<Label className="mb-0 text-default">{timeSectionText}</Label>
|
||||
<div className="mb-3 mt-3">
|
||||
<Label className="text-default mb-0">{timeSectionText}</Label>
|
||||
<TimeTimeUnitInput disabled={props.readOnly} />
|
||||
</div>
|
||||
)}
|
||||
@@ -610,7 +610,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
{selectedOptions && setSelectedOptions && allOptions && (
|
||||
<div className={classNames(!!timeSectionText && "mb-3")}>
|
||||
{isOrganization ? (
|
||||
<div className="flex gap-2 items-center text-default">
|
||||
<div className="text-default flex items-center gap-2">
|
||||
<Label>{t("which_team_apply")}</Label>
|
||||
<div className="mb-2">
|
||||
<InfoBadge content={t("team_select_info")} />
|
||||
@@ -677,7 +677,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
)}
|
||||
{!!timeSectionText && (
|
||||
<div className="flex mt-1 text-gray-500">
|
||||
<div className="mt-1 flex text-gray-500">
|
||||
<Icon name="info" className="mr-1 mt-0.5 h-4 w-4" />
|
||||
<p className="text-sm">{t("testing_sms_workflow_info_message")}</p>
|
||||
</div>
|
||||
@@ -824,12 +824,12 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
/>
|
||||
<div className="mt-1.5 flex items-center gap-1">
|
||||
<Icon name="info" size="10" className="text-gray-500" />
|
||||
<div className="text-xs text-subtle">{t("sender_id_info")}</div>
|
||||
<div className="text-subtle text-xs">{t("sender_id_info")}</div>
|
||||
</div>
|
||||
</div>
|
||||
{form.formState.errors.steps &&
|
||||
form.formState?.errors?.steps[step.stepNumber - 1]?.sender && (
|
||||
<p className="mt-1 text-xs text-error">{t("sender_id_error_message")}</p>
|
||||
<p className="text-error mt-1 text-xs">{t("sender_id_error_message")}</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
@@ -848,23 +848,23 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
)}
|
||||
{isCalAIAction(form.getValues(`steps.${step.stepNumber - 1}.action`)) && !stepAgentId && (
|
||||
<div className="p-3 mt-2 rounded-2xl border bg-muted border-muted">
|
||||
<div className="flex flex-col gap-4 justify-between sm:flex-row sm:items-center sm:gap-0">
|
||||
<div className="bg-muted border-muted mt-2 rounded-2xl border p-3">
|
||||
<div className="flex flex-col justify-between gap-4 sm:flex-row sm:items-center sm:gap-0">
|
||||
<div>
|
||||
<h2 className="text-sm font-medium leading-none text-emphasis">
|
||||
<h2 className="text-emphasis text-sm font-medium leading-none">
|
||||
{t("cal_ai_agent")}
|
||||
<Badge startIcon="info" className="rounded-md ms-2" variant="warning">
|
||||
<Badge startIcon="info" className="ms-2 rounded-md" variant="warning">
|
||||
{t("set_up_required")}
|
||||
</Badge>
|
||||
</h2>
|
||||
<p className="mt-1 text-sm font-medium leading-none text-muted">
|
||||
<p className="text-muted mt-1 text-sm font-medium leading-none">
|
||||
{t("no_phone_number_connected")}.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
color="primary"
|
||||
disabled={props.readOnly || isCreatingAgent.current || hasAutoCreated.current}
|
||||
className="flex justify-center items-center"
|
||||
className="flex items-center justify-center"
|
||||
onClick={() => handleCreateAgent()}
|
||||
loading={createAgentMutation.isPending || isCreatingAgent.current}>
|
||||
{t("set_up_agent")}
|
||||
@@ -875,9 +875,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
|
||||
{stepAgentId && isAgentLoading && <CalAIAgentDataSkeleton />}
|
||||
{stepAgentId && agentData && (
|
||||
<div className="p-4 mt-4 rounded-lg bg-muted">
|
||||
<div className="bg-muted mt-4 rounded-lg p-4">
|
||||
<div
|
||||
className="flex justify-between items-center cursor-pointer"
|
||||
className="flex cursor-pointer items-center justify-between"
|
||||
onClick={(e) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (
|
||||
@@ -892,11 +892,11 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
}
|
||||
}}>
|
||||
<div>
|
||||
<h3 className="text-base font-medium text-emphasis">{t("cal_ai_agent")}</h3>
|
||||
<h3 className="text-emphasis text-base font-medium">{t("cal_ai_agent")}</h3>
|
||||
{arePhoneNumbersActive.length > 0 ? (
|
||||
<div className="flex gap-2 items-center">
|
||||
<Icon name="phone" className="w-4 h-4 text-emphasis" />
|
||||
<span className="text-sm text-emphasis">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="phone" className="text-emphasis h-4 w-4" />
|
||||
<span className="text-emphasis text-sm">
|
||||
{formatPhoneNumber(arePhoneNumbersActive[0].phoneNumber)}
|
||||
</span>
|
||||
<Badge variant="green" size="sm" withDot>
|
||||
@@ -904,12 +904,12 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</Badge>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-1 items-center">
|
||||
<span className="text-sm text-subtle">{t("no_phone_number_connected")}</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-subtle text-sm">{t("no_phone_number_connected")}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-1 items-center" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
|
||||
{arePhoneNumbersActive.length > 0 ? (
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
@@ -1019,7 +1019,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
)}
|
||||
{isPhoneNumberNeeded && (
|
||||
<div className="p-4 pt-0 mt-2 rounded-md bg-muted">
|
||||
<div className="bg-muted mt-2 rounded-md p-4 pt-0">
|
||||
<Label className="pt-4">{t("custom_phone_number")}</Label>
|
||||
<div className="block sm:flex">
|
||||
<Controller
|
||||
@@ -1059,7 +1059,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
|
||||
{form.formState.errors.steps && form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (
|
||||
<p className="mt-1 text-xs text-error">
|
||||
<p className="text-error mt-1 text-xs">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
@@ -1070,9 +1070,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
) : (
|
||||
!props.readOnly && (
|
||||
<>
|
||||
<div className="flex flex-col mt-6 w-full">
|
||||
<div className="mt-6 flex w-full flex-col">
|
||||
<Label className="">{t("verification_code")}</Label>
|
||||
<div className="flex items-center w-full">
|
||||
<div className="flex w-full items-center">
|
||||
<TextField
|
||||
containerClassName="w-full"
|
||||
className="h-8 rounded-xl"
|
||||
@@ -1102,7 +1102,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
{form.formState.errors.steps &&
|
||||
form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (
|
||||
<p className="mt-1 text-xs text-error">
|
||||
<p className="text-error mt-1 text-xs">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
@@ -1132,9 +1132,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
)}
|
||||
{isEmailAddressNeeded && !isCalAIAction(form.getValues(`steps.${step.stepNumber - 1}.action`)) && (
|
||||
<div className="p-4 mt-5 rounded-2xl border bg-muted border-muted">
|
||||
<div className="bg-muted border-muted mt-5 rounded-2xl border p-4">
|
||||
<Label>{t("email_address")}</Label>
|
||||
<div className="block gap-2 items-center sm:flex">
|
||||
<div className="block items-center gap-2 sm:flex">
|
||||
<Controller
|
||||
name={`steps.${step.stepNumber - 1}.sendTo`}
|
||||
render={({ field: { value, onChange } }) => (
|
||||
@@ -1160,7 +1160,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
size="sm"
|
||||
disabled={emailVerified || props.readOnly || false}
|
||||
className={classNames(
|
||||
"text-sm font-medium min-w-fit",
|
||||
"min-w-fit text-sm font-medium",
|
||||
emailVerified ? "hidden" : "mt-3 sm:mt-0"
|
||||
)}
|
||||
onClick={() => {
|
||||
@@ -1174,7 +1174,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</Button>
|
||||
</div>
|
||||
{form.formState.errors.steps && form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (
|
||||
<p className="mt-1 text-xs text-error">
|
||||
<p className="text-error mt-1 text-xs">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
@@ -1185,9 +1185,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
) : (
|
||||
!props.readOnly && (
|
||||
<>
|
||||
<div className="flex flex-col mt-3 w-full">
|
||||
<div className="mt-3 flex w-full flex-col">
|
||||
<Label className="">{t("verification_code")}</Label>
|
||||
<div className="flex items-center w-full">
|
||||
<div className="flex w-full items-center">
|
||||
<TextField
|
||||
containerClassName="w-full"
|
||||
className="h-8 rounded-xl"
|
||||
@@ -1217,7 +1217,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
{form.formState.errors.steps &&
|
||||
form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (
|
||||
<p className="mt-1 text-xs text-error">
|
||||
<p className="text-error mt-1 text-xs">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
@@ -1304,7 +1304,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
)}
|
||||
{!isCalAIAction(form.getValues(`steps.${step.stepNumber - 1}.action`)) && (
|
||||
<div className="p-3 mt-3 rounded-2xl border bg-muted border-muted">
|
||||
<div className="bg-muted border-muted mt-3 rounded-2xl border p-3">
|
||||
{isEmailSubjectNeeded && (
|
||||
<div className="mb-6">
|
||||
<div className="flex items-center">
|
||||
@@ -1337,14 +1337,14 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
/>
|
||||
{form.formState.errors.steps &&
|
||||
form.formState?.errors?.steps[step.stepNumber - 1]?.emailSubject && (
|
||||
<p className="mt-1 text-xs text-error">
|
||||
<p className="text-error mt-1 text-xs">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.emailSubject?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center pb-1 mb-2">
|
||||
<Label className="flex-none mb-0">
|
||||
<div className="mb-2 flex items-center pb-1">
|
||||
<Label className="mb-0 flex-none">
|
||||
{isEmailSubjectNeeded ? t("email_body") : t("text_message")}
|
||||
</Label>
|
||||
</div>
|
||||
@@ -1373,7 +1373,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
|
||||
{form.formState.errors.steps &&
|
||||
form.formState?.errors?.steps[step.stepNumber - 1]?.reminderBody && (
|
||||
<p className="mt-1 text-sm text-error">
|
||||
<p className="text-error mt-1 text-sm">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.reminderBody?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
@@ -1398,12 +1398,16 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{!props.readOnly && !isFormTrigger(trigger) && (
|
||||
<div className="mt-2 ml-1">
|
||||
{!props.readOnly && (
|
||||
<div className="ml-1 mt-2">
|
||||
<button type="button" onClick={() => setIsAdditionalInputsDialogOpen(true)}>
|
||||
<div className="flex gap-2 items-center ml-1 text-subtle">
|
||||
<Icon name="circle-help" className="w-3 h-3" />
|
||||
<p className="text-xs text-left">{t("using_booking_questions_as_variables")}</p>
|
||||
<div className="text-subtle ml-1 flex items-center gap-2">
|
||||
<Icon name="circle-help" className="h-3 w-3" />
|
||||
<p className="text-left text-xs">
|
||||
{isFormTrigger(trigger)
|
||||
? t("using_form_responses_as_variables")
|
||||
: t("using_booking_questions_as_variables")}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
@@ -1511,24 +1515,32 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
<Dialog open={isAdditionalInputsDialogOpen} onOpenChange={setIsAdditionalInputsDialogOpen}>
|
||||
<DialogContent enableOverflow type="creation" className="sm:max-w-[610px]">
|
||||
<div>
|
||||
<h1 className="w-full text-xl font-semibold">{t("how_booking_questions_as_variables")}</h1>
|
||||
<div className="mb-6 rounded-md bg-muted-3 sm:p-4">
|
||||
<p className="font-medium test-sm">{t("format")}</p>
|
||||
<ul className="mt-2 ml-5 list-disc text-emphasis">
|
||||
<h1 className="w-full text-xl font-semibold">
|
||||
{isFormTrigger(trigger)
|
||||
? t("how_form_responses_as_variables")
|
||||
: t("how_booking_questions_as_variables")}
|
||||
</h1>
|
||||
<div className="bg-muted-3 mb-6 rounded-md sm:p-4">
|
||||
<p className="test-sm font-medium">{t("format")}</p>
|
||||
<ul className="text-emphasis ml-5 mt-2 list-disc">
|
||||
<li>{t("uppercase_for_letters")}</li>
|
||||
<li>{t("replace_whitespaces_underscores")}</li>
|
||||
<li>{t("ignore_special_characters_booking_questions")}</li>
|
||||
<li>
|
||||
{isFormTrigger(trigger)
|
||||
? t("ignore_special_characters_form_responses")
|
||||
: t("ignore_special_characters_booking_questions")}
|
||||
</li>
|
||||
</ul>
|
||||
<div className="mt-4">
|
||||
<p className="w-full font-medium test-sm">{t("example_1")}</p>
|
||||
<div className="grid grid-cols-12 mt-2">
|
||||
<div className="col-span-5 test-sm text-default ltr:mr-2 rtl:ml-2">
|
||||
{t("booking_question_identifier")}
|
||||
<p className="test-sm w-full font-medium">{t("example_1")}</p>
|
||||
<div className="mt-2 grid grid-cols-12">
|
||||
<div className="test-sm text-default col-span-5 ltr:mr-2 rtl:ml-2">
|
||||
{isFormTrigger(trigger) ? t("form_field_identifier") : t("booking_question_identifier")}
|
||||
</div>
|
||||
<div className="col-span-7 test-sm text-emphasis">{t("company_size")}</div>
|
||||
<div className="col-span-5 w-full test-sm text-default">{t("variable")}</div>
|
||||
<div className="test-sm text-emphasis col-span-7">{t("company_size")}</div>
|
||||
<div className="test-sm text-default col-span-5 w-full">{t("variable")}</div>
|
||||
|
||||
<div className="col-span-7 break-words test-sm text-emphasis">
|
||||
<div className="test-sm text-emphasis col-span-7 break-words">
|
||||
{" "}
|
||||
{`{${t("company_size")
|
||||
.replace(/[^a-zA-Z0-9 ]/g, "")
|
||||
@@ -1539,14 +1551,14 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<p className="w-full font-medium test-sm">{t("example_2")}</p>
|
||||
<div className="grid grid-cols-12 mt-2">
|
||||
<div className="col-span-5 test-sm text-default ltr:mr-2 rtl:ml-2">
|
||||
{t("booking_question_identifier")}
|
||||
<p className="test-sm w-full font-medium">{t("example_2")}</p>
|
||||
<div className="mt-2 grid grid-cols-12">
|
||||
<div className="test-sm text-default col-span-5 ltr:mr-2 rtl:ml-2">
|
||||
{isFormTrigger(trigger) ? t("form_field_identifier") : t("booking_question_identifier")}
|
||||
</div>
|
||||
<div className="col-span-7 test-sm text-emphasis">{t("what_help_needed")}</div>
|
||||
<div className="col-span-5 test-sm text-default">{t("variable")}</div>
|
||||
<div className="col-span-7 break-words test-sm text-emphasis">
|
||||
<div className="test-sm text-emphasis col-span-7">{t("what_help_needed")}</div>
|
||||
<div className="test-sm text-default col-span-5">{t("variable")}</div>
|
||||
<div className="test-sm text-emphasis col-span-7 break-words">
|
||||
{" "}
|
||||
{`{${t("what_help_needed")
|
||||
.replace(/[^a-zA-Z0-9 ]/g, "")
|
||||
@@ -1620,17 +1632,17 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
<Dialog open={isUnsubscribeDialogOpen} onOpenChange={setIsUnsubscribeDialogOpen}>
|
||||
<DialogContent type="creation" title={t("unsubscribe_phone_number")}>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-default">{t("do_you_still_want_to_unsubscribe")}</p>
|
||||
<p className="text-default text-sm">{t("do_you_still_want_to_unsubscribe")}</p>
|
||||
{getActivePhoneNumbers(
|
||||
agentData?.outboundPhoneNumbers?.map((phone) => ({
|
||||
...phone,
|
||||
subscriptionStatus: phone.subscriptionStatus ?? undefined,
|
||||
}))
|
||||
).length > 0 && (
|
||||
<div className="p-3 rounded-lg bg-muted">
|
||||
<div className="flex gap-2 items-center">
|
||||
<Icon name="phone" className="w-4 h-4 text-emphasis" />
|
||||
<span className="text-sm font-medium text-emphasis">
|
||||
<div className="bg-muted rounded-lg p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="phone" className="text-emphasis h-4 w-4" />
|
||||
<span className="text-emphasis text-sm font-medium">
|
||||
{formatPhoneNumber(
|
||||
getActivePhoneNumbers(
|
||||
agentData?.outboundPhoneNumbers?.map((phone) => ({
|
||||
@@ -1643,7 +1655,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm text-subtle">{t("the_action_will_disconnect_phone_number")}</p>
|
||||
<p className="text-subtle text-sm">{t("the_action_will_disconnect_phone_number")}</p>
|
||||
</div>
|
||||
<DialogFooter showDivider>
|
||||
<Button type="button" color="secondary" onClick={() => setIsUnsubscribeDialogOpen(false)}>
|
||||
@@ -1678,7 +1690,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
<Dialog open={isDeleteStepDialogOpen} onOpenChange={setIsDeleteStepDialogOpen}>
|
||||
<DialogContent type="confirmation" title={t("delete_workflow_step")}>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-default">{t("are_you_sure_you_want_to_delete_workflow_step")}</p>
|
||||
<p className="text-default text-sm">{t("are_you_sure_you_want_to_delete_workflow_step")}</p>
|
||||
{(() => {
|
||||
const relevantPhoneNumbers =
|
||||
agentData?.outboundPhoneNumbers?.filter(
|
||||
@@ -1688,12 +1700,12 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
return (
|
||||
relevantPhoneNumbers.length > 0 && (
|
||||
<>
|
||||
<div className="p-3 rounded-lg bg-attention">
|
||||
<div className="flex gap-2 items-start">
|
||||
<div className="bg-attention rounded-lg p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<Icon name="info" className="text-attention mt-0.5 h-4 w-4" />
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium text-attention">{t("this_action_will_also")}</p>
|
||||
<ul className="space-y-1 text-sm list-disc list-inside text-attention">
|
||||
<p className="text-attention text-sm font-medium">{t("this_action_will_also")}</p>
|
||||
<ul className="text-attention list-inside list-disc space-y-1 text-sm">
|
||||
{relevantPhoneNumbers.some(
|
||||
(phone) => phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE
|
||||
) && <li>{t("cancel_your_phone_number_subscription")}</li>}
|
||||
@@ -1703,10 +1715,10 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
</div>
|
||||
{relevantPhoneNumbers.map((phone) => (
|
||||
<div key={phone.phoneNumber} className="p-3 rounded-lg bg-muted">
|
||||
<div className="flex gap-2 items-center">
|
||||
<Icon name="phone" className="w-4 h-4 text-emphasis" />
|
||||
<span className="text-sm font-medium text-emphasis">
|
||||
<div key={phone.phoneNumber} className="bg-muted rounded-lg p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="phone" className="text-emphasis h-4 w-4" />
|
||||
<span className="text-emphasis text-sm font-medium">
|
||||
{formatPhoneNumber(phone.phoneNumber)}
|
||||
</span>
|
||||
{phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE && (
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { EventStatus } from "ics";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import generateIcsString from "@calcom/emails/lib/generateIcsString";
|
||||
@@ -24,7 +23,10 @@ import { sendOrScheduleWorkflowEmails } from "./providers/emailProvider";
|
||||
import type { FormSubmissionData, WorkflowContextData } from "./reminderScheduler";
|
||||
import type { AttendeeInBookingInfo, BookingInfo, timeUnitLowerCase } from "./smsReminderManager";
|
||||
import type { VariablesType } from "./templates/customTemplate";
|
||||
import customTemplate from "./templates/customTemplate";
|
||||
import customTemplate, {
|
||||
transformBookingResponsesToVariableFormat,
|
||||
transformRoutingFormResponsesToVariableFormat,
|
||||
} from "./templates/customTemplate";
|
||||
import emailRatingTemplate from "./templates/emailRatingTemplate";
|
||||
import emailReminderTemplate from "./templates/emailReminderTemplate";
|
||||
|
||||
@@ -62,7 +64,12 @@ type SendEmailReminderParams = {
|
||||
subject: string;
|
||||
html: string;
|
||||
replyTo?: string;
|
||||
attachments?: any[];
|
||||
attachments?: {
|
||||
content: string;
|
||||
filename: string;
|
||||
contentType: string;
|
||||
disposition: string;
|
||||
}[];
|
||||
sender?: string | null;
|
||||
};
|
||||
sendTo: string[];
|
||||
@@ -159,7 +166,7 @@ const scheduleEmailReminderForEvt = async (args: scheduleEmailReminderArgs & { e
|
||||
attendeeName = attendeeToBeUsedInMail.name;
|
||||
timeZone = evt.organizer.timeZone;
|
||||
break;
|
||||
case WorkflowActions.EMAIL_ATTENDEE:
|
||||
case WorkflowActions.EMAIL_ATTENDEE: {
|
||||
// check if first attendee of sendTo is present in the attendees list, if not take the evt attendee
|
||||
const attendeeEmailToBeUsedInMailFromEvt = evt.attendees.find(
|
||||
(attendee) => attendee.email === sendTo[0]
|
||||
@@ -171,6 +178,7 @@ const scheduleEmailReminderForEvt = async (args: scheduleEmailReminderArgs & { e
|
||||
attendeeName = evt.organizer.name;
|
||||
timeZone = attendeeToBeUsedInMail.timeZone;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let emailContent = {
|
||||
@@ -199,7 +207,7 @@ const scheduleEmailReminderForEvt = async (args: scheduleEmailReminderArgs & { e
|
||||
timeZone: timeZone,
|
||||
location: evt.location,
|
||||
additionalNotes: evt.additionalNotes,
|
||||
responses: evt.responses,
|
||||
responses: transformBookingResponsesToVariableFormat(evt.responses),
|
||||
meetingUrl: bookingMetadataSchema.parse(evt.metadata || {})?.videoCallUrl,
|
||||
cancelLink: `${bookerUrl}/booking/${evt.uid}?cancel=true${
|
||||
recipientEmail ? `&cancelledBy=${encodeURIComponent(recipientEmail)}` : ""
|
||||
@@ -358,12 +366,16 @@ const scheduleEmailReminderForForm = async (
|
||||
|
||||
if (emailBody) {
|
||||
const timeFormat = getTimeFormatStringFromUserTimeFormat(formData.user.timeFormat);
|
||||
//todo: add variables
|
||||
const emailSubjectTemplate = customTemplate(emailSubject, {}, formData.user.locale, timeFormat);
|
||||
|
||||
const variables: VariablesType = {
|
||||
responses: transformRoutingFormResponsesToVariableFormat(formData.responses),
|
||||
};
|
||||
|
||||
const emailSubjectTemplate = customTemplate(emailSubject, variables, formData.user.locale, timeFormat);
|
||||
emailContent.emailSubject = emailSubjectTemplate.text;
|
||||
emailContent.emailBody = customTemplate(
|
||||
emailBody,
|
||||
{},
|
||||
variables,
|
||||
formData.user.locale,
|
||||
timeFormat,
|
||||
hideBranding
|
||||
|
||||
@@ -10,6 +10,7 @@ import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import type { TimeFormat } from "@calcom/lib/timeFormat";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
@@ -26,6 +27,7 @@ import type { ScheduleReminderArgs } from "./emailReminderManager";
|
||||
import { scheduleSmsOrFallbackEmail, sendSmsOrFallbackEmail } from "./messageDispatcher";
|
||||
import * as twilio from "./providers/twilioProvider";
|
||||
import type { FormSubmissionData } from "./reminderScheduler";
|
||||
import customTemplate, { transformRoutingFormResponsesToVariableFormat } from "./templates/customTemplate";
|
||||
import smsReminderTemplate from "./templates/smsReminderTemplate";
|
||||
|
||||
export enum timeUnitLowerCase {
|
||||
@@ -318,7 +320,18 @@ const scheduleSMSReminderForForm = async (
|
||||
) => {
|
||||
const { message, triggerEvent, reminderPhone, sender, userId, teamId, action, formData } = args;
|
||||
|
||||
const smsMessage = message;
|
||||
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(
|
||||
|
||||
@@ -1,10 +1,68 @@
|
||||
import { guessEventLocationType } from "@calcom/app-store/locations";
|
||||
import type { FORM_SUBMITTED_WEBHOOK_RESPONSES } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { APP_NAME } from "@calcom/lib/constants";
|
||||
import { TimeFormat } from "@calcom/lib/timeFormat";
|
||||
import type { CalEventResponses } from "@calcom/types/Calendar";
|
||||
|
||||
export type WorkflowVariableResponses = Record<
|
||||
string,
|
||||
{
|
||||
value:
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| string[]
|
||||
| Record<string, string>
|
||||
| { value: string; optionValue: string };
|
||||
}
|
||||
>;
|
||||
|
||||
export function transformBookingResponsesToVariableFormat(
|
||||
responses: CalEventResponses | null | undefined
|
||||
): WorkflowVariableResponses | null {
|
||||
if (!responses) return null;
|
||||
|
||||
const transformed: WorkflowVariableResponses = {};
|
||||
|
||||
for (const [key, response] of Object.entries(responses)) {
|
||||
if (response?.value !== undefined) {
|
||||
transformed[key] = {
|
||||
value: response.value,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return Object.keys(transformed).length > 0 ? transformed : null;
|
||||
}
|
||||
|
||||
export function transformRoutingFormResponsesToVariableFormat(
|
||||
responses: FORM_SUBMITTED_WEBHOOK_RESPONSES | null | undefined
|
||||
): WorkflowVariableResponses | null {
|
||||
if (!responses) return null;
|
||||
|
||||
const transformed: WorkflowVariableResponses = {};
|
||||
|
||||
for (const [key, response] of Object.entries(responses)) {
|
||||
if (response?.value !== undefined) {
|
||||
transformed[key] = {
|
||||
value: response.value,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return Object.keys(transformed).length > 0 ? transformed : null;
|
||||
}
|
||||
|
||||
export function formatIdentifierToVariable(key: string): string {
|
||||
return key
|
||||
.replace(/[^a-zA-Z0-9 ]/g, "")
|
||||
.trim()
|
||||
.replaceAll(" ", "_")
|
||||
.toUpperCase();
|
||||
}
|
||||
|
||||
export type VariablesType = {
|
||||
eventName?: string;
|
||||
organizerName?: string;
|
||||
@@ -17,7 +75,7 @@ export type VariablesType = {
|
||||
timeZone?: string;
|
||||
location?: string | null;
|
||||
additionalNotes?: string | null;
|
||||
responses?: CalEventResponses | null;
|
||||
responses?: WorkflowVariableResponses | null;
|
||||
meetingUrl?: string;
|
||||
cancelLink?: string;
|
||||
cancelReason?: string | null;
|
||||
@@ -42,12 +100,15 @@ const customTemplate = (
|
||||
timeFormat?: TimeFormat,
|
||||
isBrandingDisabled?: boolean
|
||||
) => {
|
||||
const translatedDate = new Intl.DateTimeFormat(locale, {
|
||||
weekday: "long",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
}).format(variables.eventDate?.add(dayjs().tz(variables.timeZone).utcOffset(), "minute").toDate());
|
||||
const eventDate = variables.eventDate;
|
||||
const translatedDate = eventDate
|
||||
? new Intl.DateTimeFormat(locale, {
|
||||
weekday: "long",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
}).format(eventDate.add(dayjs().tz(variables.timeZone).utcOffset(), "minute").toDate())
|
||||
: "";
|
||||
|
||||
let locationString = variables.location || "";
|
||||
|
||||
@@ -132,23 +193,21 @@ const customTemplate = (
|
||||
return;
|
||||
}
|
||||
|
||||
// handle custom variables from form/booking responses
|
||||
if (variables.responses) {
|
||||
Object.keys(variables.responses).forEach((customInput) => {
|
||||
const formatedToVariable = customInput
|
||||
.replace(/[^a-zA-Z0-9 ]/g, "")
|
||||
.trim()
|
||||
.replaceAll(" ", "_")
|
||||
.toUpperCase();
|
||||
const formatedToVariable = formatIdentifierToVariable(customInput);
|
||||
|
||||
if (
|
||||
variable === formatedToVariable &&
|
||||
variables.responses &&
|
||||
variables.responses[customInput as keyof typeof variables.responses].value
|
||||
) {
|
||||
dynamicText = dynamicText.replace(
|
||||
`{${variable}}`,
|
||||
variables.responses[customInput as keyof typeof variables.responses].value.toString()
|
||||
);
|
||||
if (variable === formatedToVariable && variables.responses) {
|
||||
const response = variables.responses[customInput];
|
||||
if (response?.value !== undefined) {
|
||||
const responseValue = response.value;
|
||||
const valueString = Array.isArray(responseValue)
|
||||
? responseValue.join(", ")
|
||||
: String(responseValue);
|
||||
|
||||
dynamicText = dynamicText.replace(`{${variable}}`, valueString);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ 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";
|
||||
import customTemplate, { transformBookingResponsesToVariableFormat } from "./templates/customTemplate";
|
||||
|
||||
export const bulkShortenLinks = async (links: string[]) => {
|
||||
if (!process.env.DUB_API_KEY) {
|
||||
@@ -74,7 +74,7 @@ export const getSMSMessageWithVariables = async (
|
||||
timeZone: timeZone,
|
||||
location: evt.location,
|
||||
additionalNotes: evt.additionalNotes,
|
||||
responses: evt.responses,
|
||||
responses: transformBookingResponsesToVariableFormat(evt.responses),
|
||||
meetingUrl,
|
||||
cancelLink,
|
||||
rescheduleLink,
|
||||
|
||||
@@ -17,6 +17,9 @@ import { v4 as uuidv4 } from "uuid";
|
||||
import { describe, expect, beforeAll, vi, beforeEach } from "vitest";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import tasker from "@calcom/features/tasker";
|
||||
import * as rateLimitModule from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import {
|
||||
BookingStatus,
|
||||
@@ -33,6 +36,7 @@ import {
|
||||
import { test } from "@calcom/web/test/fixtures/fixtures";
|
||||
|
||||
import { deleteWorkfowRemindersOfRemovedMember } from "../../../teams/lib/deleteWorkflowRemindersOfRemovedMember";
|
||||
import { scheduleAIPhoneCall } from "../reminders/aiPhoneCallManager";
|
||||
import { scheduleEmailReminder } from "../reminders/emailReminderManager";
|
||||
import * as emailProvider from "../reminders/providers/emailProvider";
|
||||
|
||||
@@ -261,7 +265,7 @@ vi.mock("@calcom/lib/constants", async () => {
|
||||
});
|
||||
|
||||
describe("deleteRemindersOfActiveOnIds", () => {
|
||||
test("should delete all reminders and tasks from removed event types", async ({}) => {
|
||||
test("should delete all reminders and tasks from removed event types", async () => {
|
||||
const organizer = getOrganizer({
|
||||
name: "Organizer",
|
||||
email: "organizer@example.com",
|
||||
@@ -326,7 +330,7 @@ describe("deleteRemindersOfActiveOnIds", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("should delete all reminders from removed event types (org workflow)", async ({}) => {
|
||||
test("should delete all reminders from removed event types (org workflow)", async () => {
|
||||
const org = await createOrganization({
|
||||
name: "Test Org",
|
||||
slug: "testorg",
|
||||
@@ -454,7 +458,7 @@ describe("deleteRemindersOfActiveOnIds", () => {
|
||||
describe("scheduleBookingReminders", () => {
|
||||
setupAndTeardown();
|
||||
|
||||
test("schedules workflow notifications with before event trigger and email to host action", async ({}) => {
|
||||
test("schedules workflow notifications with before event trigger and email to host action", async () => {
|
||||
// organizer is part of org and two teams
|
||||
const organizer = getOrganizer({
|
||||
name: "Organizer",
|
||||
@@ -547,7 +551,7 @@ describe("scheduleBookingReminders", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("schedules workflow notifications with after event trigger and email to host action", async ({}) => {
|
||||
test("schedules workflow notifications with after event trigger and email to host action", async () => {
|
||||
// organizer is part of org and two teams
|
||||
const organizer = getOrganizer({
|
||||
name: "Organizer",
|
||||
@@ -773,7 +777,7 @@ describe("scheduleBookingReminders", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("should not schedule reminders if date is already in the past", async ({}) => {
|
||||
test("should not schedule reminders if date is already in the past", async () => {
|
||||
const organizer = getOrganizer({
|
||||
name: "Organizer",
|
||||
email: "organizer@example.com",
|
||||
@@ -850,7 +854,7 @@ describe("scheduleBookingReminders", () => {
|
||||
});
|
||||
|
||||
describe("deleteWorkfowRemindersOfRemovedMember", () => {
|
||||
test("deletes all workflow reminders when member is removed from org", async ({}) => {
|
||||
test("deletes all workflow reminders when member is removed from org", async () => {
|
||||
const org = await createOrganization({
|
||||
name: "Test Org",
|
||||
slug: "testorg",
|
||||
@@ -926,7 +930,7 @@ describe("deleteWorkfowRemindersOfRemovedMember", () => {
|
||||
expect(tasks.length).toBe(0);
|
||||
});
|
||||
|
||||
test("deletes reminders if member is removed from an org team ", async ({}) => {
|
||||
test("deletes reminders if member is removed from an org team ", async () => {
|
||||
const org = await createOrganization({
|
||||
name: "Test Org",
|
||||
slug: "testorg",
|
||||
@@ -1100,3 +1104,235 @@ describe("Workflow SMTP Emails Feature Flag", () => {
|
||||
expect(emailProvider.sendOrScheduleWorkflowEmails).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Routing Form Variables", () => {
|
||||
beforeEach(() => {
|
||||
// Reset global test storage
|
||||
globalThis.testEmails = [];
|
||||
globalThis.testSMS = [];
|
||||
});
|
||||
|
||||
test("should substitute routing form variables in email subject and body", async () => {
|
||||
const mockFormData = {
|
||||
responses: {
|
||||
"contact person": {
|
||||
value: "Jane Smith",
|
||||
response: "Jane Smith",
|
||||
},
|
||||
"company name": {
|
||||
value: "Acme Solutions",
|
||||
response: "Acme Solutions",
|
||||
},
|
||||
department: {
|
||||
value: "Engineering",
|
||||
response: "Engineering",
|
||||
},
|
||||
},
|
||||
routedEventTypeId: null,
|
||||
user: {
|
||||
email: "user@test.com",
|
||||
timeFormat: 12,
|
||||
locale: "en",
|
||||
},
|
||||
};
|
||||
|
||||
const emailArgs = {
|
||||
emailBody: "Dear {CONTACT_PERSON} from {COMPANY_NAME} ({DEPARTMENT}), thank you for your submission.",
|
||||
emailSubject: "Welcome {COMPANY_NAME} - {DEPARTMENT} Team",
|
||||
triggerEvent: WorkflowTriggerEvents.FORM_SUBMITTED,
|
||||
sendTo: ["recipient@test.com"],
|
||||
action: WorkflowActions.EMAIL_HOST,
|
||||
verifiedAt: new Date(),
|
||||
formData: mockFormData,
|
||||
};
|
||||
|
||||
await scheduleEmailReminder(emailArgs);
|
||||
|
||||
// Check that email was sent with processed variables
|
||||
expect(globalThis.testEmails).toHaveLength(1);
|
||||
const sentEmail = globalThis.testEmails[0];
|
||||
|
||||
expect(sentEmail.subject).toBe("Welcome Acme Solutions - Engineering Team");
|
||||
expect(sentEmail.html).toContain("Dear Jane Smith from Acme Solutions (Engineering)");
|
||||
});
|
||||
|
||||
test("should handle array values in routing form variables", async () => {
|
||||
// Using actual structure - for multi-select fields, value is array of labels, response is array of objects
|
||||
const mockFormData = {
|
||||
responses: {
|
||||
"selected services": {
|
||||
value: ["web development", "mobile app", "consulting"],
|
||||
response: [
|
||||
{ label: "web development", id: "web-dev" },
|
||||
{ label: "mobile app", id: "mobile" },
|
||||
{ label: "consulting", id: "consulting" },
|
||||
],
|
||||
},
|
||||
"company name": {
|
||||
value: "Digital Corp",
|
||||
response: "Digital Corp",
|
||||
},
|
||||
},
|
||||
routedEventTypeId: null,
|
||||
user: {
|
||||
email: "user@test.com",
|
||||
timeFormat: 12,
|
||||
locale: "en",
|
||||
},
|
||||
};
|
||||
|
||||
const emailArgs = {
|
||||
emailBody: "Hello {COMPANY_NAME}, you selected: {SELECTED_SERVICES}",
|
||||
emailSubject: "Services for {COMPANY_NAME}",
|
||||
triggerEvent: WorkflowTriggerEvents.FORM_SUBMITTED,
|
||||
sendTo: ["test@example.com"],
|
||||
action: WorkflowActions.EMAIL_HOST,
|
||||
verifiedAt: new Date(),
|
||||
formData: mockFormData,
|
||||
};
|
||||
|
||||
await scheduleEmailReminder(emailArgs);
|
||||
|
||||
expect(globalThis.testEmails).toHaveLength(1);
|
||||
const sentEmail = globalThis.testEmails[0];
|
||||
|
||||
expect(sentEmail.subject).toBe("Services for Digital Corp");
|
||||
expect(sentEmail.html).toContain(
|
||||
"Hello Digital Corp, you selected: web development, mobile app, consulting"
|
||||
);
|
||||
});
|
||||
|
||||
test("should handle field names with special characters in routing forms", async () => {
|
||||
const mockFormData = {
|
||||
responses: {
|
||||
"company-name!@#": {
|
||||
value: "Special Characters LLC",
|
||||
response: "Special Characters LLC",
|
||||
},
|
||||
"phone number (primary)": {
|
||||
value: "+1-555-0123",
|
||||
response: "+1-555-0123",
|
||||
},
|
||||
},
|
||||
routedEventTypeId: null,
|
||||
user: {
|
||||
email: "user@test.com",
|
||||
timeFormat: 12,
|
||||
locale: "en",
|
||||
},
|
||||
};
|
||||
|
||||
const emailArgs = {
|
||||
emailBody: "Company: {COMPANYNAME}, Phone: {PHONE_NUMBER_PRIMARY}",
|
||||
emailSubject: "Contact info for {COMPANYNAME}",
|
||||
triggerEvent: WorkflowTriggerEvents.FORM_SUBMITTED,
|
||||
sendTo: ["test@example.com"],
|
||||
action: WorkflowActions.EMAIL_HOST,
|
||||
verifiedAt: new Date(),
|
||||
formData: mockFormData,
|
||||
};
|
||||
|
||||
await scheduleEmailReminder(emailArgs);
|
||||
|
||||
expect(globalThis.testEmails).toHaveLength(1);
|
||||
const sentEmail = globalThis.testEmails[0];
|
||||
|
||||
expect(sentEmail.subject).toBe("Contact info for Special Characters LLC");
|
||||
expect(sentEmail.html).toContain("Company: Special Characters LLC, Phone: +1-555-0123");
|
||||
});
|
||||
|
||||
test("should pass routing form responses to AI phone call workflows", async () => {
|
||||
// Mock the feature flag
|
||||
const mockCheckFeature = vi
|
||||
.spyOn(FeaturesRepository.prototype, "checkIfFeatureIsEnabledGlobally")
|
||||
.mockResolvedValue(true);
|
||||
|
||||
// Mock rate limiting
|
||||
const mockRateLimit = vi
|
||||
.spyOn(rateLimitModule, "checkRateLimitAndThrowError")
|
||||
.mockResolvedValue(undefined);
|
||||
|
||||
// Mock the AI agent setup
|
||||
await prismock.agent.create({
|
||||
data: {
|
||||
id: "test-agent-id",
|
||||
providerAgentId: "provider-123",
|
||||
outboundPhoneNumbers: {
|
||||
create: {
|
||||
phoneNumber: "+1234567890",
|
||||
subscriptionStatus: "ACTIVE",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await prismock.workflowStep.create({
|
||||
data: {
|
||||
id: 999,
|
||||
stepNumber: 1,
|
||||
action: WorkflowActions.CAL_AI_PHONE_CALL,
|
||||
workflowId: 1,
|
||||
agentId: "test-agent-id",
|
||||
verifiedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
const mockFormData = {
|
||||
responses: {
|
||||
"customer name": {
|
||||
value: "John Doe",
|
||||
response: "John Doe",
|
||||
},
|
||||
"phone preference": {
|
||||
value: "mobile",
|
||||
response: { label: "mobile", id: "mobile" },
|
||||
},
|
||||
priority: {
|
||||
value: "high",
|
||||
response: { label: "high", id: "high" },
|
||||
},
|
||||
},
|
||||
routedEventTypeId: 123,
|
||||
user: {
|
||||
email: "user@test.com",
|
||||
timeFormat: 12,
|
||||
locale: "en",
|
||||
},
|
||||
};
|
||||
|
||||
const aiPhoneArgs = {
|
||||
submittedPhoneNumber: "+1-555-9999",
|
||||
triggerEvent: WorkflowTriggerEvents.FORM_SUBMITTED,
|
||||
timeSpan: { time: null, timeUnit: null },
|
||||
workflowStepId: 999,
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
verifiedAt: new Date(),
|
||||
formData: mockFormData,
|
||||
routedEventTypeId: 123,
|
||||
};
|
||||
|
||||
const mockTaskerCreate = vi.spyOn(tasker, "create").mockResolvedValue("task-id");
|
||||
|
||||
await scheduleAIPhoneCall(aiPhoneArgs);
|
||||
|
||||
// Verify that the task was created with form responses
|
||||
expect(mockTaskerCreate).toHaveBeenCalled();
|
||||
expect(mockTaskerCreate).toHaveBeenCalledWith(
|
||||
"executeAIPhoneCall",
|
||||
expect.any(Object),
|
||||
expect.any(Object)
|
||||
);
|
||||
const taskData = mockTaskerCreate.mock.calls[0][1] as {
|
||||
responses?: typeof mockFormData.responses;
|
||||
routedEventTypeId?: number;
|
||||
};
|
||||
expect(taskData.responses).toEqual(mockFormData.responses);
|
||||
expect(taskData.routedEventTypeId).toBe(123);
|
||||
|
||||
// Clean up
|
||||
mockTaskerCreate.mockRestore();
|
||||
mockCheckFeature.mockRestore();
|
||||
mockRateLimit.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import dayjs from "@calcom/dayjs";
|
||||
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
|
||||
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
|
||||
import { handleInsufficientCredits } from "@calcom/features/ee/billing/helpers/handleInsufficientCredits";
|
||||
import { formatIdentifierToVariable } from "@calcom/features/ee/workflows/lib/reminders/templates/customTemplate";
|
||||
import { WorkflowReminderRepository } from "@calcom/features/ee/workflows/lib/repository/workflowReminder";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import {
|
||||
@@ -51,6 +52,13 @@ function getVariablesFromFormResponse({
|
||||
ATTENDEE_EMAIL: submittedEmail || "",
|
||||
NUMBER_TO_CALL: numberToCall,
|
||||
eventTypeId: eventTypeId?.toString() || "",
|
||||
// Include any custom form responses
|
||||
...Object.fromEntries(
|
||||
Object.entries(responses || {}).map(([key, value]) => [
|
||||
formatIdentifierToVariable(key),
|
||||
value.value?.toString() || "",
|
||||
])
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -97,11 +105,7 @@ function getVariablesFromBooking(booking: BookingWithRelations, numberToCall: st
|
||||
// Include any custom form responses
|
||||
...Object.fromEntries(
|
||||
Object.entries(responses || {}).map(([key, value]) => [
|
||||
key
|
||||
.replace(/[^a-zA-Z0-9 ]/g, "")
|
||||
.trim()
|
||||
.replaceAll(" ", "_")
|
||||
.toUpperCase(),
|
||||
formatIdentifierToVariable(key),
|
||||
value.value?.toString() || "",
|
||||
])
|
||||
),
|
||||
@@ -192,9 +196,9 @@ export async function executeAIPhoneCall(payload: string) {
|
||||
|
||||
// form triggers don't have a booking
|
||||
const booking = workflowReminder.booking as BookingWithRelations | null;
|
||||
const responses = data.responses;
|
||||
const routingFormResponses = data.responses;
|
||||
|
||||
if (!booking && !responses) {
|
||||
if (!booking && !routingFormResponses) {
|
||||
log.warn(`No form responses or booking found for workflow reminder ${data.workflowReminderId}`);
|
||||
throw new Error("No booking, response, or form responses found");
|
||||
}
|
||||
@@ -214,7 +218,7 @@ export async function executeAIPhoneCall(payload: string) {
|
||||
|
||||
// Prefer response variables if present, else fall back to booking
|
||||
let dynamicVariables: VariablesType | undefined;
|
||||
if (responses) {
|
||||
if (routingFormResponses) {
|
||||
const workflowStep = workflowReminder.workflowStep;
|
||||
const eventTypeId =
|
||||
data.routedEventTypeId ??
|
||||
@@ -228,7 +232,7 @@ export async function executeAIPhoneCall(payload: string) {
|
||||
return;
|
||||
}
|
||||
dynamicVariables = getVariablesFromFormResponse({
|
||||
responses,
|
||||
responses: routingFormResponses,
|
||||
eventTypeId,
|
||||
numberToCall,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user