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 <[email protected]> Co-authored-by: Benny Joo <[email protected]> Co-authored-by: Morgan Vernay <[email protected]> Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
14 files changed
+444
-125
No files matched your search
@@ -28,7 +28,7 @@
|
||||
"dependencies": {
|
||||
"@calcom/platform-constants": "*",
|
||||
"@calcom/platform-enums": "*",
|
||||
"@calcom/platform-libraries": "npm:@calcom/[email protected]3",
|
||||
"@calcom/platform-libraries": "npm:@calcom/[email protected]4",
|
||||
"@calcom/platform-libraries-0.0.2": "npm:@calcom/[email protected]",
|
||||
"@calcom/platform-types": "*",
|
||||
"@calcom/platform-utils": "*",
|
||||
|
||||
+71
@@ -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: +<CountryCode><PhoneNumber> 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: +<CountryCode><PhoneNumber> 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;
|
||||
}
|
||||
+28
@@ -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;
|
||||
}
|
||||
+28
-1
@@ -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<CreatePhoneCallOutput> {
|
||||
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<UpdateTeamEventTypeOutput> {
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -31,7 +31,7 @@ type initProps = {
|
||||
eventTypeId: number;
|
||||
calApiKey: string;
|
||||
loggedInUserTimeZone: string;
|
||||
beginMessage?: string;
|
||||
beginMessage?: string | null;
|
||||
dynamicVariables: DynamicVariables;
|
||||
generalPrompt: string;
|
||||
};
|
||||
|
||||
@@ -130,7 +130,7 @@ export type TCreateRetellLLMSchema = z.infer<typeof ZCreateRetellLLMSchema>;
|
||||
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(
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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<ReturnType<typeof getAvailableSlots>>;
|
||||
|
||||
@@ -18,15 +18,22 @@ type EventType = Awaited<ReturnType<typeof EventTypeRepository.findAllByUpId>>[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: {
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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;
|
||||
Reference in new issue
Block a user