From 4d53f327d9c1afb99189b0970ed10a731220d6b2 Mon Sep 17 00:00:00 2001 From: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com> Date: Wed, 11 Sep 2024 16:41:54 +0530 Subject: [PATCH] feat: V2 API endpoint create phone call (#16528) * refactor: V2 API endpoint create phone call * fix: type err * fix: type and build err * chore: change default value * chore: move it to another route * test: for create phone call * chore: undo constant * chore: remove test * fix: make begin_message optional * chore: improvements * chore: begin message * chore: remove unused import * chore: bump platform libraries with handleCreatePhoneCall * chore: improvement --------- Co-authored-by: Keith Williams Co-authored-by: Benny Joo Co-authored-by: Morgan Vernay Co-authored-by: Peer Richelsen --- apps/api/v2/package.json | 2 +- .../inputs/create-phone-call.input.ts | 71 ++++++++ .../outputs/create-phone-call.output.ts | 28 +++ .../organizations-event-types.controller.ts | 29 ++- apps/api/v2/swagger/documentation.json | 167 +++++++++++++++++- .../ee/cal-ai-phone/retellAIService.ts | 2 +- .../features/ee/cal-ai-phone/zod-utils.ts | 2 +- .../components/tabs/ai/AIEventController.tsx | 3 +- packages/features/handleCreatePhoneCall.ts | 126 +++++++++++++ packages/lib/constants.ts | 1 + packages/platform/libraries/index.ts | 2 + .../server/routers/viewer/eventTypes/util.ts | 17 +- .../routers/viewer/organizations/_router.tsx | 3 +- .../organizations/createPhoneCall.handler.ts | 116 +----------- 14 files changed, 444 insertions(+), 125 deletions(-) create mode 100644 apps/api/v2/src/ee/event-types/event-types_2024_06_14/inputs/create-phone-call.input.ts create mode 100644 apps/api/v2/src/ee/event-types/event-types_2024_06_14/outputs/create-phone-call.output.ts create mode 100644 packages/features/handleCreatePhoneCall.ts diff --git a/apps/api/v2/package.json b/apps/api/v2/package.json index 10f4c71ecc..5eda351e79 100644 --- a/apps/api/v2/package.json +++ b/apps/api/v2/package.json @@ -28,7 +28,7 @@ "dependencies": { "@calcom/platform-constants": "*", "@calcom/platform-enums": "*", - "@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.33", + "@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.34", "@calcom/platform-libraries-0.0.2": "npm:@calcom/platform-libraries@0.0.2", "@calcom/platform-types": "*", "@calcom/platform-utils": "*", diff --git a/apps/api/v2/src/ee/event-types/event-types_2024_06_14/inputs/create-phone-call.input.ts b/apps/api/v2/src/ee/event-types/event-types_2024_06_14/inputs/create-phone-call.input.ts new file mode 100644 index 0000000000..8fa63319d2 --- /dev/null +++ b/apps/api/v2/src/ee/event-types/event-types_2024_06_14/inputs/create-phone-call.input.ts @@ -0,0 +1,71 @@ +import { ApiProperty as DocsProperty } from "@nestjs/swagger"; +import { Transform } from "class-transformer"; +import { IsString, IsBoolean, IsOptional, IsEnum, Matches } from "class-validator"; + +export enum TemplateType { + CHECK_IN_APPOINTMENT = "CHECK_IN_APPOINTMENT", + CUSTOM_TEMPLATE = "CUSTOM_TEMPLATE", +} + +export class CreatePhoneCallInput { + @IsString() + @Matches(/^\+[1-9]\d{1,14}$/, { + message: + "Invalid phone number format. Expected format: + with no spaces or separators.", + }) + @DocsProperty({ description: "Your phone number" }) + yourPhoneNumber!: string; + + @IsString() + @Matches(/^\+[1-9]\d{1,14}$/, { + message: + "Invalid phone number format. Expected format: + with no spaces or separators.", + }) + @DocsProperty({ description: "Number to call" }) + numberToCall!: string; + + @IsString() + @DocsProperty({ description: "CAL API Key" }) + calApiKey!: string; + + @IsBoolean() + @DocsProperty({ description: "Enabled status", default: true }) + enabled = true; + + @IsEnum(TemplateType) + @DocsProperty({ description: "Template type", enum: TemplateType }) + templateType: TemplateType = TemplateType.CUSTOM_TEMPLATE; + + @IsOptional() + @IsString() + @DocsProperty({ description: "Scheduler name" }) + schedulerName?: string; + + @IsOptional() + @IsString() + @Transform(({ value }) => (value ? value : undefined)) + @DocsProperty({ description: "Guest name" }) + guestName?: string; + + @IsOptional() + @IsString() + @Transform(({ value }) => (value ? value : undefined)) + @DocsProperty({ description: "Guest email" }) + guestEmail?: string; + + @IsOptional() + @IsString() + @Transform(({ value }) => (value ? value : undefined)) + @DocsProperty({ description: "Guest company" }) + guestCompany?: string; + + @IsOptional() + @IsString() + @DocsProperty({ description: "Begin message" }) + beginMessage?: string; + + @IsOptional() + @IsString() + @DocsProperty({ description: "General prompt" }) + generalPrompt?: string; +} diff --git a/apps/api/v2/src/ee/event-types/event-types_2024_06_14/outputs/create-phone-call.output.ts b/apps/api/v2/src/ee/event-types/event-types_2024_06_14/outputs/create-phone-call.output.ts new file mode 100644 index 0000000000..ac4c2dd965 --- /dev/null +++ b/apps/api/v2/src/ee/event-types/event-types_2024_06_14/outputs/create-phone-call.output.ts @@ -0,0 +1,28 @@ +import { ApiProperty } from "@nestjs/swagger"; +import { Type } from "class-transformer"; +import { IsEnum, IsString, ValidateNested } from "class-validator"; + +import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants"; + +class Data { + @IsString() + @ApiProperty() + callId!: string; + + @IsString() + @ApiProperty() + agentId!: string; +} + +export class CreatePhoneCallOutput { + @ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] }) + @IsEnum([SUCCESS_STATUS, ERROR_STATUS]) + status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS; + + @ApiProperty({ + type: Data, + }) + @ValidateNested() + @Type(() => Data) + data!: Data; +} diff --git a/apps/api/v2/src/modules/organizations/controllers/event-types/organizations-event-types.controller.ts b/apps/api/v2/src/modules/organizations/controllers/event-types/organizations-event-types.controller.ts index fa1c41df66..6ba6caf3d2 100644 --- a/apps/api/v2/src/modules/organizations/controllers/event-types/organizations-event-types.controller.ts +++ b/apps/api/v2/src/modules/organizations/controllers/event-types/organizations-event-types.controller.ts @@ -1,3 +1,5 @@ +import { CreatePhoneCallInput } from "@/ee/event-types/event-types_2024_06_14/inputs/create-phone-call.input"; +import { CreatePhoneCallOutput } from "@/ee/event-types/event-types_2024_06_14/outputs/create-phone-call.output"; import { API_VERSIONS_VALUES } from "@/lib/api-versions"; import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.decorator"; import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator"; @@ -33,6 +35,7 @@ import { import { ApiTags as DocsTags } from "@nestjs/swagger"; import { SUCCESS_STATUS } from "@calcom/platform-constants"; +import { handleCreatePhoneCall } from "@calcom/platform-libraries"; import { CreateTeamEventTypeInput_2024_06_14, GetTeamEventTypesQuery_2024_06_14, @@ -91,6 +94,30 @@ export class OrganizationsEventTypesController { }; } + @Roles("TEAM_ADMIN") + @Post("/teams/:teamId/event-types/:eventTypeId/create-phone-call") + @UseGuards(ApiAuthGuard, IsOrgGuard, IsTeamInOrg, RolesGuard) + async createPhoneCall( + @Param("eventTypeId") eventTypeId: number, + @Param("orgId", ParseIntPipe) orgId: number, + @Body() body: CreatePhoneCallInput, + @GetUser() user: UserWithProfile + ): Promise { + const data = await handleCreatePhoneCall({ + user: { + id: user.id, + timeZone: user.timeZone, + profile: { organization: { id: orgId } }, + }, + input: { ...body, eventTypeId }, + }); + + return { + status: SUCCESS_STATUS, + data, + }; + } + @UseGuards(IsOrgGuard, IsTeamInOrg, IsAdminAPIEnabledGuard) @Get("/teams/:teamId/event-types") async getTeamEventTypes( @@ -138,7 +165,7 @@ export class OrganizationsEventTypesController { @Patch("/teams/:teamId/event-types/:eventTypeId") async updateTeamEventType( @Param("teamId", ParseIntPipe) teamId: number, - @Param("eventTypeId") eventTypeId: number, + @Param("eventTypeId", ParseIntPipe) eventTypeId: number, @GetUser() user: UserWithProfile, @Body() bodyEventType: UpdateTeamEventTypeInput_2024_06_14 ): Promise { diff --git a/apps/api/v2/swagger/documentation.json b/apps/api/v2/swagger/documentation.json index 219408b271..f9f0083a60 100644 --- a/apps/api/v2/swagger/documentation.json +++ b/apps/api/v2/swagger/documentation.json @@ -1982,6 +1982,54 @@ ] } }, + "/v2/organizations/{orgId}/teams/{teamId}/event-types/{eventTypeId}/create-phone-call": { + "post": { + "operationId": "OrganizationsEventTypesController_createPhoneCall", + "parameters": [ + { + "name": "eventTypeId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + }, + { + "name": "orgId", + "required": true, + "in": "path", + "schema": { + "type": "number" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatePhoneCallInput" + } + } + } + }, + "responses": { + "201": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatePhoneCallOutput" + } + } + } + } + }, + "tags": [ + "Organizations Event Types" + ] + } + }, "/v2/organizations/{orgId}/teams/event-types": { "get": { "operationId": "OrganizationsEventTypesController_getTeamsEventTypes", @@ -3324,7 +3372,31 @@ "/v2/calendars/busy-times": { "get": { "operationId": "CalendarsController_getBusyTimes", - "parameters": [], + "parameters": [ + { + "name": "loggedInUsersTz", + "required": true, + "in": "query", + "description": "The timezone of the logged in user represented as a string", + "example": "America/New_York", + "schema": { + "type": "string" + } + }, + { + "name": "calendarsToLoad", + "required": true, + "in": "query", + "description": "An array of Calendar objects representing the calendars to be loaded", + "example": "[{ credentialId: \"1\", externalId: \"AQgtJE7RnHEeyisVq2ENs2gAAAgEGAAAACgtJE7RnHEeyisVq2ENs2gAAAhSDAAAA\" }, { credentialId: \"2\", externalId: \"AQM7RnHEeyisVq2ENs2gAAAhFDBBBBB\" }]", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + ], "responses": { "200": { "description": "", @@ -7794,6 +7866,90 @@ "data" ] }, + "CreatePhoneCallInput": { + "type": "object", + "properties": { + "yourPhoneNumber": { + "type": "string", + "pattern": "/^\\+[1-9]\\d{1,14}$/", + "description": "Your phone number" + }, + "numberToCall": { + "type": "string", + "pattern": "/^\\+[1-9]\\d{1,14}$/", + "description": "Number to call" + }, + "calApiKey": { + "type": "string", + "description": "CAL API Key" + }, + "enabled": { + "type": "object", + "default": true, + "description": "Enabled status" + }, + "templateType": { + "default": "CUSTOM_TEMPLATE", + "enum": [ + "CHECK_IN_APPOINTMENT", + "CUSTOM_TEMPLATE" + ], + "type": "string", + "description": "Template type" + }, + "schedulerName": { + "type": "string", + "description": "Scheduler name" + }, + "guestName": { + "type": "string", + "description": "Guest name" + }, + "guestEmail": { + "type": "string", + "description": "Guest email" + }, + "guestCompany": { + "type": "string", + "description": "Guest company" + }, + "beginMessage": { + "type": "string", + "description": "Begin message" + }, + "generalPrompt": { + "type": "string", + "description": "General prompt" + } + }, + "required": [ + "yourPhoneNumber", + "numberToCall", + "calApiKey", + "enabled", + "templateType" + ] + }, + "CreatePhoneCallOutput": { + "type": "object", + "properties": { + "status": { + "type": "string", + "example": "success", + "enum": [ + "success", + "error" + ] + }, + "data": { + "$ref": "#/components/schemas/Data" + } + }, + "required": [ + "status", + "data" + ] + }, "GetTeamEventTypesOutput": { "type": "object", "properties": { @@ -8636,7 +8792,8 @@ "MEETING_STARTED", "RECORDING_READY", "INSTANT_MEETING", - "RECORDING_TRANSCRIPTION_GENERATED" + "RECORDING_TRANSCRIPTION_GENERATED", + "OOO_CREATED" ] }, "active": { @@ -8709,7 +8866,8 @@ "MEETING_STARTED", "RECORDING_READY", "INSTANT_MEETING", - "RECORDING_TRANSCRIPTION_GENERATED" + "RECORDING_TRANSCRIPTION_GENERATED", + "OOO_CREATED" ] }, "active": { @@ -10304,9 +10462,6 @@ "rescheduleUid": { "type": "string" }, - "recurringEventId": { - "type": "string" - }, "timeZone": { "type": "string" }, diff --git a/packages/features/ee/cal-ai-phone/retellAIService.ts b/packages/features/ee/cal-ai-phone/retellAIService.ts index ed911c6949..b903c8883f 100644 --- a/packages/features/ee/cal-ai-phone/retellAIService.ts +++ b/packages/features/ee/cal-ai-phone/retellAIService.ts @@ -31,7 +31,7 @@ type initProps = { eventTypeId: number; calApiKey: string; loggedInUserTimeZone: string; - beginMessage?: string; + beginMessage?: string | null; dynamicVariables: DynamicVariables; generalPrompt: string; }; diff --git a/packages/features/ee/cal-ai-phone/zod-utils.ts b/packages/features/ee/cal-ai-phone/zod-utils.ts index 994484f752..16452a296e 100644 --- a/packages/features/ee/cal-ai-phone/zod-utils.ts +++ b/packages/features/ee/cal-ai-phone/zod-utils.ts @@ -130,7 +130,7 @@ export type TCreateRetellLLMSchema = z.infer; export const ZGetRetellLLMSchema = z .object({ general_prompt: z.string(), - begin_message: z.string().nullable(), + begin_message: z.string().nullable().optional(), llm_id: z.string(), llm_websocket_url: z.string(), general_tools: z.array( diff --git a/packages/features/eventtypes/components/tabs/ai/AIEventController.tsx b/packages/features/eventtypes/components/tabs/ai/AIEventController.tsx index b7cf8df83e..632e6f28ee 100644 --- a/packages/features/eventtypes/components/tabs/ai/AIEventController.tsx +++ b/packages/features/eventtypes/components/tabs/ai/AIEventController.tsx @@ -150,7 +150,7 @@ const AISettings = ({ eventType }: { eventType: EventTypeSetup }) => { const createCallMutation = trpc.viewer.organizations.createPhoneCall.useMutation({ onSuccess: (data) => { - if (!!data?.call_id) { + if (!!data?.callId) { showToast("Phone Call Created successfully", "success"); } }, @@ -175,6 +175,7 @@ const AISettings = ({ eventType }: { eventType: EventTypeSetup }) => { guestName: values.guestName && values.guestName.trim().length ? values.guestName : undefined, eventTypeId: eventType.id, calApiKey, + id: eventType.id, }); createCallMutation.mutate(data); diff --git a/packages/features/handleCreatePhoneCall.ts b/packages/features/handleCreatePhoneCall.ts new file mode 100644 index 0000000000..c9b084fd61 --- /dev/null +++ b/packages/features/handleCreatePhoneCall.ts @@ -0,0 +1,126 @@ +import { PROMPT_TEMPLATES } from "@calcom/features/ee/cal-ai-phone/promptTemplates"; +import { RetellAIService, validatePhoneNumber } from "@calcom/features/ee/cal-ai-phone/retellAIService"; +import { templateTypeEnum } from "@calcom/features/ee/cal-ai-phone/zod-utils"; +import type { TCreatePhoneCallSchema } from "@calcom/features/ee/cal-ai-phone/zod-utils"; +import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError"; +import logger from "@calcom/lib/logger"; +import prisma from "@calcom/prisma"; + +import { TRPCError } from "@trpc/server"; + +export const handleCreatePhoneCall = async ({ + user, + input, +}: { + user: { timeZone: string; id: number; profile?: { organization?: { id?: number } } }; + input: TCreatePhoneCallSchema; +}) => { + if (!user?.profile?.organization) { + throw new TRPCError({ code: "UNAUTHORIZED", message: "User is not part of an organization" }); + } + + await checkRateLimitAndThrowError({ + rateLimitingType: "core", + identifier: `createPhoneCall:${user.id}`, + }); + + await validatePhoneNumber(input.yourPhoneNumber); + + const { + yourPhoneNumber, + numberToCall, + guestName, + guestEmail, + guestCompany, + eventTypeId, + beginMessage, + calApiKey, + templateType, + schedulerName, + generalPrompt: userCustomPrompt, + } = input; + + const generalPrompt = + templateType === templateTypeEnum.enum.CUSTOM_TEMPLATE + ? userCustomPrompt + : PROMPT_TEMPLATES[templateType]?.generalPrompt; + + const retellAI = new RetellAIService({ + templateType, + generalPrompt: generalPrompt ?? "", + beginMessage: beginMessage ?? null, + yourPhoneNumber, + loggedInUserTimeZone: user.timeZone, + eventTypeId, + calApiKey, + dynamicVariables: { + guestName, + guestEmail, + guestCompany, + schedulerName, + }, + }); + + const aiPhoneCallConfig = await prisma.aIPhoneCallConfiguration.upsert({ + where: { + eventTypeId, + }, + update: { + beginMessage, + enabled: true, + guestName, + guestEmail, + guestCompany, + numberToCall, + yourPhoneNumber, + schedulerName, + templateType, + generalPrompt, + }, + create: { + eventTypeId, + beginMessage, + enabled: true, + guestName, + guestEmail, + guestCompany, + numberToCall, + yourPhoneNumber, + schedulerName, + templateType, + generalPrompt, + }, + }); + + // If no retell LLM is associated with the event type, create one + if (!aiPhoneCallConfig.llmId) { + const createdRetellLLM = await retellAI.createRetellLLMAndUpdateWebsocketUrl(); + + await prisma.aIPhoneCallConfiguration.update({ + where: { + eventTypeId, + }, + data: { + llmId: createdRetellLLM.llm_id, + }, + }); + } else { + // aiPhoneCallConfig.llmId would be set here in the else block + const retellLLM = await retellAI.getRetellLLM(aiPhoneCallConfig.llmId as string); + + const shouldUpdateLLM = + retellLLM.general_prompt !== generalPrompt || retellLLM.begin_message !== beginMessage; + + if (shouldUpdateLLM) { + const updatedRetellLLM = await retellAI.updatedRetellLLMAndUpdateWebsocketUrl( + aiPhoneCallConfig.llmId as string + ); + logger.debug("updated Retell LLM", updatedRetellLLM); + } + } + + const createPhoneCallRes = await retellAI.createRetellPhoneCall(numberToCall); + logger.debug("Create Call Response", createPhoneCallRes); + + return { callId: createPhoneCallRes.call_id, agentId: createPhoneCallRes.agent_id }; +}; diff --git a/packages/lib/constants.ts b/packages/lib/constants.ts index 1ce361a791..35802b7ddb 100644 --- a/packages/lib/constants.ts +++ b/packages/lib/constants.ts @@ -94,6 +94,7 @@ export const IS_STRIPE_ENABLED = !!( ); /** This has correct value only server side. When you want to use client side, go for IS_TEAM_BILLING_ENABLED_CLIENT. I think we should use the _CLIENT one only everywhere so that it works reliably everywhere on client as well as server */ export const IS_TEAM_BILLING_ENABLED = IS_STRIPE_ENABLED && HOSTED_CAL_FEATURES; + export const IS_TEAM_BILLING_ENABLED_CLIENT = !!process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY && HOSTED_CAL_FEATURES; diff --git a/packages/platform/libraries/index.ts b/packages/platform/libraries/index.ts index 77f74c1001..c3c7f802e9 100644 --- a/packages/platform/libraries/index.ts +++ b/packages/platform/libraries/index.ts @@ -5,6 +5,7 @@ import getBookingInfo from "@calcom/features/bookings/lib/getBookingInfo"; import handleCancelBooking from "@calcom/features/bookings/lib/handleCancelBooking"; import * as newBookingMethods from "@calcom/features/bookings/lib/handleNewBooking"; import { getPublicEvent } from "@calcom/features/eventtypes/lib/getPublicEvent"; +import { handleCreatePhoneCall } from "@calcom/features/handleCreatePhoneCall"; import handleMarkNoShow from "@calcom/features/handleMarkNoShow"; import * as instantMeetingMethods from "@calcom/features/instant-meeting/handleInstantMeeting"; import getAllUserBookings from "@calcom/lib/bookings/getAllUserBookings"; @@ -48,6 +49,7 @@ const handleInstantMeeting = instantMeetingMethods.default; export { handleInstantMeeting }; export { handleMarkNoShow }; +export { handleCreatePhoneCall }; export { getAvailableSlots }; export type AvailableSlotsType = Awaited>; diff --git a/packages/trpc/server/routers/viewer/eventTypes/util.ts b/packages/trpc/server/routers/viewer/eventTypes/util.ts index a4891c05a7..b464229f51 100644 --- a/packages/trpc/server/routers/viewer/eventTypes/util.ts +++ b/packages/trpc/server/routers/viewer/eventTypes/util.ts @@ -18,15 +18,22 @@ type EventType = Awaited>[n export const eventOwnerProcedure = authedProcedure .input( - z.object({ - id: z.number(), - users: z.array(z.number()).optional().default([]), - }) + z + .object({ + id: z.number().optional(), + eventTypeId: z.number().optional(), + users: z.array(z.number()).optional().default([]), + }) + .refine((data) => data.id !== undefined || data.eventTypeId !== undefined, { + message: "At least one of 'id' or 'eventTypeId' must be present", + path: ["id", "eventTypeId"], + }) ) .use(async ({ ctx, input, next }) => { + const id = input.eventTypeId ?? input.id; // Prevent non-owners to update/delete a team event const event = await ctx.prisma.eventType.findUnique({ - where: { id: input.id }, + where: { id }, include: { users: { select: { diff --git a/packages/trpc/server/routers/viewer/organizations/_router.tsx b/packages/trpc/server/routers/viewer/organizations/_router.tsx index 4392508ff3..4761600aed 100644 --- a/packages/trpc/server/routers/viewer/organizations/_router.tsx +++ b/packages/trpc/server/routers/viewer/organizations/_router.tsx @@ -6,6 +6,7 @@ import authedProcedure, { authedOrgAdminProcedure, } from "../../../procedures/authedProcedure"; import { importHandler, router } from "../../../trpc"; +import { eventOwnerProcedure } from "../eventTypes/util"; import { ZAddMembersToEventTypes } from "./addMembersToEventTypes.schema"; import { ZAddMembersToTeams } from "./addMembersToTeams.schema"; import { ZAdminDeleteInput } from "./adminDelete.schema"; @@ -161,7 +162,7 @@ export const viewerOrganizationsRouter = router({ const handler = await importHandler(namespaced("adminDelete"), () => import("./adminDelete.handler")); return handler(opts); }), - createPhoneCall: authedProcedure.input(createPhoneCallSchema).mutation(async (opts) => { + createPhoneCall: eventOwnerProcedure.input(createPhoneCallSchema).mutation(async (opts) => { const handler = await importHandler( namespaced("createPhoneCall"), () => import("./createPhoneCall.handler") diff --git a/packages/trpc/server/routers/viewer/organizations/createPhoneCall.handler.ts b/packages/trpc/server/routers/viewer/organizations/createPhoneCall.handler.ts index 9bec06ad2c..5d73b0b43c 100644 --- a/packages/trpc/server/routers/viewer/organizations/createPhoneCall.handler.ts +++ b/packages/trpc/server/routers/viewer/organizations/createPhoneCall.handler.ts @@ -1,13 +1,8 @@ import type { z } from "zod"; -import { PROMPT_TEMPLATES } from "@calcom/features/ee/cal-ai-phone/promptTemplates"; -import { RetellAIService, validatePhoneNumber } from "@calcom/features/ee/cal-ai-phone/retellAIService"; import type { createPhoneCallSchema } from "@calcom/features/ee/cal-ai-phone/zod-utils"; -import { templateTypeEnum } from "@calcom/features/ee/cal-ai-phone/zod-utils"; -import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError"; -import logger from "@calcom/lib/logger"; +import { handleCreatePhoneCall } from "@calcom/features/handleCreatePhoneCall"; import type { PrismaClient } from "@calcom/prisma"; -import { TRPCError } from "@calcom/trpc/server"; import type { TrpcSessionUser } from "@calcom/trpc/server/trpc"; type CreatePhoneCallProps = { @@ -19,109 +14,14 @@ type CreatePhoneCallProps = { }; const createPhoneCallHandler = async ({ input, ctx }: CreatePhoneCallProps) => { - if (!!!ctx.user.profile.organization) { - throw new TRPCError({ code: "UNAUTHORIZED" }); - } - - await checkRateLimitAndThrowError({ - rateLimitingType: "core", - identifier: `createPhoneCall:${ctx.user.id}`, + return await handleCreatePhoneCall({ + user: { + id: ctx.user.id, + timeZone: ctx.user.timeZone, + profile: { organization: { id: ctx.user.profile.organization?.id } }, + }, + input, }); - - await validatePhoneNumber(input.yourPhoneNumber); - - const { - yourPhoneNumber, - numberToCall, - guestName, - guestEmail, - guestCompany, - eventTypeId, - beginMessage, - calApiKey, - templateType, - schedulerName, - generalPrompt: userCustomPrompt, - } = input; - - const generalPrompt = - templateType === templateTypeEnum.enum.CUSTOM_TEMPLATE - ? userCustomPrompt - : PROMPT_TEMPLATES[templateType]?.generalPrompt; - - const retellAI = new RetellAIService({ - templateType, - generalPrompt: generalPrompt ?? "", - yourPhoneNumber, - loggedInUserTimeZone: ctx.user.timeZone, - eventTypeId, - calApiKey, - dynamicVariables: { - guestName, - guestEmail, - guestCompany, - schedulerName, - }, - }); - - const aiPhoneCallConfig = await ctx.prisma.aIPhoneCallConfiguration.upsert({ - where: { - eventTypeId, - }, - update: { - beginMessage, - enabled: true, - guestName, - guestEmail, - guestCompany, - numberToCall, - yourPhoneNumber, - schedulerName, - templateType, - generalPrompt, - }, - create: { - eventTypeId, - beginMessage, - enabled: true, - guestName, - guestEmail, - guestCompany, - numberToCall, - yourPhoneNumber, - schedulerName, - templateType, - generalPrompt, - }, - }); - - // If no retell LLM is associated with the event type, create one - if (!aiPhoneCallConfig.llmId) { - const createdRetellLLM = await retellAI.createRetellLLMAndUpdateWebsocketUrl(); - - await ctx.prisma.aIPhoneCallConfiguration.update({ - where: { - eventTypeId, - }, - data: { - llmId: createdRetellLLM.llm_id, - }, - }); - } else { - const retellLLM = await retellAI.getRetellLLM(aiPhoneCallConfig.llmId); - - const doWeNeedToUpdateLLM = - retellLLM.general_prompt !== generalPrompt || retellLLM.begin_message !== beginMessage; - if (doWeNeedToUpdateLLM) { - const updatedRetellLLM = await retellAI.updatedRetellLLMAndUpdateWebsocketUrl(aiPhoneCallConfig.llmId); - logger.debug("updated Retell LLM", updatedRetellLLM); - } - } - - const createPhoneCallRes = await retellAI.createRetellPhoneCall(numberToCall); - logger.debug("Create Call Response", createPhoneCallRes); - - return createPhoneCallRes; }; export default createPhoneCallHandler;