Files
calendar/packages/features/handleCreatePhoneCall.ts
T
Benny JooGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
3bf2a8fa6c refactor: replace TRPCError with ErrorWithCode in packages/features (#25482)
* refactor: replace TRPCError with ErrorWithCode in packages/features

This refactor moves error handling from throwing TRPCError directly in
packages/features to throwing ErrorWithCode instead. The conversion to
TRPCError now happens at the TRPC layer.

Changes:
- Add generic ErrorCode values (Unauthorized, Forbidden, NotFound,
  BadRequest, InternalServerError) to errorCodes.ts
- Update getServerErrorFromUnknown to map new ErrorCodes to proper
  HTTP status codes
- Create toTRPCError helper in packages/trpc/server/lib
- Create errorMappingMiddleware in packages/trpc/server/middlewares
- Migrate TRPCError throws in packages/features to ErrorWithCode:
  - teamService.ts
  - getEventTypeById.ts
  - eventTypeRepository.ts
  - OrganizationPermissionService.ts
  - OrganizationPaymentService.ts
  - sso.ts
  - handleCreatePhoneCall.ts
  - userCanCreateTeamGroupMapping.ts

This improves separation of concerns by making packages/features
transport-agnostic, allowing the same feature code to be reused from
tRPC, API routes, workers, etc.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: remove isTrpcCall parameter and fix lint warning

- Remove isTrpcCall parameter from get.handler.ts call since the
  feature layer no longer needs to know about tRPC
- Fix unsafe optional chaining lint warning in getEventTypesByViewer.ts
  by precomputing usersSource variable
- Complete migration of getEventTypesByViewer.ts to ErrorWithCode

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* revert

* add eslint rule

* add comment

* fix: add isTrpcCall back to getEventTypeById interface

The user reverted the removal of isTrpcCall parameter from the handler,
so we need to add it back to the interface to fix the type error.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* test: update teamService tests to expect ErrorWithCode instead of TRPCError

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* refactor

* wip

* feat: integrate errorMappingMiddleware into base TRPC procedure

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* connect middlewares

* revert

* revert

* refactor

* rename

* fix: handle ErrorWithCode in teams server-page error handling

The error handling was checking for TRPCError, but teamService now throws
ErrorWithCode. This caused the 'This invitation is not for your account'
error message to not be displayed when a wrong user tries to use an
invitation link.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix

* fix

* fix

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-02 08:11:17 -03:00

127 lines
3.4 KiB
TypeScript

import { PROMPT_TEMPLATES, LegacyRetellAIService } from "@calcom/features/calAIPhone";
import { templateTypeEnum } from "@calcom/features/calAIPhone";
import type { TCreatePhoneCallSchema } from "@calcom/features/calAIPhone";
import { validatePhoneNumber } from "@calcom/features/calAIPhone/retellAIService";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { ErrorWithCode } from "@calcom/lib/errors";
export const handleCreatePhoneCall = async ({
user,
input,
}: {
user: { timeZone: string; id: number; profile?: { organization?: { id?: number } } };
input: TCreatePhoneCallSchema;
}) => {
if (!user?.profile?.organization) {
throw new ErrorWithCode(ErrorCode.Unauthorized, "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 LegacyRetellAIService({
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 };
};