Files
cal.diy/packages/trpc/server/routers/viewer/aiVoiceAgent/testCall.handler.ts
T
Udit TakkarandCarinaWolli 2df2868b20 fix: cal ai webhook (#24368)
* fix: cal ai email

* fix: remove

* fix: org

* replace Cal AI with Cal.ai

* fix: use

* fix: feedback

* fix: types

* fix: types

* fix: types

* fix: tests

* Merge branch 'main' into fix/cal-ai-credits

* refactor: feedback

* refactor: imporvement

* fix: type

* refactor: feedback

* fix: tests

* fix: use pbac

---------

Co-authored-by: CarinaWolli <[email protected]>
2025-11-05 13:31:55 +04:00

70 lines
2.1 KiB
TypeScript

import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import logger from "@calcom/lib/logger";
import { PrismaAgentRepository } from "@calcom/lib/server/repository/PrismaAgentRepository";
import prisma from "@calcom/prisma";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../types";
import type { TTestCallInputSchema } from "./testCall.schema";
type TestCallHandlerOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TTestCallInputSchema;
};
export const testCallHandler = async ({ ctx, input }: TestCallHandlerOptions) => {
const timeZone = ctx.user.timeZone ?? "Europe/London";
const eventTypeId = input.eventTypeId;
const featuresRepository = new FeaturesRepository(prisma);
const calAIVoiceAgents = await featuresRepository.checkIfFeatureIsEnabledGlobally("cal-ai-voice-agents");
if (!calAIVoiceAgents) {
logger.warn("Cal.ai voice agents are disabled - skipping AI phone call scheduling");
return;
}
const agentRepo = new PrismaAgentRepository(prisma);
const agent = await agentRepo.findByIdWithCallAccess({
id: input.agentId,
userId: ctx.user.id,
});
if (!agent?.providerAgentId) {
logger.error(`Agent not found with agentId ${input.agentId}`);
throw new TRPCError({
code: "BAD_REQUEST",
message: "Agent not found",
});
}
const aiService = createDefaultAIPhoneServiceProvider();
try {
await aiService.updateToolsFromAgentId(agent.providerAgentId, {
eventTypeId,
timeZone,
userId: ctx.user.id,
teamId: input.teamId,
});
} catch (error) {
logger.error(`Failed to update tools for agent ${agent.providerAgentId}: ${error}`);
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to test the event type. Failed to update tools for agent",
});
}
return await aiService.createTestCall({
agentId: input.agentId,
phoneNumber: input.phoneNumber,
userId: ctx.user.id,
teamId: input.teamId,
timeZone,
eventTypeId,
});
};