import type { WorkflowStep } from "@prisma/client"; import type { Dispatch, SetStateAction } from "react"; import { useRef, useState, useEffect } from "react"; import type { UseFormReturn } from "react-hook-form"; import { Controller } from "react-hook-form"; import "react-phone-number-input/style.css"; import { classNames } from "@calcom/lib"; import { SENDER_ID } from "@calcom/lib/constants"; import { SENDER_NAME } from "@calcom/lib/constants"; import { useLocale } from "@calcom/lib/hooks/useLocale"; import { HttpError } from "@calcom/lib/http-error"; import { WorkflowTemplates, TimeUnit, WorkflowActions } from "@calcom/prisma/enums"; import { WorkflowTriggerEvents } from "@calcom/prisma/enums"; import { trpc } from "@calcom/trpc/react"; import { Badge, Button, Checkbox, Dialog, DialogClose, DialogContent, Dropdown, DropdownMenuContent, DropdownMenuItem, DropdownItem, DropdownMenuTrigger, EmailField, Label, PhoneInput, Select, showToast, TextArea, TextField, Editor, AddVariablesDropdown, Input, } from "@calcom/ui"; import { ArrowDown, MoreHorizontal, Trash2, HelpCircle, Info } from "@calcom/ui/components/icon"; import { isAttendeeAction, isSMSAction } from "../lib/actionHelperFunctions"; import { DYNAMIC_TEXT_VARIABLES } from "../lib/constants"; import { getWorkflowTemplateOptions, getWorkflowTriggerOptions } from "../lib/getOptions"; import emailReminderTemplate from "../lib/reminders/templates/emailReminderTemplate"; import smsReminderTemplate from "../lib/reminders/templates/smsReminderTemplate"; import type { FormValues } from "../pages/workflow"; import { TimeTimeUnitInput } from "./TimeTimeUnitInput"; type WorkflowStepProps = { step?: WorkflowStep; form: UseFormReturn; reload?: boolean; setReload?: Dispatch>; teamId?: number; }; export default function WorkflowStepContainer(props: WorkflowStepProps) { const { t } = useLocale(); const utils = trpc.useContext(); const { step, form, reload, setReload, teamId } = props; const { data: _verifiedNumbers } = trpc.viewer.workflows.getVerifiedNumbers.useQuery( { teamId }, { enabled: !!teamId } ); const verifiedNumbers = _verifiedNumbers?.map((number) => number.phoneNumber) || []; const [isAdditionalInputsDialogOpen, setIsAdditionalInputsDialogOpen] = useState(false); const [verificationCode, setVerificationCode] = useState(""); const [isPhoneNumberNeeded, setIsPhoneNumberNeeded] = useState( step?.action === WorkflowActions.SMS_NUMBER ? true : false ); const [updateTemplate, setUpdateTemplate] = useState(false); const [firstRender, setFirstRender] = useState(true); const [isSenderIdNeeded, setIsSenderIdNeeded] = useState( step?.action === WorkflowActions.SMS_NUMBER || step?.action === WorkflowActions.SMS_ATTENDEE ? true : false ); useEffect(() => { setNumberVerified( !!step && !!verifiedNumbers.find((number) => number === form.getValues(`steps.${step.stepNumber - 1}.sendTo`)) ); }, [verifiedNumbers.length]); const [isEmailAddressNeeded, setIsEmailAddressNeeded] = useState( step?.action === WorkflowActions.EMAIL_ADDRESS ? true : false ); const [isEmailSubjectNeeded, setIsEmailSubjectNeeded] = useState( step?.action === WorkflowActions.EMAIL_ATTENDEE || step?.action === WorkflowActions.EMAIL_HOST || step?.action === WorkflowActions.EMAIL_ADDRESS ? true : false ); const [showTimeSection, setShowTimeSection] = useState( form.getValues("trigger") === WorkflowTriggerEvents.BEFORE_EVENT || form.getValues("trigger") === WorkflowTriggerEvents.AFTER_EVENT ); const [showTimeSectionAfter, setShowTimeSectionAfter] = useState( form.getValues("trigger") === WorkflowTriggerEvents.AFTER_EVENT ); const { data: actionOptions } = trpc.viewer.workflows.getWorkflowActionOptions.useQuery(); const triggerOptions = getWorkflowTriggerOptions(t); const templateOptions = getWorkflowTemplateOptions(t); if (step && form.getValues(`steps.${step.stepNumber - 1}.template`) === WorkflowTemplates.REMINDER) { if (!form.getValues(`steps.${step.stepNumber - 1}.reminderBody`)) { if (isSMSAction(form.getValues(`steps.${step.stepNumber - 1}.action`))) { const smsBody = smsReminderTemplate(true, form.getValues(`steps.${step.stepNumber - 1}.action`)); form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, smsBody); } else { const reminderBodyTemplate = emailReminderTemplate( true, form.getValues(`steps.${step.stepNumber - 1}.action`) ).emailBody; form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, reminderBodyTemplate); } } if (!form.getValues(`steps.${step.stepNumber - 1}.emailSubject`)) { const subjectTemplate = emailReminderTemplate( true, form.getValues(`steps.${step.stepNumber - 1}.action`) ).emailSubject; form.setValue(`steps.${step.stepNumber - 1}.emailSubject`, subjectTemplate); } } const { ref: emailSubjectFormRef, ...restEmailSubjectForm } = step ? form.register(`steps.${step.stepNumber - 1}.emailSubject`) : { ref: null, name: "" }; const { ref: reminderBodyFormRef, ...restReminderBodyForm } = step ? form.register(`steps.${step.stepNumber - 1}.reminderBody`) : { ref: null, name: "" }; const refEmailSubject = useRef(null); const refReminderBody = useRef(null); const [numberVerified, setNumberVerified] = useState( step && !!verifiedNumbers.find((number) => number === form.getValues(`steps.${step.stepNumber - 1}.sendTo`)) ); const addVariableBody = (variable: string) => { if (step) { const currentMessageBody = refReminderBody?.current?.value || ""; const cursorPosition = refReminderBody?.current?.selectionStart || currentMessageBody.length; const messageWithAddedVariable = `${currentMessageBody.substring(0, cursorPosition)}{${variable .toUpperCase() .replace(/ /g, "_")}}${currentMessageBody.substring(cursorPosition)}`; form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, messageWithAddedVariable); } }; const addVariableEmailSubject = (variable: string) => { if (step) { const currentEmailSubject = refEmailSubject?.current?.value || ""; const cursorPosition = refEmailSubject?.current?.selectionStart || currentEmailSubject.length; const subjectWithAddedVariable = `${currentEmailSubject.substring(0, cursorPosition)}{${variable .toUpperCase() .replace(/ /g, "_")}}${currentEmailSubject.substring(cursorPosition)}`; form.setValue(`steps.${step.stepNumber - 1}.emailSubject`, subjectWithAddedVariable); } }; const sendVerificationCodeMutation = trpc.viewer.workflows.sendVerificationCode.useMutation({ onSuccess: async () => { showToast(t("verification_code_sent"), "success"); }, onError: async (error) => { showToast(error.message, "error"); }, }); const verifyPhoneNumberMutation = trpc.viewer.workflows.verifyPhoneNumber.useMutation({ onSuccess: async (isVerified) => { showToast(isVerified ? t("verified_successfully") : t("wrong_code"), "success"); setNumberVerified(isVerified); utils.viewer.workflows.getVerifiedNumbers.invalidate(); }, onError: (err) => { if (err instanceof HttpError) { const message = `${err.statusCode}: ${err.message}`; showToast(message, "error"); setNumberVerified(false); } }, }); /* const testActionMutation = trpc.viewer.workflows.testAction.useMutation({ onSuccess: async () => { showToast(t("notification_sent"), "success"); }, onError: (err) => { let message = t("unexpected_error_try_again"); if (err instanceof TRPCClientError) { if (err.message === "rate-limit-exceeded") { message = t("rate_limit_exceeded"); } else { message = err.message; } } if (err instanceof HttpError) { message = `${err.statusCode}: ${err.message}`; } showToast(message, "error"); }, }); */ //trigger if (!step) { const trigger = form.getValues("trigger"); const triggerString = t(`${trigger.toLowerCase()}_trigger`); const selectedTrigger = { label: triggerString.charAt(0).toUpperCase() + triggerString.slice(1), value: trigger, }; return ( <>
1
{t("trigger")}
{t("when_something_happens")}
{ return ( { if (val) { const oldValue = form.getValues(`steps.${step.stepNumber - 1}.action`); if (isSMSAction(val.value)) { setIsSenderIdNeeded(true); setIsEmailAddressNeeded(false); setIsPhoneNumberNeeded(val.value === WorkflowActions.SMS_NUMBER); setNumberVerified(false); // email action changes to sms action if (!isSMSAction(oldValue)) { form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, ""); form.setValue(`steps.${step.stepNumber - 1}.sender`, SENDER_ID); } setIsEmailSubjectNeeded(false); } else { setIsPhoneNumberNeeded(false); setIsSenderIdNeeded(false); setIsEmailAddressNeeded(val.value === WorkflowActions.EMAIL_ADDRESS); setIsEmailSubjectNeeded(true); } if ( form.getValues(`steps.${step.stepNumber - 1}.template`) === WorkflowTemplates.REMINDER ) { if (isSMSAction(val.value) === isSMSAction(oldValue)) { if (isAttendeeAction(oldValue) !== isAttendeeAction(val.value)) { const currentReminderBody = form.getValues(`steps.${step.stepNumber - 1}.reminderBody`) || ""; const newReminderBody = currentReminderBody .replaceAll("{ORGANIZER}", "{PLACEHOLDER}") .replaceAll("{ATTENDEE}", "{ORGANIZER}") .replaceAll("{PLACEHOLDER}", "{ATTENDEE}"); form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, newReminderBody); if (!isSMSAction(val.value)) { const currentEmailSubject = form.getValues(`steps.${step.stepNumber - 1}.emailSubject`) || ""; const newEmailSubject = isAttendeeAction(val.value) ? currentEmailSubject.replace("{ORGANIZER}", "{ATTENDEE}") : currentEmailSubject.replace("{ATTENDEE}", "{ORGANIZER}"); form.setValue( `steps.${step.stepNumber - 1}.emailSubject`, newEmailSubject || "" ); } } } else { if (isSMSAction(val.value)) { form.setValue( `steps.${step.stepNumber - 1}.reminderBody`, smsReminderTemplate(true, val.value) ); } else { const emailReminderBody = emailReminderTemplate(true, val.value); form.setValue( `steps.${step.stepNumber - 1}.reminderBody`, emailReminderBody.emailBody ); form.setValue( `steps.${step.stepNumber - 1}.emailSubject`, emailReminderBody.emailSubject ); } } } form.unregister(`steps.${step.stepNumber - 1}.sendTo`); form.clearErrors(`steps.${step.stepNumber - 1}.sendTo`); form.setValue(`steps.${step.stepNumber - 1}.action`, val.value); setUpdateTemplate(!updateTemplate); } }} defaultValue={selectedAction} options={actionOptions} isOptionDisabled={(option: { label: string; value: WorkflowActions; needsUpgrade: boolean; }) => option.needsUpgrade} /> ); }} />
{isPhoneNumberNeeded && (
( { const isAlreadyVerified = !!verifiedNumbers ?.concat([]) .find((number) => number.replace(/\s/g, "") === val?.replace(/\s/g, "")); setNumberVerified(isAlreadyVerified); onChange(val); }} /> )} />
{form.formState.errors.steps && form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (

{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}

)} {numberVerified ? (
{t("number_verified")}
) : ( <>
{ setVerificationCode(e.target.value); }} required />
{form.formState.errors.steps && form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (

{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}

)} )}
)}
{isSenderIdNeeded ? ( <>
{form.formState.errors.steps && form.formState?.errors?.steps[step.stepNumber - 1]?.sender && (

{t("sender_id_error_message")}

)} ) : ( <>
)}
{form.getValues(`steps.${step.stepNumber - 1}.action`) === WorkflowActions.SMS_ATTENDEE && (
( form.setValue(`steps.${step.stepNumber - 1}.numberRequired`, e.target.checked) } /> )} />
)} {isEmailAddressNeeded && (
)}
{ return (