refactor: Move trpc-dependent components from features to web [1] (#25859)

* refactor: migrate UnconfirmedBookingBadge from features to apps/web

Move UnconfirmedBookingBadge.tsx from packages/features/bookings/ to
apps/web/modules/bookings/components/ as part of the architectural
refactor to remove trpc client imports from the features layer.

Also removes unused preserveBookingsQueryParams function from Navigation.tsx.

Co-Authored-By: [email protected] <[email protected]>

* refactor: move shell navigation and badges to apps/web

Move shell navigation components and trpc-using badges from
packages/features to apps/web/modules to fix circular dependency:

- Move navigation folder to apps/web/modules/shell/navigation/
- Move TeamInviteBadge.tsx to apps/web/modules/shell/
- Create Shell wrapper in apps/web that provides MobileNavigationContainer
- Update all Shell imports in apps/web to use the new wrapper
- Remove MobileNavigationContainer default from features Shell.tsx
- Fix pre-existing lint warnings in touched files

This establishes the pattern for migrating React components that use
trpc hooks from the features layer to the web app layer, ensuring
proper dependency direction: apps/web imports from packages/features,
never the reverse.

Co-Authored-By: [email protected] <[email protected]>

* fix: move SideBar.tsx to apps/web to fix build error

SideBar.tsx was importing Navigation from the moved navigation folder,
causing a build error. Moving SideBar.tsx to apps/web and updating the
features Shell to not have a default SidebarContainer fixes this.

The web Shell wrapper now provides both the default SidebarContainer
and MobileNavigationContainer, maintaining the injection pattern.

Co-Authored-By: [email protected] <[email protected]>

* revert

* revert

* revert

* wip

* wip

* wip

* wip

* wip

* wip

* not used anywhere

* wip

* wip

* wip

* wip

* fix

* fix

* wip

* wip

* wip

* wip

* wip

* fix

* fix

* fix

* fix

* migrate

* migrate admin-adpi

* wip

* feat: migrate organization settings components from packages/features to apps/web/modules

- Migrate profile.tsx, appearance.tsx, general.tsx, privacy.tsx, guest-notifications.tsx, delegationCredential.tsx, other-team-members-view.tsx, other-team-profile-view.tsx
- Migrate attributes directory (AttributesForm.tsx, DeleteAttributeModal.tsx, ListSkeleton.tsx, attributes-create-view.tsx, attributes-edit-view.tsx, attributes-list-view.tsx)
- Migrate admin directory (AdminOrgEditPage.tsx, AdminOrgPage.tsx, WorkspacePlatformPage.tsx)
- Update all page imports to use new paths from ~/settings/organizations/
- Update relative imports in migrated files to use @calcom/features paths
- Fix lint warnings in migrated files

Co-Authored-By: [email protected] <[email protected]>

* fix: update test import path after migration

Co-Authored-By: [email protected] <[email protected]>

* fix: remove unnecessary test-setup import (already in vitest config)

Co-Authored-By: [email protected] <[email protected]>

* wip

* refactor: delete original files after migration to apps/web/modules

Co-Authored-By: [email protected] <[email protected]>

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* fix

* fix

* fix

* fix

* wip

* refactor more

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* mv

* update import paths

* wip

* wip

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* mv

* mv

* mv

* fix

* wip

* wip

* fix

* fix

* fix

* fix: make test mocks resilient to vi.resetAllMocks()

Co-Authored-By: [email protected] <[email protected]>

* fix: fix AttributeForm test failures

Co-Authored-By: [email protected] <[email protected]>

* fix

* fix

* refactor: move ee files to apps/web/modules/ee/ folder

- Move teams, workflows, and organizations folders to apps/web/modules/ee/
- Add LICENSE file to apps/web/modules/ee/
- Update all import paths from ~/teams/ to ~/ee/teams/
- Update all import paths from ~/settings/organizations/ to ~/ee/organizations/
- Remove duplicate MemberInvitationModal copy.tsx file

Co-Authored-By: [email protected] <[email protected]>

* fix: move useHasPaidPlan and dependent files to apps/web/modules

- Move useHasPaidPlan.ts from packages/features/billing/hooks to apps/web/modules/billing/hooks
- Move intercom files from packages/features/ee/support to apps/web/modules/ee/support
- Move ContactMenuItem.tsx and dependencies (freshchat, helpscout, zendesk) to apps/web/modules/ee/support
- Move ViewRecordingsDialog.tsx and RecordingListSkeleton to apps/web/modules/ee/video
- Move CalVideoSettings.tsx to apps/web/modules/eventtypes/components/locations
- Move CreateOrEditOutOfOfficeModal.tsx to apps/web/modules/settings/outOfOffice
- Refactor UpgradeTeamsBadge to accept props and create wrapper in apps/web/modules/billing
- Update all callers to use new file locations
- Add eslint-disable comments for pre-existing lint warnings

This fixes the tRPC server build failure caused by circular dependency where
the server build was traversing into packages/features and pulling in React
hooks that depend on @calcom/trpc/react types.

Co-Authored-By: [email protected] <[email protected]>

* fix: correct UpgradeTeamsBadge import path to use package export

Co-Authored-By: [email protected] <[email protected]>

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix: pass plan state through SelectProps to UpgradeTeamsBadge

- Add upgradeTeamsBadgeProps field to ExtendedOption type in Select component
- Update OptionComponent to spread upgradeTeamsBadgeProps to UpgradeTeamsBadge
- Update getOptions.ts to accept PlanState object and include upgradeTeamsBadgeProps
- Update WorkflowStepContainer.tsx to pass planState to getWorkflowTriggerOptions/getWorkflowTemplateOptions
- Update WorkflowDetailsPage.tsx to pass upgradeTeamsBadgeProps in transformed action options
- Update AddActionDialog.tsx interface and mapping to include upgradeTeamsBadgeProps
- Add eslint-disable comments for pre-existing React Hook dependency warnings

This fixes the UpgradeTeamsBadge refactoring issue where the badge was always showing
'upgrade' text instead of the correct text based on plan state (trial_mode, inactive_team_plan, etc.)

Co-Authored-By: [email protected] <[email protected]>

* fix: update import paths to use /ee/ folder for workflows and organizations

Co-Authored-By: [email protected] <[email protected]>

* fix: update workflow component imports to use /ee/ folder

Co-Authored-By: [email protected] <[email protected]>

* fix: add missing types.ts for LocationInput.tsx

Co-Authored-By: [email protected] <[email protected]>

* fix: extract BookingRedirectForm type to shared location

Co-Authored-By: [email protected] <[email protected]>

* fix

* wip

* wip

* fix: update BookingRedirectForm import to use local types file

Co-Authored-By: [email protected] <[email protected]>

* wip

* fix

* fix

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2025-12-23 12:22:26 -03:00
1 parent 7847177e8b
commit 8afe87ff75
374 files changed
+1213 -1417

No files matched your search

@@ -0,0 +1,284 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { isValidPhoneNumber } from "libphonenumber-js/max";
import type { Dispatch, SetStateAction } from "react";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import PhoneInput from "@calcom/features/components/phone-input";
import { WORKFLOW_ACTIONS } from "@calcom/features/ee/workflows/lib/constants";
import { onlyLettersNumbersSpaces } from "@calcom/features/ee/workflows/lib/schema";
import { SENDER_ID, SENDER_NAME } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { WorkflowActions } from "@calcom/prisma/enums";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter, DialogClose } from "@calcom/ui/components/dialog";
import { EmailField } from "@calcom/ui/components/form";
import { Select } from "@calcom/ui/components/form";
import { CheckboxField } from "@calcom/ui/components/form";
import { Form } from "@calcom/ui/components/form";
import { Label } from "@calcom/ui/components/form";
import { Input } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { Tooltip } from "@calcom/ui/components/tooltip";
interface IAddActionDialog {
isOpenDialog: boolean;
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
addAction: (
action: WorkflowActions,
sendTo?: string,
numberRequired?: boolean,
senderId?: string,
senderName?: string
) => void;
actionOptions: {
label: string;
value: WorkflowActions;
needsCredits: boolean;
creditsTeamId?: number;
isOrganization?: boolean;
needsTeamsUpgrade?: boolean;
upgradeTeamsBadgeProps?: {
hasPaidPlan?: boolean;
hasActiveTeamPlan?: boolean;
isTrial?: boolean;
};
}[];
}
interface ISelectActionOption {
label: string;
value: WorkflowActions;
}
type AddActionFormValues = {
action: WorkflowActions;
sendTo?: string;
numberRequired?: boolean;
senderId?: string;
senderName?: string;
};
export const AddActionDialog = (props: IAddActionDialog) => {
const { t } = useLocale();
const { isOpenDialog, setIsOpenDialog, addAction, actionOptions } = props;
const [isPhoneNumberNeeded, setIsPhoneNumberNeeded] = useState(false);
const [isSenderIdNeeded, setIsSenderIdNeeded] = useState(false);
const [isEmailAddressNeeded, setIsEmailAddressNeeded] = useState(false);
const formSchema = z.object({
action: z.enum(WORKFLOW_ACTIONS),
sendTo: z
.string()
.refine((val) => isValidPhoneNumber(val) || val.includes("@"))
.optional(),
numberRequired: z.boolean().optional(),
senderId: z
.string()
.refine((val) => onlyLettersNumbersSpaces(val))
.nullable(),
senderName: z.string().nullable(),
});
const form = useForm<AddActionFormValues>({
mode: "onSubmit",
defaultValues: {
action: WorkflowActions.EMAIL_HOST,
senderId: SENDER_ID,
senderName: SENDER_NAME,
},
resolver: zodResolver(formSchema),
});
const handleSelectAction = (newValue: ISelectActionOption | null) => {
if (newValue) {
form.setValue("action", newValue.value);
if (newValue.value === WorkflowActions.SMS_NUMBER) {
setIsPhoneNumberNeeded(true);
setIsSenderIdNeeded(true);
setIsEmailAddressNeeded(false);
form.resetField("senderId", { defaultValue: SENDER_ID });
} else if (newValue.value === WorkflowActions.EMAIL_ADDRESS) {
setIsEmailAddressNeeded(true);
setIsSenderIdNeeded(false);
setIsPhoneNumberNeeded(false);
} else if (newValue.value === WorkflowActions.SMS_ATTENDEE) {
setIsSenderIdNeeded(true);
setIsEmailAddressNeeded(false);
setIsPhoneNumberNeeded(false);
form.resetField("senderId", { defaultValue: SENDER_ID });
} else if (newValue.value === WorkflowActions.WHATSAPP_NUMBER) {
setIsSenderIdNeeded(false);
setIsPhoneNumberNeeded(true);
setIsEmailAddressNeeded(false);
} else {
setIsSenderIdNeeded(false);
setIsEmailAddressNeeded(false);
setIsPhoneNumberNeeded(false);
}
form.unregister("sendTo");
form.unregister("numberRequired");
form.clearErrors("action");
form.clearErrors("sendTo");
}
};
if (!actionOptions) return null;
const canRequirePhoneNumber = (workflowStep: string) => {
return (
WorkflowActions.SMS_ATTENDEE === workflowStep || WorkflowActions.WHATSAPP_ATTENDEE === workflowStep
);
};
const showSender = (action: string) => {
return (
!isSenderIdNeeded &&
!(WorkflowActions.WHATSAPP_NUMBER === action || WorkflowActions.WHATSAPP_ATTENDEE === action)
);
};
return (
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
<DialogContent type="creation" title={t("add_action")}>
<div className="-mt-3 space-x-3">
<Form
form={form}
handleSubmit={(values) => {
addAction(
values.action,
values.sendTo,
values.numberRequired,
values.senderId,
values.senderName
);
form.unregister("sendTo");
form.unregister("action");
form.unregister("numberRequired");
setIsOpenDialog(false);
setIsPhoneNumberNeeded(false);
setIsEmailAddressNeeded(false);
setIsSenderIdNeeded(false);
}}>
<div className="stack-y-1">
<Label htmlFor="label">{t("action")}:</Label>
<Controller
name="action"
control={form.control}
render={() => {
return (
<Select
isSearchable={false}
className="text-sm"
menuPlacement="bottom"
defaultValue={actionOptions[0]}
onChange={handleSelectAction}
options={actionOptions.map((option) => ({
label: option.label,
value: option.value,
needsTeamsUpgrade: option.needsTeamsUpgrade,
upgradeTeamsBadgeProps: option.upgradeTeamsBadgeProps,
}))}
isOptionDisabled={(option: {
label: string;
value: WorkflowActions;
needsTeamsUpgrade?: boolean;
}) => !!option.needsTeamsUpgrade}
/>
);
}}
/>
{form.formState.errors.action && (
<p className="mt-1 text-sm text-red-500">{form.formState.errors.action.message}</p>
)}
</div>
{isPhoneNumberNeeded && (
<div className="stack-y-1 mt-5">
<Label htmlFor="sendTo">{t("phone_number")}</Label>
<div className="mb-5 mt-1">
<Controller
control={form.control}
name="sendTo"
render={({ field: { value, onChange } }) => (
<PhoneInput
className="rounded-md"
placeholder={t("enter_phone_number")}
id="sendTo"
required
value={value}
onChange={onChange}
/>
)}
/>
{form.formState.errors.sendTo && (
<p className="mt-1 text-sm text-red-500">{form.formState.errors.sendTo.message}</p>
)}
</div>
</div>
)}
{isEmailAddressNeeded && (
<div className="mt-5">
<EmailField required label={t("email_address")} {...form.register("sendTo")} />
</div>
)}
{isSenderIdNeeded && (
<>
<div className="mt-5">
<div className="flex items-center">
<Label>{t("sender_id")}</Label>
<Tooltip content={t("sender_id_info")}>
<span>
<Icon name="info" className="mb-2 ml-2 mr-1 mt-0.5 h-4 w-4 text-gray-500" />
</span>
</Tooltip>
</div>
<Input type="text" placeholder={SENDER_ID} maxLength={11} {...form.register(`senderId`)} />
</div>
{form.formState.errors && form.formState?.errors?.senderId && (
<p className="mt-1 text-xs text-red-500">{t("sender_id_error_message")}</p>
)}
</>
)}
{showSender(form.getValues("action")) && (
<div className="mt-5">
<Label>{t("sender_name")}</Label>
<Input type="text" placeholder={SENDER_NAME} {...form.register(`senderName`)} />
</div>
)}
{canRequirePhoneNumber(form.getValues("action")) && (
<div className="mt-5">
<Controller
name="numberRequired"
control={form.control}
render={() => (
<CheckboxField
defaultChecked={form.getValues("numberRequired") || false}
description={t("make_phone_number_required")}
onChange={(e) => form.setValue("numberRequired", e.target.checked)}
/>
)}
/>
</div>
)}
<DialogFooter showDivider noSticky className="mt-12">
<DialogClose
onClick={() => {
setIsOpenDialog(false);
form.unregister("sendTo");
form.unregister("action");
form.unregister("numberRequired");
setIsPhoneNumberNeeded(false);
setIsEmailAddressNeeded(false);
setIsSenderIdNeeded(false);
}}
/>
<Button type="submit">{t("add")}</Button>
</DialogFooter>
</Form>
</div>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,189 @@
import type { Dispatch } from "react";
import type { CallDetailsAction, CallDetailsState } from "@calcom/features/ee/workflows/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { Icon } from "@calcom/ui/components/icon";
import {
Sheet,
SheetContent,
SheetBody,
SheetHeader,
SheetFooter,
SheetClose,
} from "@calcom/ui/components/sheet";
interface CallDetailsSheetProps {
state: CallDetailsState;
dispatch: Dispatch<CallDetailsAction>;
}
export function CallDetailsSheet({ state, dispatch }: CallDetailsSheetProps) {
const { t } = useLocale();
const { selectedCall } = state.callDetailsSheet;
if (!selectedCall) return null;
const formatDuration = (durationMs: number) => {
const totalSeconds = Math.round(durationMs / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}:${seconds.toString().padStart(2, "0")}`;
};
const formatTimestamp = (timestamp: number) => {
const date = new Date(timestamp);
return date.toLocaleString();
};
return (
<Sheet
open={true}
onOpenChange={() => {
dispatch({ type: "CLOSE_MODAL" });
}}>
<SheetContent className="bg-default max-w-2xl overflow-y-auto">
<SheetHeader showCloseButton={true}>
<div className="mb-4 flex items-center justify-between">
<div>
<h2 className="text-emphasis font-sans text-xl font-semibold">{t("call_details")}</h2>
<p className="text-subtle mt-1 text-sm">
{t("call_id")}: {selectedCall.call_id}{" "}
<Badge variant={selectedCall.call_status === "ended" ? "green" : "orange"}>
{selectedCall.call_status}
</Badge>
</p>
</div>
</div>
</SheetHeader>
<SheetBody className="stack-y-6 flex flex-col p-4">
{/* Call Information */}
<div className="stack-y-3">
<h3 className="text-emphasis text-base font-semibold">{t("call_information")}</h3>
<div className="grid grid-cols-2 gap-4">
<div>
<p className="text-subtle text-sm">{t("start_time")}</p>
<p className="text-default text-sm font-medium">
{selectedCall.start_timestamp
? formatTimestamp(selectedCall.start_timestamp)
: t("unknown")}
</p>
</div>
<div>
<p className="text-subtle text-sm">{t("duration")}</p>
<p className="text-default text-sm font-medium">
{selectedCall.duration_ms ? formatDuration(selectedCall.duration_ms) : t("unknown")}
</p>
</div>
<div>
<p className="text-subtle text-sm">{t("from")}</p>
<p className="text-default text-sm font-medium">
{"from_number" in selectedCall ? selectedCall.from_number || t("unknown") : t("unknown")}
</p>
</div>
<div>
<p className="text-subtle text-sm">{t("to")}</p>
<p className="text-default text-sm font-medium">
{"to_number" in selectedCall ? selectedCall.to_number || t("unknown") : t("unknown")}
</p>
</div>
<div>
<p className="text-subtle text-sm">{t("sentiment")}</p>
<Badge
variant={
selectedCall.call_analysis?.user_sentiment === "Positive"
? "green"
: selectedCall.call_analysis?.user_sentiment === "Negative"
? "red"
: "gray"
}>
{selectedCall.call_analysis?.user_sentiment || "Unknown"}
</Badge>
</div>
<div>
<p className="text-subtle text-sm">{t("disconnect_reason")}</p>
<p className="text-default text-sm font-medium">
{selectedCall.disconnection_reason?.replace(/_/g, " ")}
</p>
</div>
</div>
</div>
{/* Call Summary */}
{selectedCall.call_analysis?.call_summary && (
<div className="stack-y-3">
<h3 className="text-emphasis text-base font-semibold">{t("call_summary")}</h3>
<p className="text-default text-sm">{selectedCall.call_analysis.call_summary}</p>
</div>
)}
{/* Recording Section */}
<div className="stack-y-3">
<h3 className="text-emphasis text-base font-semibold">{t("recording")}</h3>
<div className="flex items-center gap-3">
<audio controls className="h-11 w-[258px]" src={selectedCall.recording_url}>
Your browser does not support the audio element.
</audio>
<Button color="minimal" href={selectedCall.recording_url} target="_blank" StartIcon="download">
{t("download")}
</Button>
</div>
</div>
{/* Transcription */}
<div className="stack-y-3">
<h3 className="text-emphasis text-base font-semibold">{t("transcription")}</h3>
<div className="border-subtle stack-y-3 max-h-96 overflow-y-auto rounded-md border p-4">
{selectedCall.transcript ? (
selectedCall.transcript
.split("\n")
.filter((line) => line.trim())
.map((line, index) => {
const isAgent = line.startsWith("Agent:");
const isUser = line.startsWith("User:");
const content = line.replace(/^(Agent:|User:)\s*/, "");
if (!isAgent && !isUser) return null;
return (
<div key={index} className="stack-y-1">
<div className="flex items-center gap-2">
<Icon name="user" className={isAgent ? "text-info" : "text-success"} />
<span className={`text-sm font-medium ${isAgent ? "text-info" : "text-success"}`}>
{isAgent ? t("agent") : t("user")}
</span>
</div>
<p className="text-default ml-7 text-sm">{content}</p>
</div>
);
})
) : (
<p className="text-subtle text-sm">{t("no_transcript_available")}</p>
)}
</div>
</div>
{/* Event Details */}
{selectedCall.retell_llm_dynamic_variables && (
<div className="stack-y-3">
<h3 className="text-emphasis text-base font-semibold">{t("event_details")}</h3>
<div className="border-subtle bg-cal-muted rounded-md border p-4">
<pre className="text-default overflow-x-auto text-xs">
{JSON.stringify(selectedCall.retell_llm_dynamic_variables, null, 2)}
</pre>
</div>
</div>
)}
</SheetBody>
<SheetFooter>
<SheetClose asChild>
<Button color="secondary">{t("close")}</Button>
</SheetClose>
</SheetFooter>
</SheetContent>
</Sheet>
);
}
@@ -0,0 +1,58 @@
import type { Dispatch, SetStateAction } from "react";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import { trpc } from "@calcom/trpc/react";
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
import { showToast } from "@calcom/ui/components/toast";
interface IDeleteDialog {
isOpenDialog: boolean;
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
workflowId: number;
additionalFunction: () => Promise<boolean | void>;
}
export const DeleteDialog = (props: IDeleteDialog) => {
const { t } = useLocale();
const { isOpenDialog, setIsOpenDialog, workflowId, additionalFunction } = props;
const utils = trpc.useUtils();
const deleteMutation = trpc.viewer.workflows.delete.useMutation({
onSuccess: async () => {
await utils.viewer.workflows.filteredList.invalidate();
additionalFunction();
showToast(t("workflow_deleted_successfully"), "success");
setIsOpenDialog(false);
},
onError: (err) => {
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
setIsOpenDialog(false);
}
if (err.data?.code === "UNAUTHORIZED") {
const message = `${err.data.code}: You are not authorized to delete this workflow`;
showToast(message, "error");
}
},
});
return (
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
<ConfirmationDialogContent
isPending={deleteMutation.isPending}
variety="danger"
title={t("delete_workflow")}
confirmBtnText={t("confirm_delete_workflow")}
loadingText={t("confirm_delete_workflow")}
onConfirm={(e) => {
e.preventDefault();
deleteMutation.mutate({ id: workflowId });
}}>
{t("delete_workflow_description")}
</ConfirmationDialogContent>
</Dialog>
);
};
@@ -0,0 +1,167 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import cn from "@calcom/ui/classNames";
import { EmptyScreen as ClassicEmptyScreen } from "@calcom/ui/components/empty-screen";
import { Icon } from "@calcom/ui/components/icon";
import type { IconName } from "@calcom/ui/components/icon";
import { CreateButtonWithTeamsList } from "~/ee/teams/components/createButton/CreateButtonWithTeamsList";
import { WorkflowCreationDialog, useWorkflowCreation } from "./WorkflowCreationDialog";
type WorkflowExampleType = {
icon: IconName;
iconWrapperClassName?: string;
title: string;
description: string;
image?: string;
};
function WorkflowExample(props: WorkflowExampleType) {
const { icon: iconName, title, description, iconWrapperClassName, image } = props;
return (
<div className="bg-default border-subtle max-h-24 max-w-[600px] rounded-xl border border-solid p-2.5">
<div className="flex">
<div className="flex items-center justify-center">
<div
className={cn(
"bg-emphasis dark:bg-default mr-4 flex h-10 w-10 items-center justify-center rounded-[10px]",
iconWrapperClassName
)}>
{image ? (
<img
src={image}
alt=""
role="presentation"
aria-hidden="true"
className={cn("text-default h-5 w-5")}
/>
) : (
<Icon name={iconName} className={cn("text-default h-5 w-5")} aria-hidden="true" />
)}
</div>
</div>
<div className="m-auto w-full grow items-center justify-center ">
<div className="text-semibold text-emphasis line-clamp-2 w-full text-sm font-semibold">{title}</div>
<div className="text-default text-sm font-normal leading-none">{description}</div>
</div>
</div>
</div>
);
}
export default function EmptyScreen(props: { isFilteredView: boolean }) {
const { t } = useLocale();
const { showDialog, setShowDialog, pendingTeamId, openDialog } = useWorkflowCreation();
const workflowsExamples: WorkflowExampleType[] = [
{ icon: "smartphone", title: t("send_sms_reminder"), description: t("send_sms_reminder_description") },
{
icon: "smartphone",
title: t("follow_up_with_no_shows"),
description: t("follow_up_with_no_shows_description"),
},
{
icon: "mail",
title: t("remind_attendees_to_bring_id"),
description: t("remind_attendees_to_bring_id_description"),
},
{
icon: "mail",
title: t("email_to_remind_booking"),
description: t("email_to_remind_booking_description"),
},
{
icon: "mail",
title: t("custom_email_reminder"),
description: t("custom_email_reminder_description"),
},
{
icon: "smartphone",
title: t("custom_sms_reminder"),
description: t("custom_sms_reminder_description"),
},
];
const calAITemplates: WorkflowExampleType[] = [
{
icon: "phone-outgoing",
title: t("call_to_confirm_booking"),
description: t("cal_ai_phone_call_action_description"),
iconWrapperClassName: "bg-[#2A2947]",
image: "/call-outgoing.svg",
},
{
icon: "phone-outgoing",
title: t("follow_up_with_no_shows"),
description: t("follow_up_with_no_shows_description"),
iconWrapperClassName: "bg-[#2A2947]",
image: "/call-outgoing.svg",
},
{
icon: "phone-outgoing",
title: t("remind_attendees_to_bring_id"),
description: t("remind_attendees_to_bring_id_description"),
iconWrapperClassName: "bg-[#2A2947]",
image: "/call-outgoing.svg",
},
];
// new workflow example when 'after meetings ends' trigger is implemented: Send custom thank you email to attendee after event (Smile icon),
if (props.isFilteredView) {
return <ClassicEmptyScreen Icon="zap" headline={t("no_workflows")} description={t("change_filter")} />;
}
return (
<>
<div className="min-h-80 flex w-full flex-col items-center justify-center rounded-md ">
<div className="bg-emphasis flex h-[72px] w-[72px] items-center justify-center rounded-full">
<Icon name="zap" className="dark:text-default inline-block h-10 w-10 stroke-[1.3px]" />
</div>
<div className="max-w-[420px] text-center">
<h2 className="text-semibold font-cal mt-6 text-xl dark:text-gray-300">{t("workflows")}</h2>
<p className="text-default line-clamp-2 mt-3 text-sm font-normal leading-6 dark:text-gray-300">
{t("no_workflows_description")}
</p>
<div className="mt-8 ">
<CreateButtonWithTeamsList
subtitle={t("new_workflow_subtitle").toUpperCase()}
createFunction={openDialog}
buttonText={t("create_workflow")}
includeOrg={true}
/>
</div>
</div>
</div>
<div className="flex flex-col gap-4">
<TemplateSection title={t("cal_ai_templates")} examples={calAITemplates} />
<TemplateSection title={t("standard_templates")} examples={workflowsExamples} />
</div>
<WorkflowCreationDialog open={showDialog} onOpenChange={setShowDialog} teamId={pendingTeamId} />
</>
);
}
const TemplateSection = ({ title, examples }: { title: string; examples: WorkflowExampleType[] }) => {
return (
<div className="flex items-center justify-center">
<div className="bg-cal-muted flex max-w-5xl flex-col rounded-md p-2">
<h2 className="text-emphasis mb-2 text-base font-semibold">{title}</h2>
<div className="grid grid-cols-1 items-center gap-2 lg:grid-cols-3">
{examples.map((example: WorkflowExampleType, index: number) => (
<WorkflowExample
key={index}
icon={example.icon}
title={example.title}
description={example.description}
iconWrapperClassName={example.iconWrapperClassName}
image={example.image}
/>
))}
</div>
</div>
</div>
);
};
@@ -0,0 +1,12 @@
import { SkeletonText, SkeletonContainer } from "@calcom/ui/components/skeleton";
function SkeletonLoader() {
return (
<SkeletonContainer>
<SkeletonText className="mx-auto my-8 h-48 w-full max-w-4xl" />
<SkeletonText className="mx-auto my-8 h-80 w-full max-w-4xl" />
</SkeletonContainer>
);
}
export default SkeletonLoader;
@@ -0,0 +1,37 @@
import { SkeletonText, SkeletonAvatar } from "@calcom/ui/components/skeleton";
function SkeletonLoader() {
return (
<ul className="bg-default divide-subtle animate-pulse sm:overflow-hidden">
<SkeletonItem />
<SkeletonItem />
</ul>
);
}
export default SkeletonLoader;
function SkeletonItem() {
return (
<li className="border-subtle group mb-4 flex h-[90px] w-full items-center justify-between rounded-md border px-4 py-4 sm:px-6">
<div className="grow truncate text-sm">
<div className="flex">
<SkeletonAvatar className="h-10 w-10" />
<div className="ml-4 mt-1 flex flex-col stack-y-1">
<SkeletonText className="h-5 w-20 sm:w-24" />
<div className="flex">
<SkeletonText className="h-4 w-16 ltr:mr-2 rtl:ml-2 sm:w-28" />
</div>
</div>
</div>
</div>
<div className="mt-0 flex shrink-0 sm:ml-5">
<div className="flex justify-between space-x-2 rtl:space-x-reverse">
<SkeletonText className="h-8 w-8 sm:w-16" />
<SkeletonText className="h-8 w-8 sm:w-16" />
</div>
</div>
</li>
);
}
@@ -0,0 +1,39 @@
import { Icon } from "@calcom/ui/components/icon";
import { SkeletonText } from "@calcom/ui/components/skeleton";
function SkeletonLoader() {
return (
<ul className="divide-subtle border-subtle bg-default animate-pulse divide-y rounded-md border sm:overflow-hidden">
<SkeletonItem />
<SkeletonItem />
<SkeletonItem />
</ul>
);
}
export default SkeletonLoader;
function SkeletonItem() {
return (
<li className="group flex w-full items-center justify-between px-4 py-4 sm:px-6">
<div className="grow truncate text-sm">
<div className="flex">
<div className="flex flex-col stack-y-2">
<SkeletonText className="h-4 w-16 sm:w-24" />
<div className="flex">
<Icon name="bell" className="mr-1.5 mt-0.5 inline h-4 w-4 text-gray-200" />
<SkeletonText className="h-4 w-16 ltr:mr-2 rtl:ml-2 sm:w-28" />
<Icon name="link" className="mr-1.5 mt-0.5 inline h-4 w-4 text-gray-200" />
<SkeletonText className="h-4 w-28 sm:w-36" />
</div>
</div>
</div>
</div>
<div className="mt-0 flex shrink-0 sm:ml-5">
<div className="flex justify-between space-x-2 rtl:space-x-reverse">
<SkeletonText className="h-8 w-8 sm:w-16" />
</div>
</div>
</li>
);
}
@@ -0,0 +1,109 @@
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import PhoneInput from "@calcom/features/components/phone-input";
import { getEventTypeIdForCalAiTest } from "@calcom/features/ee/workflows/lib/actionHelperFunctions";
import type { FormValues } from "@calcom/features/ee/workflows/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
import { Label } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
interface TestPhoneCallDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
agentId: string;
teamId?: number;
form: UseFormReturn<FormValues>;
eventTypeIds?: number[];
outboundEventTypeId?: number | null;
}
export function TestPhoneCallDialog({
open,
onOpenChange,
agentId,
teamId,
form,
eventTypeIds = [],
outboundEventTypeId,
}: TestPhoneCallDialogProps) {
const { t } = useLocale();
const [testPhoneNumber, setTestPhoneNumber] = useState("");
const testCallMutation = trpc.viewer.aiVoiceAgent.testCall.useMutation({
onSuccess: async (data) => {
showToast(data?.message ?? t("call_initiated_successfully"), "success");
onOpenChange(false);
setTestPhoneNumber("");
},
onError: (error: { message: string }) => {
showToast(t(error.message), "error");
},
});
const handleTestCall = () => {
if (!testPhoneNumber) {
showToast(t("please_enter_phone_number"), "error");
return;
}
const eventTypeValidation = getEventTypeIdForCalAiTest({
trigger: form.getValues("trigger"),
outboundEventTypeId,
eventTypeIds,
activeOnEventTypeId: form.getValues("activeOn")?.[0]?.value,
t,
});
if (eventTypeValidation.error || !eventTypeValidation.eventTypeId) {
showToast(eventTypeValidation.error || t("no_event_type_selected"), "error");
return;
}
if (agentId) {
testCallMutation.mutate({
agentId: agentId,
phoneNumber: testPhoneNumber,
teamId: teamId,
eventTypeId: eventTypeValidation.eventTypeId,
});
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
type="creation"
title={t("test_cal_ai_agent")}
description={t("make_test_call_to_verify_configuration")}>
<div>
<Label className="mb-1 block text-sm font-medium">{t("call_to")}:</Label>
<PhoneInput
placeholder={t("enter_phone_number_to_test_call")}
value={testPhoneNumber}
onChange={(val) => setTestPhoneNumber(val || "")}
disabled={testCallMutation.isPending}
/>
</div>
<DialogFooter showDivider>
<Button type="button" color="secondary" onClick={() => onOpenChange(false)}>
{t("cancel")}
</Button>
<Button
type="button"
onClick={handleTestCall}
loading={testCallMutation.isPending}
disabled={!testPhoneNumber}>
<Icon name="phone" className="mr-2 h-4 w-4" />
{t("make_test_call")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,94 @@
import { useState } from "react";
import { useFormContext } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { TimeUnit } from "@calcom/prisma/enums";
import { Icon } from "@calcom/ui/components/icon";
import { TextField } from "@calcom/ui/components/form";
import {
Dropdown,
DropdownItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@calcom/ui/components/dropdown";
const TIME_UNITS = [TimeUnit.DAY, TimeUnit.HOUR, TimeUnit.MINUTE] as const;
type Props = {
disabled: boolean;
defaultTime?: number;
};
const TimeUnitAddonSuffix = ({
DropdownItems,
timeUnitOptions,
}: {
DropdownItems: JSX.Element;
timeUnitOptions: { [x: string]: string };
}) => {
// because isDropdownOpen already triggers a render cycle we can use getValues()
// instead of watch() function
const form = useFormContext();
const timeUnit = form.getValues("timeUnit") ?? TimeUnit.MINUTE;
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
return (
<Dropdown onOpenChange={setIsDropdownOpen}>
<DropdownMenuTrigger asChild>
<button className="flex items-center">
<div className="mr-1 w-3/5">{timeUnit ? timeUnitOptions[timeUnit] : "undefined"}</div>
<div className="w-1/4 pt-1">
{isDropdownOpen ? <Icon name="chevron-up" /> : <Icon name="chevron-down" />}
</div>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>{DropdownItems}</DropdownMenuContent>
</Dropdown>
);
};
export const TimeTimeUnitInput = (props: Props) => {
const form = useFormContext();
const { t } = useLocale();
const timeUnitOptions = TIME_UNITS.reduce((acc, option) => {
acc[option] = t(`${option.toLowerCase()}_timeUnit`);
return acc;
}, {} as { [x: string]: string });
return (
<div className="flex">
<div className="grow">
<TextField
type="number"
min="1"
label=""
disabled={props.disabled}
defaultValue={form.getValues("time") ?? props.defaultTime ?? 24}
className="rounded-r-none text-sm focus:ring-0"
{...form.register("time", { valueAsNumber: true })}
addOnSuffix={
<TimeUnitAddonSuffix
timeUnitOptions={timeUnitOptions}
DropdownItems={
<>
{TIME_UNITS.map((timeUnit, index) => (
<DropdownMenuItem key={index} className="outline-none">
<DropdownItem
key={index}
type="button"
onClick={() => {
form.setValue("timeUnit", timeUnit, { shouldDirty: true });
}}>
{timeUnitOptions[timeUnit]}
</DropdownItem>
</DropdownMenuItem>
))}
</>
}
/>
}
/>
</div>
</div>
);
};
@@ -0,0 +1,208 @@
import { getCoreRowModel, getSortedRowModel, useReactTable, type ColumnDef } from "@tanstack/react-table";
import { usePathname } from "next/navigation";
import { useMemo, useState } from "react";
import { DataTableProvider, DataTableWrapper } from "@calcom/features/data-table";
import { useSegments } from "@calcom/features/data-table/hooks/useSegments";
import { useVoicePreview } from "@calcom/features/ee/workflows/hooks/useVoicePreview";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Dialog, DialogContent, DialogHeader } from "@calcom/ui/components/dialog";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
type Voice = {
voice_id: string;
voice_name: string;
provider: "elevenlabs" | "openai" | "deepgram";
gender: "male" | "female";
accent?: string;
age?: string;
preview_audio_url?: string;
};
type VoiceSelectionDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
selectedVoiceId?: string;
onVoiceSelect: (voiceId: string) => void;
};
function VoiceSelectionTable({
selectedVoiceId,
onVoiceSelect,
}: {
selectedVoiceId?: string;
onVoiceSelect: (voiceId: string) => void;
}) {
const pathname = usePathname();
if (!pathname) return null;
return (
<DataTableProvider tableIdentifier={pathname} useSegments={useSegments} defaultPageSize={1000}>
<VoiceSelectionContent selectedVoiceId={selectedVoiceId} onVoiceSelect={onVoiceSelect} />
</DataTableProvider>
);
}
function VoiceSelectionContent({
selectedVoiceId,
onVoiceSelect,
}: {
selectedVoiceId?: string;
onVoiceSelect: (voiceId: string) => void;
}) {
const { t } = useLocale();
const { playingVoiceId, handlePlayVoice } = useVoicePreview();
const [rowSelection, setRowSelection] = useState({});
const { data: voices, isLoading } = trpc.viewer.aiVoiceAgent.listVoices.useQuery();
const handleUseVoice = (voiceId: string) => {
onVoiceSelect(voiceId);
showToast("Voice selected successfully", "success");
};
const voiceData: Voice[] = useMemo(() => {
if (!voices) return [];
return voices;
}, [voices]);
const columns = useMemo<ColumnDef<Voice>[]>(
() => [
{
id: "voice",
accessorKey: "voice_name",
header: t("voice"),
size: 200,
cell: ({ row }) => (
<div className="flex items-center gap-3">
<Button
type="button"
variant="icon"
color="secondary"
size="sm"
onClick={() => handlePlayVoice(row.original.preview_audio_url, row.original.voice_id)}
className="rounded-full">
{playingVoiceId === row.original.voice_id ? (
<Icon name="pause" className="text-default h-3 w-3" />
) : (
<Icon name="play" className="text-default h-3 w-3" />
)}
</Button>
<div className="flex items-center gap-2">
<div className="bg-subtle flex h-10 w-10 items-center justify-center rounded-full">
<Icon name="user" className="text-default h-5 w-5" />
</div>
<span className="text-emphasis font-medium">{row.original.voice_name}</span>
</div>
</div>
),
},
{
id: "trait",
accessorKey: "accent",
header: t("trait"),
size: 200,
cell: ({ row }) => (
<div className="flex gap-2 text-sm">
{row.original.accent && (
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">
{row.original.accent}
</span>
)}
{row.original.gender && (
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">
{row.original.gender}
</span>
)}
{row.original.provider && (
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">
{row.original.provider}
</span>
)}
{row.original.age && (
<span className="bg-subtle text-default rounded-md px-2 py-1 text-xs">{row.original.age}</span>
)}
</div>
),
},
{
id: "voice_id",
accessorKey: "voice_id",
header: t("voice_id"),
size: 200,
cell: ({ row }) => <span className="text-muted font-mono text-sm">{row.original.voice_id}</span>,
},
{
id: "actions",
header: "",
size: 120,
cell: ({ row }) => (
<Button
type="button"
size="sm"
color={selectedVoiceId === row.original.voice_id ? "primary" : "secondary"}
onClick={() => handleUseVoice(row.original.voice_id)}
className="whitespace-nowrap">
{selectedVoiceId === row.original.voice_id ? <>{t("current_voice")}</> : t("use_voice")}
</Button>
),
},
],
[t, playingVoiceId, selectedVoiceId]
);
const table = useReactTable({
data: voiceData,
columns,
enableRowSelection: false,
manualPagination: false,
state: {
rowSelection,
},
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
onRowSelectionChange: setRowSelection,
getRowId: (row) => row.voice_id,
});
return (
<div className="border-subtle max-h-[500px] overflow-auto rounded-lg border">
<DataTableWrapper<Voice>
testId="voice-selection-data-table"
table={table}
isPending={isLoading}
totalRowCount={voiceData?.length || 0}
paginationMode="standard"
className="h-auto"
/>
</div>
);
}
export function VoiceSelectionDialog({
open,
onOpenChange,
selectedVoiceId,
onVoiceSelect,
}: VoiceSelectionDialogProps) {
const { t } = useLocale();
const handleVoiceSelect = (voiceId: string) => {
onVoiceSelect(voiceId);
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent enableOverflow className="flex h-[80vh] flex-col p-6 sm:max-w-7xl">
<DialogHeader title={t("select_voice")} subtitle={t("choose_a_voice_for_your_agent")} />
<div className="mt-4 min-h-0 flex-1 overflow-hidden">
<VoiceSelectionTable selectedVoiceId={selectedVoiceId} onVoiceSelect={handleVoiceSelect} />
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,487 @@
import Link from "next/link";
import { useState, useEffect, useRef, useCallback } from "react";
import type { UseFormReturn } from "react-hook-form";
import type { RetellWebClient } from "retell-client-js-sdk";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { getEventTypeIdForCalAiTest } from "@calcom/features/ee/workflows/lib/actionHelperFunctions";
import type { FormValues } from "@calcom/features/ee/workflows/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
interface WebCallDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
agentId: string;
teamId?: number;
isOrganization?: boolean;
form: UseFormReturn<FormValues>;
eventTypeIds?: number[];
outboundEventTypeId?: number | null;
}
interface TranscriptEntry {
speaker: "agent" | "user";
text: string;
timestamp: Date;
}
type CallStatus = "idle" | "connecting" | "active" | "ended" | "error";
export function WebCallDialog({
open,
onOpenChange,
agentId,
teamId,
isOrganization = false,
form,
eventTypeIds = [],
outboundEventTypeId,
}: WebCallDialogProps) {
const { t } = useLocale();
const [callStatus, setCallStatus] = useState<CallStatus>("idle");
const [transcript, setTranscript] = useState<TranscriptEntry[]>([]);
const [isMuted, setIsMuted] = useState(false);
const [callDuration, setCallDuration] = useState(0);
const [error, setError] = useState<string | null>(null);
const retellWebClientRef = useRef<RetellWebClient | null>(null);
const callStartTimeRef = useRef<Date | null>(null);
const durationIntervalRef = useRef<NodeJS.Timeout | null>(null);
const transcriptEndRef = useRef<HTMLDivElement>(null);
const callStatusRef = useRef<CallStatus>("idle");
const { data: hasCredits, isLoading: creditsLoading } = trpc.viewer.credits.hasAvailableCredits.useQuery(
{ teamId },
{ enabled: open }
);
const getBillingPath = () => {
if (!teamId) return "/settings/billing";
return isOrganization ? "/settings/organizations/billing" : `/settings/teams/${teamId}/billing`;
};
const createWebCallMutation = trpc.viewer.aiVoiceAgent.createWebCall.useMutation({
onSuccess: async (data) => {
try {
await startWebCall(data.accessToken);
} catch (error) {
console.error("Failed to start web call:", error);
setCallStatus("error");
setError(t("failed_to_start_web_call_try_again"));
}
},
onError: (error: { message: string }) => {
setCallStatus("error");
setError(error.message);
showToast(error.message, "error");
},
});
const startWebCall = async (accessToken: string) => {
try {
const { RetellWebClient } = await import("retell-client-js-sdk");
const retellWebClient = new RetellWebClient();
retellWebClientRef.current = retellWebClient;
retellWebClient.on("call_started", () => {
callStartTimeRef.current = new Date();
callStatusRef.current = "active";
setCallStatus("active");
startDurationTimer();
});
retellWebClient.on("call_ended", () => {
setCallStatus("ended");
stopDurationTimer();
});
retellWebClient.on("agent_start_talking", () => {
console.log("Agent started talking");
});
retellWebClient.on("agent_stop_talking", () => {
console.log("Agent stopped talking");
});
retellWebClient.on("update", (update: { transcript?: Array<{ role: string; content: string }> }) => {
console.log("📝 Received update event:", update);
if (update.transcript && Array.isArray(update.transcript)) {
console.log("📜 Transcript array received:", update.transcript);
try {
const newEntries: TranscriptEntry[] = update.transcript
.map((entry) => {
if (!entry.role || !entry.content) {
console.warn("⚠️ Invalid transcript entry:", entry);
return null;
}
const mappedEntry = {
speaker: entry.role === "agent" ? "agent" : "user",
text: entry.content,
timestamp: new Date(),
};
console.log("✅ Mapped transcript entry:", mappedEntry);
return mappedEntry;
})
.filter(Boolean) as TranscriptEntry[];
console.log("🔄 Setting transcript with entries:", newEntries.length, "entries");
console.log("📋 Current transcript state has:", transcript.length, "entries");
setTranscript(newEntries);
} catch (error) {
console.error("❌ Error processing transcript update:", error);
}
} else {
console.log(
"🚫 No transcript data in update or transcript is not an array:",
typeof update.transcript
);
}
});
retellWebClient.on("error", (error: Error | { message?: string }) => {
console.error("Web call error:", error);
setCallStatus("error");
setError(t("call_encountered_error_try_again"));
stopDurationTimer();
});
setCallStatus("connecting");
await retellWebClient.startCall({
accessToken: accessToken,
sampleRate: 24000,
emitRawAudioSamples: false,
});
} catch (error) {
console.error("Error starting web call:", error);
setCallStatus("error");
setError(t("failed_initialize_web_call_microphone_permissions"));
}
};
const startDurationTimer = useCallback(() => {
if (durationIntervalRef.current) {
clearInterval(durationIntervalRef.current);
durationIntervalRef.current = null;
}
if (!callStartTimeRef.current) {
return;
}
durationIntervalRef.current = setInterval(() => {
if (callStartTimeRef.current) {
const now = Date.now();
const startTime = callStartTimeRef.current.getTime();
const duration = Math.floor((now - startTime) / 1000);
if (duration >= 0) {
setCallDuration(duration);
}
}
}, 1000);
}, []);
const stopDurationTimer = () => {
if (durationIntervalRef.current) {
clearInterval(durationIntervalRef.current);
durationIntervalRef.current = null;
}
};
const handleStartCall = () => {
const eventTypeValidation = getEventTypeIdForCalAiTest({
trigger: form.getValues("trigger"),
outboundEventTypeId,
eventTypeIds,
activeOnEventTypeId: form.getValues("activeOn")?.[0]?.value,
t,
});
if (eventTypeValidation.error || !eventTypeValidation.eventTypeId) {
showToast(eventTypeValidation.error || t("no_event_type_selected"), "error");
return;
}
if (agentId) {
setError(null);
setTranscript([]);
setCallDuration(0);
createWebCallMutation.mutate({
agentId: agentId,
teamId: teamId,
eventTypeId: eventTypeValidation.eventTypeId,
});
}
};
const handleEndCall = async () => {
if (retellWebClientRef.current && callStatus === "active") {
try {
await retellWebClientRef.current.stopCall();
setCallStatus("ended");
stopDurationTimer();
} catch (error) {
console.error("Error ending call:", error);
}
}
};
const handleToggleMute = async () => {
if (retellWebClientRef.current && callStatus === "active") {
try {
if (isMuted) {
await retellWebClientRef.current.unmute();
} else {
await retellWebClientRef.current.mute();
}
setIsMuted(!isMuted);
} catch (error) {
console.error("Error toggling mute:", error);
}
}
};
const formatDuration = (seconds: number) => {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
};
const getStatusIcon = () => {
switch (callStatus) {
case "connecting":
return <Icon name="loader" className="h-4 w-4 animate-spin rounded-full" />;
case "active":
return <Icon name="phone" className="text-success h-4 w-4" />;
case "ended":
return <Icon name="phone-off" className="text-muted h-4 w-4" />;
case "error":
return <Icon name="triangle-alert" className="text-error h-4 w-4" />;
default:
return <Icon name="phone" className="text-subtle h-4 w-4" />;
}
};
const getStatusText = () => {
switch (callStatus) {
case "connecting":
return t("connecting_to_agent");
case "active":
return `${t("call_active")} - ${formatDuration(callDuration)}`;
case "ended":
return `${t("call_ended")} - ${formatDuration(callDuration)}`;
case "error":
return t("call_error");
default:
return t("ready_to_start_call");
}
};
useEffect(() => {
if (transcriptEndRef.current) {
transcriptEndRef.current.scrollIntoView({ behavior: "smooth" });
}
}, [transcript]);
useEffect(() => {
return () => {
stopDurationTimer();
if (retellWebClientRef.current && callStatus === "active") {
try {
retellWebClientRef.current.stopCall();
} catch (error) {
console.error("Error stopping call during cleanup:", error);
}
}
};
}, [callStatus]);
useEffect(() => {
callStatusRef.current = callStatus;
if (callStatus === "active" && callStartTimeRef.current && !durationIntervalRef.current) {
startDurationTimer();
}
}, [callStatus, startDurationTimer]);
useEffect(() => {
return () => {
stopDurationTimer();
};
}, []);
const resetDialogState = () => {
setCallStatus("idle");
callStatusRef.current = "idle";
setTranscript([]);
setIsMuted(false);
setCallDuration(0);
setError(null);
callStartTimeRef.current = null;
stopDurationTimer();
retellWebClientRef.current = null;
};
return (
<Dialog
open={open}
onOpenChange={(open) => {
if (!open) {
if (retellWebClientRef.current) {
try {
retellWebClientRef.current.stopCall();
} catch (e) {
console.error("Error stopping call on close:", e);
}
}
resetDialogState();
}
onOpenChange(open);
}}>
<DialogContent
enableOverflow
type="creation"
title={t("web_call")}
description={t("test_your_agent_with_web_call")}>
{!creditsLoading && (
<Alert
severity="info"
CustomIcon="info"
title={t("credits_required")}
message={
hasCredits ? (
t("web_call_credits_info")
) : (
<>
{t("web_call_no_credits")}{" "}
<Link href={getBillingPath()} className="text-semantic-info underline">
{t("purchase_credits")}
</Link>
</>
)
}
/>
)}
<div className="mt-2 flex items-center justify-between rounded-lg border p-3">
<div className="flex items-center gap-2">
{getStatusIcon()}
<span className="text-sm font-medium">{getStatusText()}</span>
</div>
{callStatus === "active" && (
<div className="flex items-center gap-2">
<div className="bg-error h-2 w-2 animate-pulse rounded-full" />
<span className="text-subtle text-xs">{t("live")}</span>
</div>
)}
</div>
<div className="mt-2 rounded-lg border p-3 placeholder:min-h-[300px]">
<div className="mb-3 flex items-center justify-between">
<h4 className="text-sm font-medium">{t("transcript")}</h4>
{transcript.length > 0 && (
<Button
type="button"
color="secondary"
size="sm"
variant="icon"
onClick={() => setTranscript([])}
disabled={callStatus === "active"}>
<Icon name="trash" className="h-4 w-4" />
</Button>
)}
</div>
<div className="stack-y-3 h-60 overflow-y-auto p-2">
{transcript.length === 0 ? (
<div className="flex h-40 items-center justify-center text-center">
<div>
<Icon name="message-circle" className="text-subtle mx-auto h-8 w-8" />
<p className="text-subtle mt-2 text-sm">
{callStatus === "idle"
? t("start_call_to_see_conversation")
: t("waiting_for_conversation")}
</p>
</div>
</div>
) : (
transcript.map((entry, index) => (
<div
key={index}
className={`flex gap-2 ${entry.speaker === "agent" ? "justify-start" : "justify-end"}`}>
<div
className={`max-w-[80%] rounded-lg px-3 py-2 text-sm ${
entry.speaker === "agent"
? "border-brand bg-brand/10 text-brand-emphasis border"
: "border-subtle bg-subtle text-emphasis border"
}`}>
<div className="mb-1 flex items-center gap-2">
<span className="text-xs font-medium">
{entry.speaker === "agent" ? t("ai_agent") : t("you")}
</span>
</div>
<p>{entry.text}</p>
</div>
</div>
))
)}
<div ref={transcriptEndRef} />
</div>
</div>
{error && callStatus === "error" && (
<div className="border-error bg-error/10 rounded-lg p-3">
<div className="flex items-center gap-2">
<Icon name="triangle-alert" className="text-error h-6 w-6" />
<span className="text-error text-sm">{error}</span>
</div>
</div>
)}
<DialogFooter showDivider className="mt-6">
<div className="flex gap-2">
{callStatus === "active" && (
<Button type="button" color="secondary" onClick={handleToggleMute} variant="icon">
<Icon name={isMuted ? "mic-off" : "mic"} className="h-4 w-4" />
</Button>
)}
{callStatus === "idle" ||
callStatus === "error" ||
callStatus === "ended" ||
callStatus === "connecting" ? (
<Tooltip content={!hasCredits ? t("credits_required_tooltip") : undefined}>
<Button
type="button"
onClick={handleStartCall}
loading={createWebCallMutation.isPending || callStatus === "connecting"}
disabled={!hasCredits || createWebCallMutation.isPending || callStatus === "connecting"}>
<Icon name="phone" className="mr-2 h-4 w-4" />
{callStatus === "connecting" ? t("connecting") : t("start_web_call")}
</Button>
</Tooltip>
) : (
<Button
type="button"
color="destructive"
onClick={handleEndCall}
disabled={callStatus !== "active"}>
<Icon name="phone-off" className="mr-2 h-4 w-4" />
{t("end_call")}
</Button>
)}
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,195 @@
import { useRouter } from "next/navigation";
import { useState } from "react";
import posthog from "posthog-js";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import { trpc } from "@calcom/trpc/react";
import cn from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { Dialog, DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
import { Icon } from "@calcom/ui/components/icon";
import type { IconName } from "@calcom/ui/components/icon";
import { RadioGroup, Radio, RadioIndicator } from "@calcom/ui/components/radio";
import { showToast } from "@calcom/ui/components/toast";
type WorkflowOptionCardProps = {
title: string;
description: string;
icon?: IconName;
isSelected: boolean;
onClick: () => void;
iconWrapperClassName?: string;
image?: string;
value: "scratch" | "calai";
};
function WorkflowOptionCard(props: WorkflowOptionCardProps) {
const { title, description, icon, isSelected, onClick, image, iconWrapperClassName, value } = props;
return (
<div
data-testid={`workflow-option-card-${value}`}
onClick={onClick}
className={cn(
`relative flex flex-1 cursor-pointer flex-col rounded-lg border p-4 transition-colors`,
isSelected ? "border-brand-default" : "border-subtle hover:border-emphasis"
)}>
<div className="absolute right-3 top-3">
<Radio value={value} aria-label={title}>
<RadioIndicator />
</Radio>
</div>
<div className="flex flex-col">
<div
className={cn(
"mb-5 flex h-10 w-10 items-center justify-center rounded-lg border",
iconWrapperClassName
)}>
{image ? (
<img
src={image}
alt=""
role="presentation"
aria-hidden="true"
className={cn("text-default h-5 w-5")}
/>
) : (
<Icon name={icon || "circle-plus"} className={cn("text-default h-5 w-5")} aria-hidden="true" />
)}
</div>
<h3 className="text-emphasis text-sm font-semibold">{title}</h3>
<p className="text-subtle text-sm">{description}</p>
</div>
</div>
);
}
type WorkflowCreationDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
teamId?: number;
onSuccess?: () => void;
};
export function WorkflowCreationDialog({
open,
onOpenChange,
teamId,
onSuccess,
}: WorkflowCreationDialogProps) {
const { t } = useLocale();
const router = useRouter();
const [selectedOption, setSelectedOption] = useState<"scratch" | "calai">("scratch");
const [isLoading, setIsLoading] = useState(false);
const handleOptionChange = (value: string) => {
if (value === "scratch" || value === "calai") {
setSelectedOption(value);
}
};
const createMutation = trpc.viewer.workflows.create.useMutation({
onSuccess: async ({ workflow }) => {
onOpenChange(false);
if (onSuccess) {
onSuccess();
} else {
router.replace(`/workflows/${workflow.id}`);
}
},
onError: (err) => {
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
}
if (err.data?.code === "UNAUTHORIZED") {
const message = `${err.data.code}: ${t("unauthorized_create_workflow")}`;
showToast(message, "error");
}
},
});
const handleContinue = () => {
if (selectedOption === "scratch") {
createMutation.mutate({ teamId });
} else if (selectedOption === "calai") {
setIsLoading(true);
const queryParams = new URLSearchParams({
action: "calAi",
templateWorkflowId: "wf-11",
...(teamId && { teamId: teamId.toString() }),
});
router.push(`/workflow/new?${queryParams.toString()}`);
setIsLoading(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
title={t("new_workflow_btn")}
description={t("how_would_you_like_to_start")}
type="creation"
enableOverflow
Icon="zap">
<RadioGroup
value={selectedOption}
onValueChange={handleOptionChange}
aria-label={t("new_workflow_btn")}>
<div className="mt-6 flex gap-4">
<WorkflowOptionCard
title={t("start_from_scratch_title")}
description={t("start_from_scratch_description")}
icon="circle-plus"
isSelected={selectedOption === "scratch"}
onClick={() => setSelectedOption("scratch")}
iconWrapperClassName="bg-cal-muted"
value="scratch"
/>
<WorkflowOptionCard
title={t("cal_ai_template_title")}
description={t("cal_ai_template_description")}
image="/call-outgoing.svg"
isSelected={selectedOption === "calai"}
onClick={() => setSelectedOption("calai")}
iconWrapperClassName="bg-[#2A2947]"
value="calai"
/>
</div>
</RadioGroup>
<DialogFooter className="relative" showDivider>
<Button type="button" color="minimal" onClick={() => onOpenChange(false)}>
{t("cancel")}
</Button>
<Button
data-testid="continue-button"
type="button"
onClick={handleContinue}
loading={createMutation.isPending || isLoading}>
{t("continue")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export function useWorkflowCreation() {
const [showDialog, setShowDialog] = useState(false);
const [pendingTeamId, setPendingTeamId] = useState<number | undefined>(undefined);
const openDialog = (teamId?: number) => {
setPendingTeamId(teamId);
setShowDialog(true);
posthog.capture("create_new_workflow_button_clicked", { teamId });
};
return {
showDialog,
setShowDialog,
pendingTeamId,
openDialog,
};
}
@@ -0,0 +1,334 @@
import { useSearchParams } from "next/navigation";
import type { Dispatch, SetStateAction } from "react";
import { useState, useEffect } from "react";
import type { UseFormReturn } from "react-hook-form";
import { useAgentsData } from "@calcom/features/ee/workflows/hooks/useAgentsData";
import {
isCalAIAction,
isSMSAction,
isFormTrigger,
} from "@calcom/features/ee/workflows/lib/actionHelperFunctions";
import { ALLOWED_FORM_WORKFLOW_ACTIONS } from "@calcom/features/ee/workflows/lib/constants";
import emailReminderTemplate from "@calcom/features/ee/workflows/lib/reminders/templates/emailReminderTemplate";
import type { FormValues } from "@calcom/features/ee/workflows/lib/types";
import type { WorkflowPermissions } from "@calcom/features/workflows/repositories/WorkflowPermissionsRepository";
import { SENDER_ID, SENDER_NAME, SCANNING_WORKFLOW_STEPS } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import { WorkflowActions } from "@calcom/prisma/enums";
import { WorkflowTemplates } from "@calcom/prisma/enums";
import { trpc, type RouterOutputs } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { FormCard, FormCardBody } from "@calcom/ui/components/card";
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { useHasPaidPlan, useHasActiveTeamPlan } from "@calcom/web/modules/billing/hooks/useHasPaidPlan";
import { AddActionDialog } from "./AddActionDialog";
import WorkflowStepContainer from "./WorkflowStepContainer";
type User = RouterOutputs["viewer"]["me"]["get"];
interface Props {
form: UseFormReturn<FormValues>;
workflowId: number;
selectedOptions: Option[];
setSelectedOptions: Dispatch<SetStateAction<Option[]>>;
teamId?: number;
user: User;
isOrg: boolean;
allOptions: Option[];
eventTypeOptions: Option[];
onSaveWorkflow?: () => Promise<void>;
permissions: WorkflowPermissions;
}
export default function WorkflowDetailsPage(props: Props) {
const {
form,
workflowId,
selectedOptions,
setSelectedOptions,
teamId,
isOrg,
allOptions,
eventTypeOptions,
permissions,
} = props;
const { t, i18n } = useLocale();
const { hasPaidPlan } = useHasPaidPlan();
const { hasActiveTeamPlan, isTrial } = useHasActiveTeamPlan();
const [isAddActionDialogOpen, setIsAddActionDialogOpen] = useState(false);
const [isDeleteStepDialogOpen, setIsDeleteStepDialogOpen] = useState(false);
const [reload, setReload] = useState(false);
const [updateTemplate, setUpdateTemplate] = useState(false);
const searchParams = useSearchParams();
const eventTypeId = searchParams?.get("eventTypeId");
// Get base action options and transform them for form triggers
const { data: baseActionOptions } = trpc.viewer.workflows.getWorkflowActionOptions.useQuery();
const transformedActionOptions = baseActionOptions
? baseActionOptions
.filter((option) => {
const isFormWorkflowWithInvalidSteps =
isFormTrigger(form.getValues("trigger")) &&
!ALLOWED_FORM_WORKFLOW_ACTIONS.some((action) => action === option.value);
const isSelectAllCalAiAction = isCalAIAction(option.value) && form.watch("selectAll");
const isOrgCalAiAction = isCalAIAction(option.value) && isOrg;
if (isFormWorkflowWithInvalidSteps || isSelectAllCalAiAction || isOrgCalAiAction) {
return false;
}
return true;
})
.map((option) => {
let label = option.label;
// Transform labels for form triggers
if (isFormTrigger(form.getValues("trigger"))) {
if (option.value === WorkflowActions.EMAIL_ATTENDEE) {
label = t("email_attendee_action_form");
} else if (option.value === WorkflowActions.SMS_ATTENDEE) {
label = t("sms_attendee_action_form");
}
}
const needsTeamsUpgrade = isFormTrigger(form.getValues("trigger")) && !hasActiveTeamPlan;
return {
...option,
label,
creditsTeamId: teamId,
isOrganization: isOrg,
isCalAi: isCalAIAction(option.value),
needsTeamsUpgrade,
upgradeTeamsBadgeProps: needsTeamsUpgrade
? { hasPaidPlan, hasActiveTeamPlan, isTrial }
: undefined,
};
})
: [];
useEffect(() => {
const matchingOption = allOptions.find((option) => option.value === eventTypeId);
if (matchingOption && !selectedOptions.find((option) => option.value === eventTypeId)) {
const newOptions = [...selectedOptions, matchingOption];
setSelectedOptions(newOptions);
form.setValue("activeOn", newOptions);
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally only run when eventTypeId changes
}, [eventTypeId]);
const addAction = (
action: WorkflowActions,
sendTo?: string,
numberRequired?: boolean,
sender?: string,
senderName?: string
) => {
const steps = form.getValues("steps");
const id =
steps?.length > 0
? steps.sort((a, b) => {
return a.id - b.id;
})[0].id - 1
: 0;
const timeFormat = getTimeFormatStringFromUserTimeFormat(props.user.timeFormat);
const template = isFormTrigger(form.getValues("trigger"))
? WorkflowTemplates.CUSTOM
: WorkflowTemplates.REMINDER;
const { emailBody: reminderBody, emailSubject } =
template !== WorkflowTemplates.CUSTOM
? emailReminderTemplate({
isEditingMode: true,
locale: i18n.language,
t,
action,
timeFormat,
})
: { emailBody: null, emailSubject: null };
const step = {
id: id > 0 ? 0 : id, //id of new steps always <= 0
action,
stepNumber:
steps && steps.length > 0
? steps.sort((a, b) => {
return a.stepNumber - b.stepNumber;
})[steps.length - 1].stepNumber + 1
: 1,
sendTo: sendTo || null,
workflowId: workflowId,
reminderBody,
emailSubject,
template,
numberRequired: numberRequired || false,
sender: isSMSAction(action) ? sender || SENDER_ID : SENDER_ID,
senderName: !isSMSAction(action) ? senderName || SENDER_NAME : SENDER_NAME,
numberVerificationPending: false,
includeCalendarEvent: false,
verifiedAt: SCANNING_WORKFLOW_STEPS ? null : new Date(),
agentId: null,
inboundAgentId: null,
};
steps?.push(step);
form.setValue("steps", steps);
};
const { outboundAgentQueries: agentQueriesTrpc, inboundAgentQueries: inboundAgentQueriesTrpc } =
useAgentsData(form);
return (
<>
<div>
<FormCard
className="border-muted mb-0"
collapsible={false}
label={
<div className="flex items-center gap-2 pt-1 pb-2">
<div className="border-subtle text-subtle ml-1 rounded-lg border p-1">
<Icon name="zap" size="16" />
</div>
<div className="text-sm font-medium leading-none">{t("trigger")}</div>
</div>
}>
<FormCardBody className="border-muted">
<WorkflowStepContainer
form={form}
user={props.user}
teamId={teamId}
readOnly={permissions.readOnly}
selectedOptions={selectedOptions}
setSelectedOptions={setSelectedOptions}
isOrganization={isOrg}
allOptions={allOptions}
eventTypeOptions={eventTypeOptions}
onSaveWorkflow={props.onSaveWorkflow}
actionOptions={transformedActionOptions}
updateTemplate={updateTemplate}
setUpdateTemplate={setUpdateTemplate}
/>
</FormCardBody>
</FormCard>
<div className="mt-0! ml-7 h-3 w-2 border-l" />
{form.getValues("steps") && (
<div className="">
{form.getValues("steps")?.map((step, index) => {
const agentData = agentQueriesTrpc[index]?.data;
const isAgentLoading = agentQueriesTrpc[index]?.isPending;
const inboundAgentData = inboundAgentQueriesTrpc[index]?.data;
const isInboundAgentLoading = inboundAgentQueriesTrpc[index]?.isPending;
return (
<div key={index}>
<FormCard
key={step.id}
className="bg-cal-muted border-muted mb-0"
collapsible={false}
label={
<div className="flex items-center gap-2 pt-1 pb-2">
<div className="border-subtle text-subtle rounded-lg border p-1">
<Icon name="arrow-right" size="16" />
</div>
<div className="text-sm font-medium leading-none">{t("action")}</div>
</div>
}
deleteField={
!permissions.readOnly
? {
color: "destructive",
check: () => true,
disabled: !permissions.canUpdate,
fn: () => {
if (
isCalAIAction(step.action) &&
agentData?.outboundPhoneNumbers &&
agentData.outboundPhoneNumbers.length > 0
) {
setIsDeleteStepDialogOpen(true);
} else {
const steps = form.getValues("steps");
const updatedSteps = steps
?.filter((currStep) => currStep.id !== step.id)
.map((s) => {
const updatedStep = s;
if (step.stepNumber < updatedStep.stepNumber) {
updatedStep.stepNumber = updatedStep.stepNumber - 1;
}
return updatedStep;
});
form.setValue("steps", updatedSteps);
if (setReload) {
setReload(!reload);
}
}
},
}
: null
}>
<FormCardBody className="border-muted">
<WorkflowStepContainer
form={form}
user={props.user}
step={step}
reload={reload}
setReload={setReload}
teamId={teamId}
readOnly={permissions.readOnly}
eventTypeOptions={eventTypeOptions}
onSaveWorkflow={props.onSaveWorkflow}
setIsDeleteStepDialogOpen={setIsDeleteStepDialogOpen}
isDeleteStepDialogOpen={isDeleteStepDialogOpen}
isAgentLoading={isAgentLoading}
agentData={agentData}
inboundAgentData={inboundAgentData}
isInboundAgentLoading={isInboundAgentLoading}
allOptions={allOptions}
actionOptions={transformedActionOptions}
updateTemplate={updateTemplate}
setUpdateTemplate={setUpdateTemplate}
/>
</FormCardBody>
</FormCard>
{index !== form.getValues("steps").length - 1 && (
<div className="border-default mt-0! ml-7 h-3 w-2 border-l" />
)}
</div>
);
})}
</div>
)}
{!permissions.readOnly && (
<>
<div className="border-default mt-0! ml-7 h-3 w-2 border-l" />
<Button
type="button"
onClick={() => setIsAddActionDialogOpen(true)}
color="secondary"
className="bg-default">
{t("add_action")}
</Button>
</>
)}
</div>
<AddActionDialog
isOpenDialog={isAddActionDialogOpen}
setIsOpenDialog={setIsAddActionDialogOpen}
addAction={addAction}
actionOptions={transformedActionOptions}
/>
</>
);
}
@@ -0,0 +1,319 @@
import { useAutoAnimate } from "@formkit/auto-animate/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { getActionIcon } from "@calcom/features/ee/workflows/lib/getActionIcon";
import type { WorkflowListType } from "@calcom/features/ee/workflows/lib/types";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
import { ArrowButton } from "@calcom/ui/components/arrow-button";
import { Avatar } from "@calcom/ui/components/avatar";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
import {
Dropdown,
DropdownItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@calcom/ui/components/dropdown";
import { Icon } from "@calcom/ui/components/icon";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { DeleteDialog } from "./DeleteDialog";
/** @deprecated Use WorkflowListType from ../lib/types instead */
export type WorkflowType = WorkflowListType;
interface Props {
workflows: WorkflowType[] | undefined;
}
export default function WorkflowListPage({ workflows }: Props) {
const { t } = useLocale();
const utils = trpc.useUtils();
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [workflowToDeleteId, setwWorkflowToDeleteId] = useState(0);
const [parent] = useAutoAnimate<HTMLUListElement>();
const router = useRouter();
const mutation = trpc.viewer.workflows.workflowOrder.useMutation({
onError: async (err) => {
console.error(err.message);
await utils.viewer.workflows.filteredList.cancel();
await utils.viewer.workflows.filteredList.invalidate();
},
onSettled: () => {
utils.viewer.workflows.filteredList.invalidate();
},
});
async function moveWorkflow(index: number, increment: 1 | -1) {
const types = workflows!;
const newList = [...types];
const type = types[index];
const tmp = types[index + increment];
if (tmp) {
newList[index] = tmp;
newList[index + increment] = type;
}
await utils.viewer.appRoutingForms.forms.cancel();
mutation.mutate({
ids: newList?.map((type) => type.id),
});
}
return (
<>
{workflows && workflows.length > 0 ? (
<div className="bg-default border-subtle overflow-hidden rounded-md border sm:mx-0">
<ul className="divide-subtle static! w-full divide-y" data-testid="workflow-list" ref={parent}>
{workflows.map((workflow, index) => {
const firstItem = workflows[0];
const lastItem = workflows[workflows.length - 1];
const dataTestId = `workflow-${workflow.name.toLowerCase().replaceAll(" ", "-")}`;
return (
<li
key={workflow.id}
data-testid={dataTestId}
className="group flex w-full max-w-full items-center justify-between overflow-hidden">
{!(firstItem && firstItem.id === workflow.id) && (
<ArrowButton onClick={() => moveWorkflow(index, -1)} arrowDirection="up" />
)}
{!(lastItem && lastItem.id === workflow.id) && (
<ArrowButton onClick={() => moveWorkflow(index, 1)} arrowDirection="down" />
)}
<div className="first-line:group hover:bg-cal-muted flex w-full items-center justify-between p-4 transition sm:px-6">
<Link href={`/workflows/${workflow.id}`} className="grow cursor-pointer">
<div className="rtl:space-x-reverse">
<div className="flex">
<div
className={classNames(
"max-w-56 text-emphasis truncate text-sm font-medium leading-6 md:max-w-max",
workflow.name ? "text-emphasis" : "text-subtle"
)}>
{workflow.name
? workflow.name
: workflow.steps[0]
? `Untitled (${`${t(`${workflow.steps[0].action.toLowerCase()}_action`)}`
.charAt(0)
.toUpperCase()}${`${t(
`${workflow.steps[0].action.toLowerCase()}_action`
)}`.slice(1)})`
: "Untitled"}
</div>
<div>
{(workflow.permissions?.readOnly ?? workflow.readOnly) && (
<Badge variant="gray" className="ml-2 ">
{t("readonly")}
</Badge>
)}
</div>
</div>
<ul className="mt-1 flex flex-wrap space-x-2 sm:flex-nowrap ">
<li>
<Badge variant="gray">
<div>
{getActionIcon(workflow.steps)}
<span className="mr-1">{t("triggers")}</span>
{workflow.timeUnit && workflow.time && (
<span className="mr-1">
{t(`${workflow.timeUnit.toLowerCase()}`, { count: workflow.time })}
</span>
)}
<span>{t(`${workflow.trigger.toLowerCase()}_trigger`)}</span>
</div>
</Badge>
</li>
<li>
<Badge variant="gray">
{/*active on all badge */}
{workflow.isActiveOnAll ? (
<div>
<Icon name="link" className="mr-1.5 inline h-3 w-3" aria-hidden="true" />
{workflow.isOrg ? t("active_on_all_teams") : t("active_on_all_event_types")}
</div>
) : workflow.activeOn && workflow.activeOn.length > 0 ? (
//active on event types badge
<Tooltip
content={workflow.activeOn
.filter((wf) => (workflow.teamId ? wf.eventType.parentId === null : true))
.map((activeOn, key) => (
<p key={key}>
{activeOn.eventType.title}
{activeOn.eventType._count.children > 0
? ` (+${activeOn.eventType._count.children})`
: ""}
</p>
))}>
<div>
<Icon name="link" className="mr-1.5 inline h-3 w-3" aria-hidden="true" />
{t("active_on_event_types", {
count: workflow.activeOn.filter((wf) =>
workflow.teamId ? wf.eventType.parentId === null : true
).length,
})}
</div>
</Tooltip>
) : workflow.activeOnTeams && workflow.activeOnTeams.length > 0 ? (
//active on teams badge
<Tooltip
content={workflow.activeOnTeams.map((activeOn, key) => (
<p key={key}>{activeOn.team.name}</p>
))}>
<div>
<Icon name="link" className="mr-1.5 inline h-3 w-3" aria-hidden="true" />
{t("active_on_teams", {
count: workflow.activeOnTeams?.length,
})}
</div>
</Tooltip>
) : (
// active on no teams or event types
<div>
<Icon name="link" className="mr-1.5 inline h-3 w-3" aria-hidden="true" />
{workflow.isOrg ? t("no_active_teams") : t("no_active_event_types")}
</div>
)}
</Badge>
</li>
<div className="block md:hidden">
{workflow.team?.name && (
<li>
<Badge variant="gray">
<>{workflow.team.name}</>
</Badge>
</li>
)}
</div>
</ul>
</div>
</Link>
<div>
<div className="hidden md:block">
{workflow.team?.name && (
<Badge className="mb-2 mr-4 mt-1 p-px px-2" variant="gray">
<Avatar
alt={workflow.team?.name || ""}
href={
workflow.team?.id
? `/settings/teams/${workflow.team?.id}/profile`
: "/settings/my-account/profile"
}
imageSrc={getPlaceholderAvatar(
workflow?.team.logo,
workflow.team?.name as string
)}
size="xs"
className="mt-[3px] inline-flex justify-center"
/>
<div>{workflow.team.name}</div>
</Badge>
)}
</div>
</div>
<div className="flex shrink-0">
<div className="hidden sm:block">
<ButtonGroup combined>
<Tooltip content={t("edit") as string}>
<Button
type="button"
color="secondary"
variant="icon"
StartIcon="pencil"
disabled={
workflow.permissions ? !workflow.permissions?.canUpdate : workflow.readOnly
}
onClick={async () => await router.replace(`/workflows/${workflow.id}`)}
data-testid="edit-button"
/>
</Tooltip>
<Tooltip content={t("delete") as string}>
<Button
onClick={() => {
setDeleteDialogOpen(true);
setwWorkflowToDeleteId(workflow.id);
}}
color="destructive"
variant="icon"
disabled={
workflow.permissions ? !workflow.permissions?.canDelete : workflow.readOnly
}
StartIcon="trash-2"
data-testid="delete-button"
/>
</Tooltip>
</ButtonGroup>
</div>
{(workflow.permissions?.canUpdate ||
workflow.permissions?.canDelete ||
(!workflow.permissions && !workflow.readOnly)) && (
<div className="block sm:hidden">
<Dropdown>
<DropdownMenuTrigger asChild>
<Button type="button" color="minimal" variant="icon" StartIcon="ellipsis" />
</DropdownMenuTrigger>
<DropdownMenuContent>
{(workflow.permissions
? workflow.permissions?.canUpdate
: !workflow.readOnly) && (
<DropdownMenuItem>
<DropdownItem
type="button"
StartIcon="pencil"
onClick={async () => await router.replace(`/workflows/${workflow.id}`)}>
{t("edit")}
</DropdownItem>
</DropdownMenuItem>
)}
{(workflow.permissions
? workflow.permissions?.canDelete
: !workflow.readOnly) && (
<DropdownMenuItem>
<DropdownItem
type="button"
color="destructive"
StartIcon="trash-2"
onClick={() => {
setDeleteDialogOpen(true);
setwWorkflowToDeleteId(workflow.id);
}}>
{t("delete")}
</DropdownItem>
</DropdownMenuItem>
)}
</DropdownMenuContent>
</Dropdown>
</div>
)}
</div>
</div>
</li>
);
})}
</ul>
<DeleteDialog
isOpenDialog={deleteDialogOpen}
setIsOpenDialog={setDeleteDialogOpen}
workflowId={workflowToDeleteId}
additionalFunction={async () => {
await utils.viewer.workflows.filteredList.invalidate();
}}
/>
</div>
) : (
<></>
)}
</>
);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,389 @@
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import type { Language } from "@calcom/features/calAIPhone/providers/retellAI/types";
import { restorePromptComplexity } from "@calcom/features/calAIPhone/providers/retellAI/utils/promptUtils";
import type { FormValues } from "@calcom/features/ee/workflows/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import {
Dropdown,
DropdownItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@calcom/ui/components/dropdown";
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
import { ToggleGroup } from "@calcom/ui/components/form";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetBody,
SheetFooter,
} from "@calcom/ui/components/sheet";
import { showToast } from "@calcom/ui/components/toast";
import { WebCallDialog } from "../WebCallDialog";
import { IncomingCallsTab } from "./components/tabs/IncomingCallsTab";
import { OutgoingCallsTab } from "./components/tabs/OutgoingCallsTab";
import { PhoneNumberTab } from "./components/tabs/PhoneNumberTab";
import { useAgentForms } from "./hooks/useAgentForms";
import type { AgentFormValues } from "./types/schemas";
type AgentConfigurationSheetProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
agentId?: string | null;
inboundAgentId?: string | null;
agentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
inboundAgentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
onUpdate: (data: AgentFormValues & { id: string }) => void;
readOnly?: boolean;
teamId?: number;
isOrganization?: boolean;
workflowId?: string;
workflowStepId?: number;
activeTab?: "outgoingCalls" | "phoneNumber" | "incomingCalls";
form: UseFormReturn<FormValues>;
eventTypeOptions?: Option[];
};
export function AgentConfigurationSheet({
open,
activeTab: _activeTab,
onOpenChange,
agentId,
inboundAgentId,
agentData,
inboundAgentData,
readOnly = false,
teamId,
isOrganization = false,
workflowId,
workflowStepId,
form,
eventTypeOptions = [],
}: AgentConfigurationSheetProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const [activeTab, setActiveTab] = useState<"outgoingCalls" | "phoneNumber" | "incomingCalls">(
_activeTab ?? "outgoingCalls"
);
const [isWebCallDialogOpen, setIsWebCallDialogOpen] = useState(false);
const activeAgentId = activeTab === "incomingCalls" ? inboundAgentId : agentId;
const { outboundAgentForm, inboundAgentForm } = useAgentForms({ agentData, inboundAgentData });
const trigger = form.watch("trigger");
const updateAgentMutation = trpc.viewer.aiVoiceAgent.update.useMutation({
onSuccess: async () => {
if (activeAgentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: activeAgentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const handleAgentUpdate = async (data: AgentFormValues) => {
if (!agentId) return;
if (trigger === "FORM_SUBMITTED" && !data.outboundEventTypeId) {
showToast(t("select_event_type_to_schedule_calls"), "error");
return;
}
const updatePayload = {
generalPrompt: restorePromptComplexity(data.generalPrompt),
beginMessage: data.beginMessage,
language: data.language as Language,
voiceId: data.voiceId,
outboundEventTypeId: data.outboundEventTypeId,
};
await updateAgentMutation.mutateAsync({
id: agentId,
teamId: teamId,
...updatePayload,
});
};
const handleInboundAgentUpdate = async (data: AgentFormValues) => {
if (!inboundAgentId) return;
const updatePayload = {
generalPrompt: restorePromptComplexity(data.generalPrompt),
beginMessage: data.beginMessage,
language: data.language as Language,
voiceId: data.voiceId,
};
await updateAgentMutation.mutateAsync({
id: inboundAgentId,
teamId: teamId,
...updatePayload,
});
};
return (
<>
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="sm:max-w-xl">
<SheetHeader showCloseButton={false} className="w-full">
<SheetTitle className="mb-6">{t("cal_ai_agent_configuration")}</SheetTitle>
<ToggleGroup
onValueChange={(val) => {
setActiveTab((val || "outgoingCalls") as "outgoingCalls" | "phoneNumber" | "incomingCalls");
}}
value={activeTab}
options={[
{ value: "outgoingCalls", label: t("outgoing_calls") },
{ value: "phoneNumber", label: t("phone_number") },
{ value: "incomingCalls", label: t("incoming_calls") },
]}
isFullWidth={true}
/>
</SheetHeader>
<SheetBody className="px-0">
{activeTab === "outgoingCalls" && (
<OutgoingCallsTab
outboundAgentForm={outboundAgentForm}
readOnly={readOnly}
eventTypeOptions={eventTypeOptions}
trigger={trigger}
/>
)}
{activeTab === "phoneNumber" && (
<PhoneNumberTab
agentData={agentData}
agentId={agentId}
readOnly={readOnly}
teamId={teamId}
workflowId={workflowId}
isOrganization={isOrganization}
form={form}
eventTypeIds={eventTypeOptions?.map((opt) => parseInt(opt.value, 10))}
/>
)}
{activeTab === "incomingCalls" && (
<IncomingCallsTab
agentData={agentData}
inboundAgentData={inboundAgentData}
inboundAgentId={inboundAgentId}
inboundAgentForm={inboundAgentForm}
form={form}
eventTypeOptions={eventTypeOptions}
readOnly={readOnly}
teamId={teamId}
workflowStepId={workflowStepId}
/>
)}
</SheetBody>
<SheetFooter>
<div className="mr-auto">
<Dropdown>
<DropdownMenuTrigger asChild>
<Button
color="secondary"
className="rounded-[10px]"
disabled={readOnly}
EndIcon="chevron-down">
{t("test_agent")}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>
<DropdownItem
type="button"
StartIcon="monitor"
onClick={() => {
setIsWebCallDialogOpen(true);
}}>
{t("web_call")}
</DropdownItem>
</DropdownMenuItem>
</DropdownMenuContent>
</Dropdown>
</div>
<Button
className="justify-center"
type="button"
color="secondary"
onClick={() => onOpenChange(false)}>
{t("cancel")}
</Button>
<Button
type="button"
className="justify-center"
onClick={() => {
if (activeTab === "incomingCalls" && inboundAgentId) {
inboundAgentForm.handleSubmit(handleInboundAgentUpdate)();
} else if (activeTab === "outgoingCalls" && agentId) {
outboundAgentForm.handleSubmit(handleAgentUpdate)();
}
}}
disabled={
readOnly ||
updateAgentMutation.isPending ||
(activeTab === "outgoingCalls" && !outboundAgentForm.formState.isDirty) ||
(activeTab === "incomingCalls" && !inboundAgentForm.formState.isDirty) ||
(activeTab === "outgoingCalls" && !agentId) ||
(activeTab === "incomingCalls" && !inboundAgentId)
}
loading={updateAgentMutation.isPending}>
{t("save")}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
{activeAgentId && (
<WebCallDialog
open={isWebCallDialogOpen}
onOpenChange={setIsWebCallDialogOpen}
agentId={activeAgentId}
teamId={teamId}
isOrganization={isOrganization}
form={form}
eventTypeIds={eventTypeOptions?.map((opt) => parseInt(opt.value, 10))}
outboundEventTypeId={agentData?.outboundEventTypeId}
/>
)}
{/* <ToolsDialog
open={toolDialogOpen}
onOpenChange={setToolDialogOpen}
toolDraft={toolDraft}
setToolDraft={setToolDraft}
onSave={handleToolDialogSave}
isEditing={editingToolIndex !== null}
/> */}
</>
);
}
// const ToolsDialog = ({
// open,
// onOpenChange,
// toolDraft,
// setToolDraft,
// onSave,
// isEditing,
// }: {
// open: boolean;
// onOpenChange: (open: boolean) => void;
// toolDraft: ToolDraft | null;
// setToolDraft: (draft: ToolDraft) => void;
// onSave: () => void;
// isEditing: boolean;
// }) => {
// const { t } = useLocale();
// const TOOL_TYPES = [
// { label: t("Check Availability"), value: "check_availability_cal" },
// { label: t("Book Appointment"), value: "book_appointment_cal" },
// { label: t("End Call"), value: "end_call" },
// ];
// return (
// <Dialog open={open} onOpenChange={onOpenChange}>
// <DialogContent
// enableOverflow
// title={isEditing ? t("Edit Function") : t("Add Function")}
// type="creation">
// <div className="flex flex-col gap-4">
// <div>
// <Label>{t("Type")}</Label>
// <Select
// options={TOOL_TYPES}
// value={TOOL_TYPES.find((opt) => opt.value === toolDraft?.type) || null}
// onChange={(option) => setToolDraft((d: ToolDraft) => ({ ...d, type: option?.value || "" }))}
// placeholder={t("Select function type")}
// />
// </div>
// <div>
// <Label>{t("Name")}</Label>
// <TextField
// required
// value={toolDraft?.name || ""}
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, name: e.target.value }))}
// placeholder={t("Enter function name")}
// />
// </div>
// <div>
// <Label>{t("Description")}</Label>
// <TextArea
// value={toolDraft?.description || ""}
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, description: e.target.value }))}
// placeholder={t("Enter description (optional)")}
// />
// </div>
// {(toolDraft?.type === "check_availability_cal" || toolDraft?.type === "book_appointment_cal") && (
// <>
// <div>
// <Label>
// {t("API Key (Cal.com)")}
// <span className="text-red-500"> *</span>
// </Label>
// <TextField
// required
// value={toolDraft?.cal_api_key || ""}
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, cal_api_key: e.target.value }))}
// placeholder={t("Enter Cal.com API key")}
// />
// </div>
// <div>
// <Label>
// {t("Event Type ID (Cal.com)")}
// <span className="text-red-500"> *</span>
// </Label>
// <TextField
// required
// value={toolDraft?.event_type_id || ""}
// onChange={(e) =>
// setToolDraft((d: ToolDraft) => ({
// ...d,
// event_type_id: e.target.value ? Number(e.target.value) : null,
// }))
// }
// placeholder={t("Enter Event Type ID")}
// type="number"
// />
// </div>
// <div>
// <Label>
// {t("Timezone")}
// <span className="text-red-500"> *</span>
// </Label>
// <TextField
// required
// value={toolDraft?.timezone || ""}
// onChange={(e) => setToolDraft((d: ToolDraft) => ({ ...d, timezone: e.target.value }))}
// placeholder={t("America/Los_Angeles")}
// />
// <p className="mt-1 text-xs text-subtle">{t("Required for Cal.com calendar integration")}</p>
// </div>
// </>
// )}
// </div>
// <DialogFooter showDivider>
// <Button type="button" color="secondary" onClick={() => onOpenChange(false)}>
// {t("Cancel")}
// </Button>
// <Button type="button" onClick={onSave}>
// {t("Save")}
// </Button>
// </DialogFooter>
// </DialogContent>
// </Dialog>
// );
// };
@@ -0,0 +1,140 @@
"use client";
import posthog from "posthog-js";
import { CAL_AI_PHONE_NUMBER_MONTHLY_PRICE } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { Dialog } from "@calcom/ui/components/dialog";
import { DialogContent, DialogHeader, DialogFooter as BaseDialogFooter } from "@calcom/ui/components/dialog";
import { Label } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
interface BuyNumberDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
agentId?: string | null;
workflowId?: string;
teamId?: number;
}
export function BuyNumberDialog({ open, onOpenChange, agentId, workflowId, teamId }: BuyNumberDialogProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const buyNumberMutation = trpc.viewer.phoneNumber.buy.useMutation({
onSuccess: async (data: { checkoutUrl?: string; message?: string; phoneNumber?: unknown }) => {
if (data.checkoutUrl) {
window.location.href = data.checkoutUrl;
} else if (data.phoneNumber) {
showToast(t("phone_number_purchased_successfully"), "success");
posthog.capture("calai_phone_number_purchased");
await utils.viewer.me.get.invalidate();
onOpenChange(false);
if (agentId) {
utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
} else {
showToast(data.message || t("something_went_wrong"), "error");
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent type="creation">
<DialogHeader
title={t("buy_a_new_number")}
subtitle={t("buy_number_for_x_per_month", {
priceInDollars: CAL_AI_PHONE_NUMBER_MONTHLY_PRICE,
})}
/>
<div className="flex flex-col">
<div>
<div>
<Alert
className="mb-4"
severity="info"
message={t("only_us_phone_numbers_can_be_purchased_here")}
/>
<Label>{t("supported_call_destinations")}</Label>
<div className="-mb-4 grid grid-cols-2 gap-x-8 gap-y-1 text-sm">
<div className="flex items-center gap-2">
<span className="text-xl">🇺🇸</span>
<span className="text-default">United States</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇮🇳</span>
<span className="text-default">India</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇦🇺</span>
<span className="text-default">Australia</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇩🇪</span>
<span className="text-default">Germany</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇪🇸</span>
<span className="text-default">Spain</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇬🇧</span>
<span className="text-default">United Kingdom</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇲🇽</span>
<span className="text-default">Mexico</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇫🇷</span>
<span className="text-default">France</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇯🇵</span>
<span className="text-default">Japan</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇨🇦</span>
<span className="text-default">Canada</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xl">🇮🇹</span>
<span className="text-default">Italy</span>
</div>
</div>
</div>
</div>
<BaseDialogFooter showDivider className="relative">
<Button onClick={() => onOpenChange(false)} color="secondary">
{t("close")}
</Button>
<Button
StartIcon="external-link"
onClick={() => {
if (!agentId || !workflowId) {
return;
}
posthog.capture("calai_buy_number_button_clicked", { agentId, workflowId, teamId });
buyNumberMutation.mutate({
agentId: agentId,
workflowId: workflowId,
teamId: teamId ?? undefined,
});
}}
loading={buyNumberMutation.isPending}
disabled={buyNumberMutation.isPending}>
{t("buy_us_number_button", { priceInDollars: CAL_AI_PHONE_NUMBER_MONTHLY_PRICE })}
</Button>
</BaseDialogFooter>
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,95 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
import { Dialog as UIDialog } from "@calcom/ui/components/dialog";
import { showToast } from "@calcom/ui/components/toast";
interface ConfirmationDialogsProps {
cancellingNumberId: number | null;
setCancellingNumberId: (id: number | null) => void;
numberToDelete: string | null;
setNumberToDelete: (number: string | null) => void;
agentId?: string | null;
}
export function ConfirmationDialogs({
cancellingNumberId,
setCancellingNumberId,
numberToDelete,
setNumberToDelete,
agentId,
}: ConfirmationDialogsProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const cancelSubscriptionMutation = trpc.viewer.phoneNumber.cancel.useMutation({
onSuccess: async (data: { message?: string }) => {
showToast(data.message || t("phone_number_subscription_cancelled_successfully"), "success");
setCancellingNumberId(null);
await utils.viewer.me.get.invalidate();
if (agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
setCancellingNumberId(null);
},
});
const deletePhoneNumberMutation = trpc.viewer.phoneNumber.delete.useMutation({
onSuccess: async () => {
showToast(t("phone_number_deleted_successfully"), "success");
setNumberToDelete(null);
if (agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
setNumberToDelete(null);
},
});
const confirmCancelSubscription = () => {
if (cancellingNumberId) {
cancelSubscriptionMutation.mutate({ phoneNumberId: cancellingNumberId });
}
};
const confirmDeletePhoneNumber = () => {
if (numberToDelete) {
deletePhoneNumberMutation.mutate({ phoneNumber: numberToDelete });
}
};
return (
<>
<UIDialog open={cancellingNumberId !== null} onOpenChange={() => setCancellingNumberId(null)}>
<ConfirmationDialogContent
isPending={cancelSubscriptionMutation.isPending}
variety="danger"
title={t("cancel_phone_number_subscription")}
confirmBtnText={t("yes_cancel_subscription")}
onConfirm={confirmCancelSubscription}>
{t("cancel_phone_number_subscription_confirmation")}
</ConfirmationDialogContent>
</UIDialog>
<UIDialog open={numberToDelete !== null} onOpenChange={() => setNumberToDelete(null)}>
<ConfirmationDialogContent
isPending={deletePhoneNumberMutation.isPending}
variety="danger"
title={t("delete_phone_number")}
confirmBtnText={t("yes_delete_phone_number")}
onConfirm={confirmDeletePhoneNumber}>
{t("delete_phone_number_confirmation")}
</ConfirmationDialogContent>
</UIDialog>
</>
);
}
@@ -0,0 +1,252 @@
"use client";
import { Controller } from "react-hook-form";
import type { UseFormReturn } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Dialog } from "@calcom/ui/components/dialog";
import { DialogContent, DialogHeader, DialogFooter as BaseDialogFooter } from "@calcom/ui/components/dialog";
import { Form, Label, Switch, TextField } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
import type { PhoneNumberFormValues } from "../../types/schemas";
interface ImportNumberDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
phoneNumberForm: UseFormReturn<PhoneNumberFormValues>;
showAdvancedFields: boolean;
setShowAdvancedFields: (show: boolean) => void;
agentId?: string | null;
workflowId?: string;
teamId?: number;
}
export function ImportNumberDialog({
open,
onOpenChange,
phoneNumberForm,
showAdvancedFields,
setShowAdvancedFields,
agentId,
workflowId,
teamId,
}: ImportNumberDialogProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const importNumberMutation = trpc.viewer.phoneNumber.import.useMutation({
onSuccess: async () => {
showToast(t("phone_number_imported_successfully"), "success");
onOpenChange(false);
phoneNumberForm.reset();
await utils.viewer.me.get.invalidate();
if (agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const handleImportPhoneNumber = (values: PhoneNumberFormValues) => {
if (!agentId) {
showToast(t("agent_required_for_import"), "error");
return;
}
const mutationPayload = {
...values,
workflowId: workflowId,
agentId: agentId,
teamId: teamId,
};
importNumberMutation.mutate(mutationPayload);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent enableOverflow type="creation">
<DialogHeader title={t("import_phone_number")} subtitle={t("import_phone_number_description")} />
<Form form={phoneNumberForm} handleSubmit={(values) => handleImportPhoneNumber(values)}>
<div className="stack-y-6">
<Controller
name="phoneNumber"
control={phoneNumberForm.control}
render={({ field: { value } }) => (
<TextField
name="phoneNumber"
label={
<span className="flex items-center gap-1">
{t("phone_number")}
<Tooltip content={t("phone_number_info_tooltip")}>
<Icon name="info" className="text-muted h-4 w-4 cursor-pointer" />
</Tooltip>
</span>
}
value={value}
required
type="text"
placeholder="eg:- +12088782105"
onChange={(e) => {
phoneNumberForm.setValue("phoneNumber", e?.target.value, { shouldDirty: true });
}}
/>
)}
/>
<Controller
name="terminationUri"
control={phoneNumberForm.control}
render={({ field: { value } }) => (
<TextField
name="terminationUri"
label={
<span className="flex items-center gap-1">
{t("termination_uri")}
<Tooltip content={t("termination_uri_info_tooltip")}>
<Icon name="info" className="text-muted h-4 w-4 cursor-pointer" />
</Tooltip>
</span>
}
value={value}
required
type="text"
placeholder="sip.example.co.pstn.twilio.com"
onChange={(e) => {
phoneNumberForm.setValue("terminationUri", e?.target.value, { shouldDirty: true });
}}
/>
)}
/>
<div className="bg-cal-muted rounded-xl p-1">
<div className="flex items-center justify-between p-2">
<Label className="text-emphasis mb-0 text-sm font-medium leading-none">{t("advanced")}</Label>
<Switch size="sm" checked={showAdvancedFields} onCheckedChange={setShowAdvancedFields} />
</div>
{showAdvancedFields && (
<div className="bg-default stack-y-5 rounded-lg p-4">
<Controller
name="sipTrunkAuthUsername"
control={phoneNumberForm.control}
render={({ field: { value } }) => (
<TextField
name="sipTrunkAuthUsername"
label={
<span className="flex items-center gap-1">
{t("sip_trunk_username")}
<Tooltip content={t("sip_trunk_username_info_tooltip")}>
<Icon name="info" className="text-muted h-4 w-4 cursor-pointer" />
</Tooltip>
</span>
}
value={value}
type="text"
onChange={(e) => {
phoneNumberForm.setValue("sipTrunkAuthUsername", e?.target.value, {
shouldDirty: true,
});
}}
/>
)}
/>
<Controller
name="sipTrunkAuthPassword"
control={phoneNumberForm.control}
render={({ field: { value } }) => (
<TextField
name="sipTrunkAuthPassword"
label={
<span className="flex items-center gap-1">
{t("sip_trunk_password")}
<Tooltip content={t("sip_trunk_password_info_tooltip")}>
<Icon name="info" className="text-muted h-4 w-4 cursor-pointer" />
</Tooltip>
</span>
}
value={value}
type="password"
onChange={(e) => {
phoneNumberForm.setValue("sipTrunkAuthPassword", e?.target.value, {
shouldDirty: true,
});
}}
/>
)}
/>
<Controller
name="nickname"
control={phoneNumberForm.control}
render={({ field: { value } }) => (
<TextField
name="nickname"
label={
<span className="flex items-center gap-1">
{t("nickname")}
<Tooltip content={t("nickname_info_tooltip")}>
<Icon name="info" className="text-muted h-4 w-4 cursor-pointer" />
</Tooltip>
</span>
}
value={value}
type="text"
onChange={(e) => {
phoneNumberForm.setValue("nickname", e?.target.value, { shouldDirty: true });
}}
/>
)}
/>
</div>
)}
</div>
{/* Having trouble importing section */}
<div className="rounded-lg border p-2">
<div className="flex items-start gap-3">
<Icon name="info" className="text-subtle mt-0.5 h-5 w-5 shrink-0" />
<div className="flex-1">
<p className="text-emphasis text-sm font-medium">{t("having_trouble_importing")}</p>
<p className="text-subtle mt-1 text-sm leading-tight">
{t("learn_how_to_get_your_terminator")}
</p>
</div>
<Button
type="button"
color="secondary"
size="base"
EndIcon="external-link"
href="https://cal.com/help/importing/import-numbers"
target="_blank"
className="text-emphasis my-auto">
{t("learn")}
</Button>
</div>
</div>
</div>
<BaseDialogFooter showDivider className="relative">
<Button onClick={() => onOpenChange(false)} color="secondary">
{t("cancel")}
</Button>
<Button
type="submit"
loading={importNumberMutation.isPending}
disabled={importNumberMutation.isPending}>
{t("create")}
</Button>
</BaseDialogFooter>
</Form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,178 @@
"use client";
import { useRef } from "react";
import type { UseFormReturn } from "react-hook-form";
import { DYNAMIC_TEXT_VARIABLES } from "@calcom/features/ee/workflows/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { AddVariablesDropdown } from "@calcom/ui/components/editor";
import { Input, Label, TextArea } from "@calcom/ui/components/form";
import type { AgentFormValues } from "../../types/schemas";
import { LanguageSelector } from "./LanguageSelector";
import { VoiceSelector } from "./VoiceSelector";
interface AgentConfigFormProps {
form: UseFormReturn<AgentFormValues>;
readOnly?: boolean;
selectedVoiceId?: string;
onVoiceDialogOpen: () => void;
}
export function AgentConfigForm({
form,
readOnly = false,
selectedVoiceId,
onVoiceDialogOpen,
}: AgentConfigFormProps) {
const { t } = useLocale();
const generalPromptRef = useRef<HTMLTextAreaElement | null>(null);
const addVariableToGeneralPrompt = (variable: string) => {
if (generalPromptRef.current) {
const currentPrompt = generalPromptRef.current.value || "";
const cursorPosition = generalPromptRef.current.selectionStart || currentPrompt.length;
const variableName = `{${variable.toUpperCase().replace(/ /g, "_")}}`;
const newPrompt = `${currentPrompt.substring(
0,
cursorPosition
)}${variableName}${currentPrompt.substring(cursorPosition)}`;
form.setValue("generalPrompt", newPrompt, { shouldDirty: true, shouldTouch: true });
requestAnimationFrame(() => {
if (generalPromptRef.current) {
generalPromptRef.current.focus();
generalPromptRef.current.setSelectionRange(
cursorPosition + variableName.length,
cursorPosition + variableName.length
);
}
});
}
};
return (
<div className="stack-y-4">
<LanguageSelector control={form.control} name="language" disabled={readOnly} />
<VoiceSelector
selectedVoiceId={selectedVoiceId}
onVoiceDialogOpen={onVoiceDialogOpen}
disabled={readOnly}
/>
<div>
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("initial_message")} *</Label>
<p className="text-subtle mb-1.5 text-xs">{t("initial_message_description")}</p>
<Input
type="text"
{...form.register("beginMessage")}
placeholder={t("hi_how_are_you_doing")}
disabled={readOnly}
/>
</div>
<div>
<div className="mb-1.5">
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("general_prompt")} *</Label>
<p className="text-subtle text-xs">{t("general_prompt_description")}</p>
</div>
<div className="flex items-center justify-between rounded-t-lg border border-b-0 p-2">
{!readOnly && (
<AddVariablesDropdown
addVariable={addVariableToGeneralPrompt}
variables={[...DYNAMIC_TEXT_VARIABLES, "number_to_call"]}
addVariableButtonClassName="border rounded-[10px] py-1 px-1"
/>
)}
</div>
<TextArea
{...form.register("generalPrompt")}
ref={(e) => {
form.register("generalPrompt").ref(e);
generalPromptRef.current = e;
}}
placeholder={t("enter_the_general_prompt_for_the_agent")}
className="min-h-[500px] rounded-t-none"
disabled={readOnly}
/>
</div>
{/* Commented code for future tools implementation */}
{/* <div className="p-4 rounded-lg border border-subtle bg-default">
<div className="flex justify-between items-center mb-4">
<div>
<h4 className="text-sm font-medium text-emphasis">{t("Functions")}</h4>
<p className="text-xs text-subtle">
{t(
"Enable your agent with capabilities such as calendar bookings, call termination, etc."
)}
</p>
</div>
<Button
type="button"
onClick={openAddToolDialog}
color="secondary"
size="sm"
disabled={readOnly}>
<Icon name="plus" className="mr-2 w-4 h-4" />
{t("Add Function")}
</Button>
</div>
<div className="stack-y-3">
{toolFields.map((tool, idx) => (
<div
key={tool.id}
className="flex justify-between items-center p-4 rounded-lg border transition-colors border-subtle bg-cal-muted hover:bg-default">
<div className="flex gap-3">
<div className="flex justify-center items-center w-8 h-8 rounded-md border bg-default border-subtle">
<Icon name="zap" className="w-4 h-4 text-emphasis" />
</div>
<div>
<p className="font-medium text-emphasis">{tool.name}</p>
<p className="text-sm text-subtle">
{tool.type === "check_availability_cal" && t("Check Availability")}
{tool.type === "book_appointment_cal" && t("Book Appointment")}
{tool.type === "end_call" && t("End Call")}
</p>
</div>
</div>
<div className="flex gap-2 items-center">
<Button
type="button"
size="sm"
color="secondary"
variant="icon"
onClick={() => openEditToolDialog(idx)}
disabled={readOnly}>
<Icon name="pencil" className="w-4 h-4" />
</Button>
{tool.name !== "end_call" && (
<Button
type="button"
color="destructive"
variant="icon"
size="sm"
onClick={() => handleToolDelete(idx)}
disabled={readOnly}>
<Icon name="trash" className="w-4 h-4" />
</Button>
)}
</div>
</div>
))}
{toolFields.length === 0 && (
<div className="flex flex-col justify-center items-center p-6 text-center rounded-lg border border-subtle bg-cal-muted">
<Icon name="zap" className="w-6 h-6 text-subtle" />
<p className="mt-2 text-sm text-subtle">{t("No functions configured yet")}</p>
<p className="text-xs text-subtle">
{t("Add functions to enable advanced capabilities")}
</p>
</div>
)}
</div>
</div> */}
</div>
);
}
@@ -0,0 +1,39 @@
"use client";
import { Controller } from "react-hook-form";
import type { Control } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Label, Select } from "@calcom/ui/components/form";
import type { AgentFormValues } from "../../types/schemas";
import { LANGUAGE_OPTIONS } from "../../utils/constants";
interface LanguageSelectorProps {
control: Control<AgentFormValues>;
name: keyof AgentFormValues;
disabled?: boolean;
}
export function LanguageSelector({ control, name, disabled = false }: LanguageSelectorProps) {
const { t } = useLocale();
return (
<div>
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("language")}</Label>
<Controller
name={name}
control={control}
render={({ field }) => (
<Select
value={LANGUAGE_OPTIONS.find((option) => option.value === field.value)}
onChange={(option) => field.onChange(option?.value)}
options={LANGUAGE_OPTIONS}
isDisabled={disabled}
className="mb-4"
/>
)}
/>
</div>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { Label } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
interface VoiceSelectorProps {
selectedVoiceId?: string;
onVoiceDialogOpen: () => void;
disabled?: boolean;
}
export function VoiceSelector({ selectedVoiceId, onVoiceDialogOpen, disabled = false }: VoiceSelectorProps) {
const { t } = useLocale();
return (
<div>
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("voice")}</Label>
<p className="text-subtle mb-1.5 text-xs">{t("select_voice_for_agent")}</p>
<Button
type="button"
color="secondary"
onClick={onVoiceDialogOpen}
disabled={disabled}
className="w-full justify-start">
<Icon name="user" className="mr-2 h-4 w-4" />
{selectedVoiceId ? <span className="text-sm">{selectedVoiceId}</span> : t("select_voice")}
</Button>
</div>
);
}
@@ -0,0 +1,194 @@
"use client";
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import type { FormValues } from "@calcom/features/ee/workflows/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Label, Select } from "@calcom/ui/components/form";
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { VoiceSelectionDialog } from "../../../VoiceSelectionDialog";
import type { AgentFormValues } from "../../types/schemas";
import { AgentConfigForm } from "../forms/AgentConfigForm";
interface IncomingCallsTabProps {
agentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
inboundAgentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
inboundAgentId?: string | null;
inboundAgentForm: UseFormReturn<AgentFormValues>;
form: UseFormReturn<FormValues>;
eventTypeOptions: Option[];
readOnly?: boolean;
teamId?: number;
workflowStepId?: number;
}
export function IncomingCallsTab({
agentData,
inboundAgentData,
inboundAgentId,
inboundAgentForm,
form,
eventTypeOptions,
readOnly = false,
teamId,
workflowStepId,
}: IncomingCallsTabProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const [isVoiceDialogOpen, setIsVoiceDialogOpen] = useState(false);
const setupInboundAgentMutation = trpc.viewer.aiVoiceAgent.setupInboundAgent.useMutation({
onSuccess: async (data) => {
showToast(t("inbound_agent_setup_success"), "success");
// Update the form with the new inbound agent ID
if (data.agentId && form && workflowStepId) {
const stepIndex = form.getValues("steps")?.findIndex((s) => s.id === workflowStepId);
if (stepIndex !== undefined && stepIndex !== -1) {
form.setValue(`steps.${stepIndex}.inboundAgentId`, data.agentId, { shouldDirty: true });
}
}
// Invalidate and refetch the agent data
if (data.agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: data.agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const updateInboundAgentEventTypeMutation =
trpc.viewer.aiVoiceAgent.updateInboundAgentEventType.useMutation({
onSuccess: async () => {
showToast(t("agent_event_type_updated_successfully"), "success");
if (inboundAgentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: inboundAgentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const hasActivePhoneNumbers =
agentData?.outboundPhoneNumbers &&
agentData.outboundPhoneNumbers.filter(
(phone) =>
phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE || !phone.subscriptionStatus
).length > 0;
if (!hasActivePhoneNumbers) {
return (
<div className="border-subtle rounded-xl border p-8">
<div className="stack-y-6 flex flex-col items-center text-center">
<div className="bg-cal-muted flex h-16 w-16 items-center justify-center rounded-lg">
<Icon name="info" className="text-subtle h-8 w-8" />
</div>
<div className="stack-y-2">
<h3 className="text-emphasis text-lg font-semibold">{t("setup_incoming_agent")}</h3>
<p className="text-subtle text-sm">{t("connect_a_phone_number_first")}</p>
</div>
</div>
</div>
);
}
if (!inboundAgentId) {
return (
<div className="border-subtle rounded-xl border p-8">
<div className="stack-y-6 flex flex-col items-center text-center">
<div className="bg-cal-muted flex h-16 w-16 items-center justify-center rounded-lg">
<Icon name="phone-incoming" className="text-subtle h-8 w-8" />
</div>
<div className="stack-y-2">
<h3 className="text-emphasis text-lg font-semibold">{t("setup_inbound_agent")}</h3>
<p className="text-subtle text-sm">{t("setup_inbound_agent_for_incoming_calls")}</p>
</div>
<Button
onClick={() => {
const phoneNumber = agentData?.outboundPhoneNumbers?.filter(
(phone) =>
phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE ||
!phone.subscriptionStatus
)[0]?.phoneNumber;
if (!phoneNumber) {
showToast(t("no_active_phone_number_available"), "error");
return;
}
if (!workflowStepId) {
showToast(t("workflow_step_not_configured"), "error");
return;
}
setupInboundAgentMutation.mutate({
phoneNumber,
teamId,
workflowStepId: workflowStepId,
});
}}
className="px-6"
loading={setupInboundAgentMutation.isPending}
disabled={setupInboundAgentMutation.isPending || !workflowStepId}>
{t("setup_inbound_agent")}
</Button>
</div>
</div>
);
}
return (
<div className="stack-y-4">
<div>
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("event_type")}</Label>
<p className="text-subtle mb-1.5 text-xs">{t("select_event_type_for_inbound_calls")}</p>
<Select
isSearchable={false}
innerClassNames={{ valueContainer: "font-medium" }}
className="text-sm font-medium"
isDisabled={readOnly || updateInboundAgentEventTypeMutation.isPending}
isLoading={updateInboundAgentEventTypeMutation.isPending}
onChange={(val) => {
if (val && inboundAgentId) {
updateInboundAgentEventTypeMutation.mutate({
agentId: inboundAgentId,
eventTypeId: parseInt(val.value),
teamId,
});
}
}}
value={eventTypeOptions.find(
(opt) => opt.value === inboundAgentData?.inboundEventTypeId?.toString()
)}
options={eventTypeOptions}
placeholder={t("select_event_type")}
/>
</div>
<AgentConfigForm
form={inboundAgentForm}
readOnly={readOnly}
selectedVoiceId={inboundAgentForm.watch("voiceId")}
onVoiceDialogOpen={() => setIsVoiceDialogOpen(true)}
/>
<VoiceSelectionDialog
open={isVoiceDialogOpen}
onOpenChange={setIsVoiceDialogOpen}
selectedVoiceId={inboundAgentForm.watch("voiceId")}
onVoiceSelect={(voiceId: string) => {
inboundAgentForm.setValue("voiceId", voiceId, { shouldDirty: true });
}}
/>
</div>
);
}
@@ -0,0 +1,74 @@
"use client";
import { useState } from "react";
import { Controller } from "react-hook-form";
import type { UseFormReturn } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { WorkflowTriggerEvents } from "@calcom/prisma/enums";
import { Label, Select } from "@calcom/ui/components/form";
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
import { VoiceSelectionDialog } from "../../../VoiceSelectionDialog";
import type { AgentFormValues } from "../../types/schemas";
import { AgentConfigForm } from "../forms/AgentConfigForm";
interface OutgoingCallsTabProps {
outboundAgentForm: UseFormReturn<AgentFormValues>;
readOnly?: boolean;
eventTypeOptions?: Option[];
trigger?: WorkflowTriggerEvents;
}
export function OutgoingCallsTab({
outboundAgentForm,
readOnly = false,
eventTypeOptions = [],
trigger,
}: OutgoingCallsTabProps) {
const [isVoiceDialogOpen, setIsVoiceDialogOpen] = useState(false);
const { t } = useLocale();
return (
<>
{trigger === "FORM_SUBMITTED" && (
<div>
<Label className="text-emphasis mb-1 block text-sm font-medium">{t("event_type")}</Label>
<p className="text-subtle mb-1.5 text-xs">{t("select_event_type_for_outbound_calls")}</p>
<Controller
name="outboundEventTypeId"
control={outboundAgentForm.control}
render={({ field }) => (
<Select
isSearchable={false}
innerClassNames={{ valueContainer: "font-medium" }}
value={eventTypeOptions.find((option) => option.value === field.value?.toString())}
onChange={(option) => field.onChange(option?.value ? parseInt(option.value) : undefined)}
options={eventTypeOptions}
isDisabled={readOnly}
placeholder={t("select_event_type")}
className="mb-4"
/>
)}
/>
</div>
)}
<AgentConfigForm
form={outboundAgentForm}
readOnly={readOnly}
selectedVoiceId={outboundAgentForm.watch("voiceId")}
onVoiceDialogOpen={() => setIsVoiceDialogOpen(true)}
/>
<VoiceSelectionDialog
open={isVoiceDialogOpen}
onOpenChange={setIsVoiceDialogOpen}
selectedVoiceId={outboundAgentForm.watch("voiceId")}
onVoiceSelect={(voiceId: string) => {
outboundAgentForm.setValue("voiceId", voiceId, { shouldDirty: true });
}}
/>
</>
);
}
@@ -0,0 +1,367 @@
"use client";
import posthog from "posthog-js";
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import type { FormValues } from "@calcom/features/ee/workflows/lib/types";
import { CAL_AI_PHONE_NUMBER_MONTHLY_PRICE } from "@calcom/lib/constants";
import { formatPhoneNumber } from "@calcom/lib/formatPhoneNumber";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import {
Dropdown,
DropdownItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@calcom/ui/components/dropdown";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { WebCallDialog } from "@calcom/web/modules/ee/workflows/components/WebCallDialog";
import { TestPhoneCallDialog } from "../../../TestPhoneCallDialog";
import { usePhoneNumberActions } from "../../hooks/usePhoneNumberActions";
import { BuyNumberDialog } from "../dialogs/BuyNumberDialog";
import { ConfirmationDialogs } from "../dialogs/ConfirmationDialogs";
import { ImportNumberDialog } from "../dialogs/ImportNumberDialog";
interface PhoneNumberTabProps {
agentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
readOnly?: boolean;
agentId?: string | null;
teamId?: number;
workflowId?: string;
isOrganization?: boolean;
form?: UseFormReturn<FormValues>;
eventTypeIds?: number[];
}
export function PhoneNumberTab({
agentData,
readOnly = false,
agentId,
teamId,
workflowId,
isOrganization = false,
form,
eventTypeIds = [],
}: PhoneNumberTabProps) {
const { t } = useLocale();
const utils = trpc.useUtils();
const [isBuyDialogOpen, setIsBuyDialogOpen] = useState(false);
const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);
const [showAdvancedFields, setShowAdvancedFields] = useState(false);
const [isTestAgentDialogOpen, setIsTestAgentDialogOpen] = useState(false);
const [isWebCallDialogOpen, setIsWebCallDialogOpen] = useState(false);
const phoneNumberActions = usePhoneNumberActions();
const buyNumberMutation = trpc.viewer.phoneNumber.buy.useMutation({
onSuccess: async (data: { checkoutUrl?: string; message?: string; phoneNumber?: unknown }) => {
if (data.checkoutUrl) {
window.location.href = data.checkoutUrl;
} else if (data.phoneNumber) {
showToast(t("phone_number_purchased_successfully"), "success");
await utils.viewer.me.get.invalidate();
setIsBuyDialogOpen(false);
if (agentId) {
utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
} else {
showToast(data.message || t("something_went_wrong"), "error");
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const importNumberMutation = trpc.viewer.phoneNumber.import.useMutation({
onSuccess: async () => {
showToast(t("phone_number_imported_successfully"), "success");
setIsImportDialogOpen(false);
await utils.viewer.me.get.invalidate();
if (agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const updateAgentMutation = trpc.viewer.aiVoiceAgent.update.useMutation({
onSuccess: async () => {
if (agentId) {
await utils.viewer.aiVoiceAgent.get.invalidate({ id: agentId });
}
},
onError: (error: { message: string }) => {
showToast(error.message, "error");
},
});
const hasActivePhoneNumbers =
agentData?.outboundPhoneNumbers &&
agentData.outboundPhoneNumbers.filter(
(phone) =>
phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE || !phone.subscriptionStatus
).length > 0;
const outboundEventTypeId =
form?.watch("trigger") === "FORM_SUBMITTED" ? agentData?.outboundEventTypeId : null;
if (hasActivePhoneNumbers) {
const activePhoneNumbers = agentData.outboundPhoneNumbers.filter(
(phone) =>
phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE || !phone.subscriptionStatus
);
const phoneNumber = activePhoneNumbers[0];
return (
<>
<div className="stack-y-2 relative">
{updateAgentMutation.isPending && (
<div className="absolute inset-0 z-10 flex items-center justify-center rounded-lg bg-white/50">
<div className="flex items-center gap-2 text-sm text-gray-600">
<Icon name="loader" className="h-4 w-4 animate-spin" />
{t("updating")}...
</div>
</div>
)}
<div className="border-subtle rounded-lg border p-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<span className="text-emphasis text-sm">{formatPhoneNumber(phoneNumber.phoneNumber)}</span>
<Badge variant="green" size="md" withDot>
{t("active")}
</Badge>
{phoneNumber.subscriptionStatus && (
<span className="text-muted text-xs">
{t("phone_number_cost", {
price: CAL_AI_PHONE_NUMBER_MONTHLY_PRICE,
})}
</span>
)}
</div>
</div>
<div className="flex items-center gap-1">
<Dropdown>
<DropdownMenuTrigger asChild>
<Button
color="secondary"
className="rounded-[10px]"
disabled={readOnly}
EndIcon="chevron-down">
{t("test_agent")}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>
<DropdownItem
type="button"
StartIcon="phone"
onClick={() => {
setIsTestAgentDialogOpen(true);
}}>
{t("phone_call")}
</DropdownItem>
</DropdownMenuItem>
<DropdownMenuItem>
<DropdownItem
type="button"
StartIcon="monitor"
onClick={() => {
setIsWebCallDialogOpen(true);
}}>
{t("web_call")}
</DropdownItem>
</DropdownMenuItem>
</DropdownMenuContent>
</Dropdown>
{!readOnly && (
<Dropdown>
<DropdownMenuTrigger asChild>
<Button type="button" color="secondary" variant="icon" StartIcon="ellipsis" />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>
<DropdownItem
type="button"
StartIcon="trash"
color="destructive"
onClick={() => {
if (readOnly) return;
if (phoneNumber.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE) {
phoneNumberActions.handleCancelSubscription(phoneNumber.id);
} else {
phoneNumberActions.handleDeletePhoneNumber(phoneNumber.phoneNumber);
}
}}>
{phoneNumber.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE
? t("unsubscribe")
: t("delete")}
</DropdownItem>
</DropdownMenuItem>
</DropdownMenuContent>
</Dropdown>
)}
</div>
</div>
</div>
</div>
<BuyNumberDialog
open={isBuyDialogOpen}
onOpenChange={setIsBuyDialogOpen}
agentId={agentId}
workflowId={workflowId}
teamId={teamId}
/>
<ImportNumberDialog
open={isImportDialogOpen}
onOpenChange={setIsImportDialogOpen}
phoneNumberForm={phoneNumberActions.phoneNumberForm}
showAdvancedFields={showAdvancedFields}
setShowAdvancedFields={setShowAdvancedFields}
agentId={agentId}
workflowId={workflowId}
teamId={teamId}
/>
{agentId && form && (
<TestPhoneCallDialog
open={isTestAgentDialogOpen}
onOpenChange={setIsTestAgentDialogOpen}
agentId={agentId}
teamId={teamId}
form={form}
eventTypeIds={eventTypeIds}
outboundEventTypeId={outboundEventTypeId}
/>
)}
{agentId && form && (
<WebCallDialog
open={isWebCallDialogOpen}
onOpenChange={setIsWebCallDialogOpen}
agentId={agentId}
teamId={teamId}
isOrganization={isOrganization}
form={form}
eventTypeIds={eventTypeIds}
outboundEventTypeId={outboundEventTypeId}
/>
)}
<ConfirmationDialogs
cancellingNumberId={phoneNumberActions.cancellingNumberId}
setCancellingNumberId={phoneNumberActions.setCancellingNumberId}
numberToDelete={phoneNumberActions.numberToDelete}
setNumberToDelete={phoneNumberActions.setNumberToDelete}
agentId={agentId}
/>
</>
);
}
return (
<>
<div className="border-subtle rounded-xl border p-8">
<div className="stack-y-6 flex flex-col items-center text-center">
<div className="bg-cal-muted flex h-16 w-16 items-center justify-center rounded-lg">
<Icon name="phone" className="text-subtle h-8 w-8" />
</div>
<div className="stack-y-2">
<h3 className="text-emphasis text-lg font-semibold">{t("no_phone_numbers")}</h3>
<p className="text-subtle text-sm">{t("buy_a_phone_number_or_import_one_you_already_have")}</p>
</div>
<div className="flex gap-3">
<Button
onClick={() => {
if (readOnly) return;
posthog.capture("calai_buy_number_modal_opened");
setIsBuyDialogOpen(true);
}}
StartIcon="external-link"
className="px-6"
disabled={readOnly || buyNumberMutation.isPending}>
{t("buy")}
</Button>
<Button
onClick={() => {
if (readOnly) return;
setIsImportDialogOpen(true);
}}
color="secondary"
className="px-6"
disabled={readOnly || importNumberMutation.isPending}>
{t("import")}
</Button>
</div>
</div>
</div>
<BuyNumberDialog
open={isBuyDialogOpen}
onOpenChange={setIsBuyDialogOpen}
agentId={agentId}
workflowId={workflowId}
teamId={teamId}
/>
<ImportNumberDialog
open={isImportDialogOpen}
onOpenChange={setIsImportDialogOpen}
phoneNumberForm={phoneNumberActions.phoneNumberForm}
showAdvancedFields={showAdvancedFields}
setShowAdvancedFields={setShowAdvancedFields}
agentId={agentId}
workflowId={workflowId}
teamId={teamId}
/>
{agentId && form && (
<TestPhoneCallDialog
open={isTestAgentDialogOpen}
onOpenChange={setIsTestAgentDialogOpen}
agentId={agentId}
teamId={teamId}
form={form}
eventTypeIds={eventTypeIds}
outboundEventTypeId={outboundEventTypeId}
/>
)}
{agentId && form && (
<WebCallDialog
open={isWebCallDialogOpen}
onOpenChange={setIsWebCallDialogOpen}
agentId={agentId}
teamId={teamId}
isOrganization={isOrganization}
form={form}
eventTypeIds={eventTypeIds}
outboundEventTypeId={outboundEventTypeId}
/>
)}
<ConfirmationDialogs
cancellingNumberId={phoneNumberActions.cancellingNumberId}
setCancellingNumberId={phoneNumberActions.setCancellingNumberId}
numberToDelete={phoneNumberActions.numberToDelete}
setNumberToDelete={phoneNumberActions.setNumberToDelete}
agentId={agentId}
/>
</>
);
}
@@ -0,0 +1,75 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { cleanPromptForDisplay } from "@calcom/features/calAIPhone/providers/retellAI/utils/promptUtils";
import type { RouterOutputs } from "@calcom/trpc/react";
import type { AgentFormValues } from "../types/schemas";
import { agentSchema } from "../types/schemas";
interface UseAgentFormsProps {
agentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
inboundAgentData?: RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
}
export function useAgentForms({ agentData, inboundAgentData }: UseAgentFormsProps) {
const outboundAgentForm = useForm<AgentFormValues>({
resolver: zodResolver(agentSchema),
defaultValues: {
generalPrompt: "",
beginMessage: "",
numberToCall: "",
language: "en-US",
voiceId: "",
generalTools: [],
},
});
const inboundAgentForm = useForm<AgentFormValues>({
resolver: zodResolver(agentSchema),
defaultValues: {
generalPrompt: "",
beginMessage: "",
numberToCall: "",
language: "en-US",
voiceId: "",
generalTools: [],
},
});
useEffect(() => {
if (agentData?.retellData) {
const retellData = agentData.retellData;
outboundAgentForm.reset({
generalPrompt: cleanPromptForDisplay(retellData.generalPrompt || ""),
beginMessage: retellData.beginMessage || "",
numberToCall: "",
language: retellData.language || "en-US",
voiceId: retellData.voiceId || "",
generalTools: retellData.generalTools || [],
outboundEventTypeId: agentData.outboundEventTypeId || undefined,
});
}
}, [agentData, outboundAgentForm]);
useEffect(() => {
if (inboundAgentData?.retellData) {
const retellData = inboundAgentData.retellData;
inboundAgentForm.reset({
generalPrompt: cleanPromptForDisplay(retellData.generalPrompt || ""),
beginMessage: retellData.beginMessage || "",
numberToCall: "",
language: retellData.language || "en-US",
voiceId: retellData.voiceId || "",
generalTools: retellData.generalTools || [],
});
}
}, [inboundAgentData, inboundAgentForm]);
return {
outboundAgentForm,
inboundAgentForm,
};
}
@@ -0,0 +1,40 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useState } from "react";
import { useForm } from "react-hook-form";
import type { PhoneNumberFormValues } from "../types/schemas";
import { phoneNumberFormSchema } from "../types/schemas";
export function usePhoneNumberActions() {
const [cancellingNumberId, setCancellingNumberId] = useState<number | null>(null);
const [numberToDelete, setNumberToDelete] = useState<string | null>(null);
const phoneNumberForm = useForm<PhoneNumberFormValues>({
resolver: zodResolver(phoneNumberFormSchema),
defaultValues: {
phoneNumber: "",
terminationUri: "",
sipTrunkAuthUsername: "",
sipTrunkAuthPassword: "",
nickname: "",
},
});
const handleCancelSubscription = (phoneNumberId: number) => {
setCancellingNumberId(phoneNumberId);
};
const handleDeletePhoneNumber = (phoneNumber: string) => {
setNumberToDelete(phoneNumber);
};
return {
phoneNumberForm,
cancellingNumberId,
setCancellingNumberId,
numberToDelete,
setNumberToDelete,
handleCancelSubscription,
handleDeletePhoneNumber,
};
}
@@ -0,0 +1,46 @@
import { isValidPhoneNumber } from "libphonenumber-js/max";
import { z } from "zod";
export const agentSchema = z.object({
generalPrompt: z.string().min(1, "General prompt is required"),
beginMessage: z.string().min(1, "Begin message is required"),
numberToCall: z.string().optional(),
language: z.string().optional(),
voiceId: z.string().optional(),
outboundEventTypeId: z.number().optional(),
generalTools: z
.array(
z.object({
type: z.string(),
name: z.string(),
description: z.string().nullish().default(null),
cal_api_key: z.string().nullish().default(null),
event_type_id: z.number().nullish().default(null),
timezone: z.string().nullish().default(null),
})
)
.optional(),
});
export const phoneNumberFormSchema = z.object({
phoneNumber: z.string().refine((val) => isValidPhoneNumber(val)),
terminationUri: z.string().min(1, "Termination URI is required"),
sipTrunkAuthUsername: z.string().optional(),
sipTrunkAuthPassword: z.string().optional(),
nickname: z.string().optional(),
});
export type AgentFormValues = z.infer<typeof agentSchema>;
export type PhoneNumberFormValues = z.infer<typeof phoneNumberFormSchema>;
// Commented types for future implementation
// type RetellData = RouterOutputs["viewer"]["ai"]["get"]["retellData"];
// type ToolDraft = {
// type: string;
// name: string;
// description: string | null;
// cal_api_key: string | null;
// event_type_id: number | null;
// timezone: string;
// };
@@ -0,0 +1,38 @@
export const LANGUAGE_OPTIONS = [
{ value: "en-US", label: "English (US)" },
{ value: "en-IN", label: "English (India)" },
{ value: "en-GB", label: "English (UK)" },
{ value: "en-AU", label: "English (Australia)" },
{ value: "en-NZ", label: "English (New Zealand)" },
{ value: "de-DE", label: "German" },
{ value: "es-ES", label: "Spanish (Spain)" },
{ value: "es-419", label: "Spanish (Latin America)" },
{ value: "hi-IN", label: "Hindi" },
{ value: "fr-FR", label: "French (France)" },
{ value: "fr-CA", label: "French (Canada)" },
{ value: "ja-JP", label: "Japanese" },
{ value: "pt-PT", label: "Portuguese (Portugal)" },
{ value: "pt-BR", label: "Portuguese (Brazil)" },
{ value: "zh-CN", label: "Chinese (Simplified)" },
{ value: "ru-RU", label: "Russian" },
{ value: "it-IT", label: "Italian" },
{ value: "ko-KR", label: "Korean" },
{ value: "nl-NL", label: "Dutch (Netherlands)" },
{ value: "nl-BE", label: "Dutch (Belgium)" },
{ value: "pl-PL", label: "Polish" },
{ value: "tr-TR", label: "Turkish" },
{ value: "th-TH", label: "Thai" },
{ value: "vi-VN", label: "Vietnamese" },
{ value: "ro-RO", label: "Romanian" },
{ value: "bg-BG", label: "Bulgarian" },
{ value: "ca-ES", label: "Catalan" },
{ value: "da-DK", label: "Danish" },
{ value: "fi-FI", label: "Finnish" },
{ value: "el-GR", label: "Greek" },
{ value: "hu-HU", label: "Hungarian" },
{ value: "id-ID", label: "Indonesian" },
{ value: "no-NO", label: "Norwegian" },
{ value: "sk-SK", label: "Slovak" },
{ value: "sv-SE", label: "Swedish" },
{ value: "multi", label: "Multilingual" },
];
@@ -0,0 +1,570 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useSession } from "next-auth/react";
import { useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { useForm, useWatch } from "react-hook-form";
import { Toaster } from "sonner";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import {
isSMSAction,
isSMSOrWhatsappAction,
isCalAIAction,
isFormTrigger,
} from "@calcom/features/ee/workflows/lib/actionHelperFunctions";
import { formSchema } from "@calcom/features/ee/workflows/lib/schema";
import type { FormValues } from "@calcom/features/ee/workflows/lib/types";
import {
getTranslatedText,
translateVariablesToEnglish,
} from "@calcom/features/ee/workflows/lib/variableTranslations";
import type { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
import type { WorkflowPermissions } from "@calcom/features/workflows/repositories/WorkflowPermissionsRepository";
import { SENDER_ID } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import { WorkflowActions } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { Alert } from "@calcom/ui/components/alert";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
import { Form, Input } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { DeleteDialog } from "../components/DeleteDialog";
import SkeletonLoader from "../components/SkeletonLoaderEdit";
import WorkflowDetailsPage from "../components/WorkflowDetailsPage";
type PageProps = {
workflow: number;
workflowData?: Awaited<ReturnType<typeof WorkflowRepository.getById>>;
verifiedNumbers?: Awaited<ReturnType<typeof WorkflowRepository.getVerifiedNumbers>>;
verifiedEmails?: Awaited<ReturnType<typeof WorkflowRepository.getVerifiedEmails>>;
};
function WorkflowPage({
workflow: workflowId,
workflowData: workflowDataProp,
verifiedNumbers: verifiedNumbersProp,
verifiedEmails: verifiedEmailsProp,
}: PageProps) {
const { t, i18n } = useLocale();
const session = useSession();
const [selectedOptions, setSelectedOptions] = useState<Option[]>([]);
const [isAllDataLoaded, setIsAllDataLoaded] = useState(false);
const [isMixedEventType, setIsMixedEventType] = useState(false); //for old event types before team workflows existed
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [isEditingName, setIsEditingName] = useState(false);
const [nameValue, setNameValue] = useState("");
const searchParams = useSearchParams();
const form = useForm<FormValues>({
mode: "onBlur",
resolver: zodResolver(formSchema),
});
const utils = trpc.useUtils();
const watchedTrigger = useWatch({
control: form.control,
name: "trigger",
});
const userQuery = useMeQuery();
const user = userQuery.data;
const {
data: workflowData,
isError: _isError,
error,
isPending: _isPendingWorkflow,
} = trpc.viewer.workflows.get.useQuery(
{ id: +workflowId },
{
enabled: workflowDataProp ? false : !!workflowId,
}
);
const workflow = workflowDataProp || workflowData;
const isPendingWorkflow = workflowDataProp ? false : _isPendingWorkflow;
const isError = workflowDataProp ? false : _isError;
const { data: verifiedNumbersData } = trpc.viewer.workflows.getVerifiedNumbers.useQuery(
{ teamId: workflow?.team?.id },
{
enabled: verifiedNumbersProp ? false : !!workflow?.id,
}
);
const verifiedNumbers = verifiedNumbersProp || verifiedNumbersData;
const { data: verifiedEmailsData } = trpc.viewer.workflows.getVerifiedEmails.useQuery(
{
teamId: workflow?.team?.id,
},
{ enabled: !verifiedEmailsProp }
);
const verifiedEmails = verifiedEmailsProp || verifiedEmailsData;
const isOrg = workflow?.team?.isOrganization ?? false;
const teamId = workflow?.teamId ?? undefined;
const { data, isPending: isPendingEventTypes } = trpc.viewer.eventTypes.getActiveOnOptions.useQuery(
{ teamId, isOrg },
{ enabled: !isPendingWorkflow }
);
const teamOptions = data?.teamOptions ?? [];
const routingFormOptions = data?.routingFormOptions ?? [];
let allEventTypeOptions = data?.eventTypeOptions ?? [];
const distinctEventTypes = new Set();
if (!teamId && isMixedEventType) {
allEventTypeOptions = [...allEventTypeOptions, ...selectedOptions];
allEventTypeOptions = allEventTypeOptions.filter((option) => {
const duplicate = distinctEventTypes.has(option.value);
distinctEventTypes.add(option.value);
return !duplicate;
});
}
const hasPermissions = (w: typeof workflow): w is RouterOutputs["viewer"]["workflows"]["get"] => {
return w !== null && w !== undefined && "permissions" in w;
};
const permissions: WorkflowPermissions =
workflow && hasPermissions(workflow)
? workflow?.permissions
: {
canUpdate: !teamId,
canView: !teamId,
canDelete: !teamId,
readOnly: !!teamId,
};
// Watch for form name changes
const watchedName = form.watch("name");
// Handler functions for editable name
const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setNameValue(e.target.value);
};
const handleNameSubmit = () => {
form.setValue("name", nameValue);
setIsEditingName(false);
};
const handleNameKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
form.setValue("name", nameValue);
setIsEditingName(false);
} else if (e.key === "Escape") {
setNameValue(watchedName || "");
setIsEditingName(false);
}
};
const isPending = isPendingWorkflow || isPendingEventTypes;
useEffect(() => {
requestAnimationFrame(() => {
window.scrollTo({
top: 0,
behavior: "smooth",
});
});
}, [isPending]);
useEffect(() => {
if (!isPending) {
if (hasPermissions(workflow)) {
setFormData(workflow);
} else if (workflow) {
const workflowWithDefaults = {
...workflow,
permissions: {
canUpdate: false,
canView: false,
canDelete: false,
canManage: false,
readOnly: true,
},
readOnly: true,
} as RouterOutputs["viewer"]["workflows"]["get"];
setFormData(workflowWithDefaults);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isPending]);
// Update nameValue when workflow changes
useEffect(() => {
if (workflow?.name) {
setNameValue(workflow.name);
}
}, [workflow?.name]);
function setFormData(workflowData: RouterOutputs["viewer"]["workflows"]["get"] | undefined) {
if (workflowData) {
if (workflowData.userId && workflowData.activeOn.find((active) => !!active.eventType.teamId)) {
setIsMixedEventType(true);
}
let activeOn;
if (workflowData.isActiveOnAll) {
activeOn = isOrg
? teamOptions
: isFormTrigger(workflowData.trigger)
? routingFormOptions
: allEventTypeOptions;
} else {
if (isOrg) {
activeOn = workflowData.activeOnTeams.flatMap((active) => {
return {
value: String(active.team.id) || "",
label: active.team.slug || "",
};
});
setSelectedOptions(activeOn || []);
} else if (isFormTrigger(workflowData.trigger)) {
activeOn = workflowData.activeOnRoutingForms?.flatMap((active) => {
return {
value: String(active.routingForm.id) || "",
label: active.routingForm.name || "",
};
});
setSelectedOptions(activeOn || []);
} else {
setSelectedOptions(
workflowData.activeOn?.flatMap((active) => {
if (workflowData.teamId && active.eventType.parentId) return [];
return {
value: String(active.eventType.id),
label: active.eventType.title,
};
}) || []
);
activeOn = workflowData.activeOn
? workflowData.activeOn.map((active) => ({
value: active.eventType.id.toString(),
label: active.eventType.slug,
}))
: undefined;
}
}
//translate dynamic variables into local language
const steps = workflowData.steps?.map((step) => {
const updatedStep = {
...step,
senderName: step.sender,
sender: isSMSAction(step.action) ? step.sender : SENDER_ID,
};
if (step.reminderBody) {
updatedStep.reminderBody = getTranslatedText(step.reminderBody || "", {
locale: i18n.language,
t,
});
}
if (step.emailSubject) {
updatedStep.emailSubject = getTranslatedText(step.emailSubject || "", {
locale: i18n.language,
t,
});
}
return updatedStep;
});
form.setValue("name", workflowData.name);
form.setValue("steps", steps);
form.setValue("trigger", workflowData.trigger);
form.setValue("time", workflowData.time || undefined);
form.setValue("timeUnit", workflowData.timeUnit || undefined);
form.setValue("activeOn", activeOn || []);
form.setValue("selectAll", workflowData.isActiveOnAll ?? false);
setNameValue(workflowData.name);
setIsAllDataLoaded(true);
}
}
const updateMutation = trpc.viewer.workflows.update.useMutation({
onSuccess: async ({ workflow }) => {
utils.viewer.workflows.get.setData({ id: +workflow.id }, workflow);
setFormData(workflow);
const autoCreateAgent = searchParams?.get("autoCreateAgent");
if (!autoCreateAgent) {
showToast(
t("workflow_updated_successfully", {
workflowName: workflow.name,
}),
"success"
);
}
},
onError: (err) => {
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
}
},
});
const validateAndSubmitWorkflow = async (values: FormValues): Promise<void> => {
let isEmpty = false;
let isVerified = true;
values.steps.forEach((step) => {
const strippedHtml = step.reminderBody?.replace(/<[^>]+>/g, "") || "";
const isBodyEmpty =
!isSMSOrWhatsappAction(step.action) && !isCalAIAction(step.action) && strippedHtml.length <= 1;
if (isBodyEmpty) {
form.setError(`steps.${step.stepNumber - 1}.reminderBody`, {
type: "custom",
message: t("fill_this_field"),
});
}
if (step.reminderBody) {
step.reminderBody = translateVariablesToEnglish(step.reminderBody, {
locale: i18n.language,
t,
});
}
if (step.emailSubject) {
step.emailSubject = translateVariablesToEnglish(step.emailSubject, {
locale: i18n.language,
t,
});
}
isEmpty = !isEmpty ? isBodyEmpty : isEmpty;
//check if phone number is verified
if (
(step.action === WorkflowActions.SMS_NUMBER || step.action === WorkflowActions.WHATSAPP_NUMBER) &&
!verifiedNumbers?.find((verifiedNumber) => verifiedNumber.phoneNumber === step.sendTo)
) {
isVerified = false;
form.setError(`steps.${step.stepNumber - 1}.sendTo`, {
type: "custom",
message: t("not_verified"),
});
}
if (
step.action === WorkflowActions.EMAIL_ADDRESS &&
!verifiedEmails?.find((verifiedEmail) => verifiedEmail === step.sendTo)
) {
isVerified = false;
form.setError(`steps.${step.stepNumber - 1}.sendTo`, {
type: "custom",
message: t("not_verified"),
});
}
});
if (!isEmpty && isVerified) {
let activeOnEventTypeOrTeamIds: number[] = [];
let activeOnRoutingFormIds: string[] = [];
if (isOrg || !isFormTrigger(values.trigger)) {
activeOnEventTypeOrTeamIds = values.activeOn
.filter((option) => option.value !== "all")
.map((option) => {
return parseInt(option.value, 10);
});
} else {
// Form triggers, activeOn contains routing form IDs (strings)
activeOnRoutingFormIds = values.activeOn
.filter((option) => option.value !== "all")
.map((option) => option.value);
}
await updateMutation.mutateAsync({
id: workflowId,
name: values.name,
activeOnEventTypeIds: activeOnEventTypeOrTeamIds,
activeOnRoutingFormIds,
steps: values.steps,
trigger: values.trigger,
time: values.time || null,
timeUnit: values.timeUnit || null,
isActiveOnAll: values.selectAll || false,
});
utils.viewer.workflows.getVerifiedNumbers.invalidate();
} else {
const validationErrors: string[] = [];
if (isEmpty) {
validationErrors.push(t("workflow_validation_empty_fields"));
}
if (!isVerified) {
validationErrors.push(t("workflow_validation_unverified_contacts"));
}
throw new Error(`${t("workflow_validation_failed")}: ${validationErrors.join("; ")}`);
}
};
const handleSaveWorkflow = async (): Promise<void> => {
const values = form.getValues();
await validateAndSubmitWorkflow(values);
};
return session.data ? (
<LicenseRequired>
<Form
form={form}
handleSubmit={async (values) => {
await validateAndSubmitWorkflow(values);
}}>
<div className="flex h-full min-h-screen w-full flex-col">
<div className="bg-default border-muted flex w-full items-center justify-between border-b px-4 py-2">
<div className="border-muted flex items-center gap-2">
<Button
color="secondary"
size="sm"
variant="icon"
StartIcon="arrow-left"
href="/workflows"
data-testid="go-back-button"
/>
<div className="flex min-w-0 items-center leading-none">
<span className="text-subtle min-w-content text-sm font-semibold leading-none">
{t("workflows")}
</span>
<span className="text-subtle mx-1 text-sm font-semibold leading-none">/</span>
{isEditingName ? (
<Input
{...form.register("name")}
data-testid="workflow-name"
onChange={handleNameChange}
onKeyDown={handleNameKeyDown}
onBlur={handleNameSubmit}
className="text-default focus:shadow-outline-gray-focused h-auto w-full whitespace-nowrap border-none p-1 text-sm font-semibold leading-none focus:ring-0"
autoFocus
/>
) : (
<div className="group flex items-center gap-1">
<span
className="text-default hover:bg-cal-muted min-w-[100px] cursor-pointer truncate whitespace-nowrap rounded p-1 text-sm font-semibold leading-none"
onClick={() => setIsEditingName(true)}>
{watchedName ? watchedName : isPending ? t("loading") : t("untitled")}
</span>
<Button
variant="icon"
color="minimal"
data-testid="edit-workflow-name-button"
disabled={isPending}
onClick={() => setIsEditingName(true)}
CustomStartIcon={
<Icon name="pencil" className="text-subtle group-hover:text-default h-3 w-3" />
}>
<span className="sr-only">{t("edit")}</span>
</Button>
</div>
)}
</div>
{workflow && workflow.team && (
<Badge className="ml-4 mt-1" variant="gray">
{workflow.team.name}
</Badge>
)}
{permissions.readOnly && (
<Badge className="ml-4 mt-1" variant="gray">
{t("readonly")}
</Badge>
)}
</div>
<div className="border-muted flex justify-end gap-2">
<Tooltip sideOffset={4} content={t("delete")} side="bottom">
<Button
color="destructive"
type="button"
StartIcon="trash-2"
data-testid="delete-button"
onClick={() => {
setDeleteDialogOpen(true);
}}
disabled={!permissions.canDelete}
/>
</Tooltip>
<Button
loading={updateMutation.isPending}
disabled={permissions.readOnly || updateMutation.isPending}
data-testid="save-workflow"
type="submit"
color="primary">
{t("save")}
</Button>
</div>
</div>
<div className="bg-default min-h-screen w-full px-2 sm:p-0">
<div className="mx-auto my-8 max-w-4xl">
{!isError ? (
<>
{isAllDataLoaded && user ? (
<>
<WorkflowDetailsPage
form={form}
workflowId={+workflowId}
user={user}
selectedOptions={selectedOptions}
setSelectedOptions={setSelectedOptions}
teamId={workflow ? workflow.teamId || undefined : undefined}
isOrg={isOrg}
allOptions={
isOrg
? teamOptions
: isFormTrigger(watchedTrigger)
? routingFormOptions
: allEventTypeOptions
}
eventTypeOptions={allEventTypeOptions}
onSaveWorkflow={handleSaveWorkflow}
permissions={permissions}
/>
</>
) : (
<SkeletonLoader />
)}
</>
) : (
<Alert severity="error" title={t("something_went_wrong")} message={error?.message ?? ""} />
)}
</div>
</div>
</div>
</Form>
<DeleteDialog
isOpenDialog={deleteDialogOpen}
setIsOpenDialog={setDeleteDialogOpen}
workflowId={workflowId}
additionalFunction={async () => {
// Navigate back to workflows list after deletion
window.location.href = "/workflows";
}}
/>
<Toaster position="bottom-right" />
</LicenseRequired>
) : (
<></>
);
}
export default WorkflowPage;
@@ -0,0 +1,236 @@
"use client";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import type { Dispatch, SetStateAction } from "react";
import { useState } from "react";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import type { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
import { FilterResults } from "@calcom/features/filters/components/FilterResults";
import { TeamsFilter } from "@calcom/features/filters/components/TeamsFilter";
import { getTeamsFiltersFromQuery } from "@calcom/features/filters/lib/getTeamsFiltersFromQuery";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
import { Avatar } from "@calcom/ui/components/avatar";
import { AnimatedPopover } from "@calcom/ui/components/popover";
import Shell, { ShellMain } from "@calcom/web/modules/shell/Shell";
import EmptyScreen from "@calcom/web/modules/ee/workflows/components/EmptyScreen";
import SkeletonLoader from "@calcom/web/modules/ee/workflows/components/SkeletonLoaderList";
import {
WorkflowCreationDialog,
useWorkflowCreation,
} from "@calcom/web/modules/ee/workflows/components/WorkflowCreationDialog";
import WorkflowList from "@calcom/web/modules/ee/workflows/components/WorkflowListPage";
import { CreateButtonWithTeamsList } from "~/ee/teams/components/createButton/CreateButtonWithTeamsList";
type PageProps = {
filteredList?: Awaited<ReturnType<typeof WorkflowRepository.getFilteredList>>;
};
function WorkflowsPage({ filteredList }: PageProps) {
const { t } = useLocale();
const session = useSession();
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- router is kept for future use
const router = useRouter();
const routerQuery = useRouterQuery();
const filters = getTeamsFiltersFromQuery(routerQuery);
const { showDialog, setShowDialog, pendingTeamId, openDialog } = useWorkflowCreation();
const { data, isPending: _isPending } = trpc.viewer.workflows.filteredList.useQuery(
{
filters,
},
{
enabled: !filteredList,
}
);
const filteredWorkflows = filteredList ?? data;
const isPending = filteredList ? false : _isPending;
return (
<Shell withoutMain>
<LicenseRequired>
<ShellMain
heading={t("workflows")}
subtitle={t("workflows_to_automate_notifications")}
title={t("workflows")}
description={t("workflows_to_automate_notifications")}
CTA={
session.data?.hasValidLicense ? (
<CreateButtonWithTeamsList
subtitle={t("new_workflow_subtitle").toUpperCase()}
createFunction={openDialog}
disableMobileButton={true}
onlyShowWithNoTeams={true}
includeOrg={true}
withPermission={{
permission: "workflow.create",
fallbackRoles: ["ADMIN", "OWNER"],
}}
/>
) : null
}>
<>
{filteredWorkflows?.totalCount ? (
<div className="mb-2 flex">
<TeamsFilter />
<div className="mb-4 ml-auto">
<CreateButtonWithTeamsList
subtitle={t("new_workflow_subtitle").toUpperCase()}
createFunction={openDialog}
disableMobileButton={true}
onlyShowWithTeams={true}
includeOrg={true}
withPermission={{
permission: "workflow.create",
fallbackRoles: ["ADMIN", "OWNER"],
}}
/>
</div>
</div>
) : null}
<FilterResults
queryRes={{ isPending, data: filteredWorkflows }}
emptyScreen={<EmptyScreen isFilteredView={false} />}
noResultsScreen={<EmptyScreen isFilteredView={true} />}
SkeletonLoader={SkeletonLoader}>
<WorkflowList workflows={filteredWorkflows?.filtered} />
</FilterResults>
</>
</ShellMain>
<WorkflowCreationDialog open={showDialog} onOpenChange={setShowDialog} teamId={pendingTeamId} />
</LicenseRequired>
</Shell>
);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Filter component is kept for future use
const Filter = (props: {
profiles: {
readOnly?: boolean | undefined;
slug: string | null;
name: string | null;
teamId: number | null | undefined;
image?: string | undefined | null;
}[];
checked: {
userId: number | null;
teamIds: number[];
};
setChecked: Dispatch<
SetStateAction<{
userId: number | null;
teamIds: number[];
}>
>;
}) => {
const session = useSession();
const userId = session.data?.user.id || 0;
const user = session.data?.user.name || "";
const userName = session.data?.user.username;
const userAvatar = `${WEBAPP_URL}/${userName}/avatar.png`;
const teams = props.profiles.filter((profile) => !!profile.teamId);
const { checked, setChecked } = props;
const [noFilter, setNoFilter] = useState(true);
return (
<div className={classNames("-mb-2", noFilter ? "w-16" : "w-[100px]")}>
<AnimatedPopover text={noFilter ? "All" : "Filtered"}>
<div className="item-center focus-within:bg-subtle hover:bg-cal-muted flex px-4 py-[6px] transition hover:cursor-pointer">
<Avatar
imageSrc={userAvatar || ""}
size="sm"
alt={`${user} Avatar`}
className="self-center"
asChild
/>
<label
htmlFor="yourWorkflows"
className="text-default ml-2 mr-auto self-center truncate text-sm font-medium">
{user}
</label>
<input
id="yourWorkflows"
type="checkbox"
className="text-emphasis focus:ring-emphasis dark:text-muted border-default inline-flex h-4 w-4 place-self-center justify-self-end rounded transition "
checked={!!checked.userId}
onChange={(e) => {
if (e.target.checked) {
setChecked({ userId: userId, teamIds: checked.teamIds });
if (checked.teamIds.length === teams.length) {
setNoFilter(true);
}
} else if (!e.target.checked) {
setChecked({ userId: null, teamIds: checked.teamIds });
setNoFilter(false);
}
}}
/>
</div>
{teams.map((profile) => (
<div
className="item-center focus-within:bg-subtle hover:bg-cal-muted flex px-4 py-[6px] transition hover:cursor-pointer"
key={`${profile.teamId || 0}`}>
<Avatar
imageSrc={profile.image || ""}
size="sm"
alt={`${profile.slug} Avatar`}
className="self-center"
asChild
/>
<label
htmlFor={profile.slug || ""}
className="text-default ml-2 mr-auto select-none self-center truncate text-sm font-medium hover:cursor-pointer">
{profile.slug}
</label>
<input
id={profile.slug || ""}
name={profile.slug || ""}
type="checkbox"
checked={checked.teamIds?.includes(profile.teamId || 0)}
onChange={(e) => {
if (e.target.checked) {
const updatedChecked = checked;
updatedChecked.teamIds.push(profile.teamId || 0);
setChecked({ userId: checked.userId, teamIds: [...updatedChecked.teamIds] });
if (checked.userId && updatedChecked.teamIds.length === teams.length) {
setNoFilter(true);
} else {
setNoFilter(false);
}
} else if (!e.target.checked) {
const index = checked.teamIds.indexOf(profile.teamId || 0);
if (index !== -1) {
const updatedChecked = checked;
updatedChecked.teamIds.splice(index, 1);
setChecked({ userId: checked.userId, teamIds: [...updatedChecked.teamIds] });
if (checked.userId && updatedChecked.teamIds.length === teams.length) {
setNoFilter(true);
} else {
setNoFilter(false);
}
}
}
}}
className="text-emphasis focus:ring-emphasis dark:text-muted border-default inline-flex h-4 w-4 place-self-center justify-self-end rounded transition "
/>
</div>
))}
</AnimatedPopover>
</div>
);
};
export default WorkflowsPage;