* feat: Cal.ai Self Serve #2 * chore: fix import and remove logs * fix: update checkout session * fix: type errors and test * fix: imports * fix: type err * fix: type error * fix: tests * chore: save progress * fix: workflow flow * fix: workflow update bug * tests: add unit tests for retell ai webhoo * fix: status code * fix: test and delete bug * fix: add dynamic variables * fix: type err * chore: update unit test * fix: type error * chore: update default prompt * fix: type errors * fix: workflow permissions * fix: workflow page * fix: translations * feat: add call duration * chore: add booking uid * fix: button positioning * chore: update tests * chore: improvements * chore: some more improvements * refactor: improvements * refactor: code feedback * refactor: improvements * feat: enable credits for orgs (#23077) * Show credits UI for orgs * fix stripe callback url when buying credits * give orgs 20% credits * add test for calulating credits --------- Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com> * fix: types * fix: types * chore: error * fix: type error * fix: type error * chore: mock env * feat: add idempotency key to prevent double charging * chore: add userId and teamId * fix: skip inbound calls * chore: update tests * feat: add feature flag for voice agent * feat: finish test call and other improvements * chore: add alert * chore: update .env.example * chore: improvements * fix: update tests * refactor: remove un necessary * feat: add setup badge * chore: improvements * fix: use referene id * chore: improvements * fix: type error * fix: type * refactor: change pricing logic * refactor: update tests * fix: conflicts * fix: billing link for orgs * fix: types * refactor: move feature flag up * fix: alert and test call credit check * fix: update unit tests * fix: feedback * refactor: improvements * refactor: move handlers to separate files * fix: types * fix: missing import * fix: type * refactor: change general tools functions handling * refactor: use repository * refactor: improvements * fix: types * fix: type errorr * fix: auth check * feat: add creditFor * fix: update defualt prompt * fix: throw error on frontend * fix: update unit tests * fix: use deleteAllWorkflowReminders * refactor: add connect phone number * refactor: improvements * chore: translation * chore: update message * chore: translation * design improvements buy number dialog * add translation for error message * use translation key in error message * refactor: improve connect phone number tab * feat: support un saved workflow to tests * chore: remove un used * fix: remove un used * fix: remove un used * refactor: similify billing --------- Co-authored-by: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com> Co-authored-by: CarinaWolli <wollencarina@gmail.com> Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Keith Williams <keithwillcode@gmail.com>
201 lines
5.7 KiB
TypeScript
201 lines
5.7 KiB
TypeScript
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
|
import { HttpError } from "@calcom/lib/http-error";
|
|
import logger from "@calcom/lib/logger";
|
|
|
|
import type {
|
|
AIPhoneServiceProviderType,
|
|
AIPhoneServiceCall,
|
|
} from "../../../interfaces/AIPhoneService.interface";
|
|
import type { AgentRepositoryInterface } from "../../interfaces/AgentRepositoryInterface";
|
|
import type { RetellAIRepository, RetellDynamicVariables } from "../types";
|
|
|
|
interface RetellAIServiceInterface {
|
|
updateToolsFromAgentId(
|
|
agentId: string,
|
|
data: { eventTypeId: number | null; timeZone: string; userId: number | null; teamId?: number | null }
|
|
): Promise<void>;
|
|
}
|
|
|
|
export class CallService {
|
|
private logger = logger.getSubLogger({ prefix: ["CallService"] });
|
|
private retellAIService?: RetellAIServiceInterface;
|
|
|
|
constructor(
|
|
private retellRepository: RetellAIRepository,
|
|
private agentRepository: AgentRepositoryInterface
|
|
) {}
|
|
|
|
setRetellAIService(service: RetellAIServiceInterface): void {
|
|
this.retellAIService = service;
|
|
}
|
|
|
|
async createPhoneCall(data: {
|
|
fromNumber: string;
|
|
toNumber: string;
|
|
dynamicVariables?: RetellDynamicVariables;
|
|
}): Promise<AIPhoneServiceCall<AIPhoneServiceProviderType.RETELL_AI>> {
|
|
if (!data.fromNumber?.trim()) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "From phone number is required and cannot be empty",
|
|
});
|
|
}
|
|
|
|
if (!data.toNumber?.trim()) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "To phone number is required and cannot be empty",
|
|
});
|
|
}
|
|
|
|
const { fromNumber, toNumber, dynamicVariables } = data;
|
|
|
|
try {
|
|
return await this.retellRepository.createPhoneCall({
|
|
fromNumber,
|
|
toNumber,
|
|
dynamicVariables,
|
|
});
|
|
} catch (error) {
|
|
this.logger.error("Failed to create phone call in external AI service", {
|
|
fromNumber: data.fromNumber,
|
|
toNumber: data.toNumber,
|
|
error,
|
|
});
|
|
throw new HttpError({
|
|
statusCode: 500,
|
|
message: `Failed to create phone call from ${data.fromNumber} to ${data.toNumber}`,
|
|
});
|
|
}
|
|
}
|
|
|
|
async createTestCall({
|
|
agentId,
|
|
phoneNumber,
|
|
userId,
|
|
teamId,
|
|
timeZone,
|
|
eventTypeId,
|
|
}: {
|
|
agentId: string;
|
|
phoneNumber?: string;
|
|
userId: number;
|
|
teamId?: number;
|
|
timeZone: string;
|
|
eventTypeId: number;
|
|
}) {
|
|
if (!agentId?.trim()) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "Agent ID is required and cannot be empty",
|
|
});
|
|
}
|
|
|
|
await this.validateCreditsForTestCall({ userId, teamId });
|
|
|
|
await checkRateLimitAndThrowError({
|
|
rateLimitingType: "core",
|
|
identifier: `test-call:${userId}`,
|
|
});
|
|
|
|
const toNumber = phoneNumber?.trim();
|
|
if (!toNumber) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "Phone number is required for test call",
|
|
});
|
|
}
|
|
|
|
const agent = await this.agentRepository.findByIdWithCallAccess({
|
|
id: agentId,
|
|
userId,
|
|
});
|
|
|
|
if (!agent) {
|
|
throw new HttpError({
|
|
statusCode: 404,
|
|
message: "Agent not found or you don't have permission to use it.",
|
|
});
|
|
}
|
|
|
|
const agentPhoneNumber = agent.outboundPhoneNumbers?.[0]?.phoneNumber;
|
|
|
|
if (!agentPhoneNumber) {
|
|
throw new HttpError({
|
|
statusCode: 400,
|
|
message: "Agent must have a phone number assigned to make calls.",
|
|
});
|
|
}
|
|
|
|
if (!this.retellAIService) {
|
|
this.logger.error("RetellAIService not configured before createTestCall");
|
|
throw new HttpError({
|
|
statusCode: 500,
|
|
message: "Internal configuration error: AI phone service not initialized",
|
|
});
|
|
}
|
|
|
|
const call = await this.createPhoneCall({
|
|
fromNumber: agentPhoneNumber,
|
|
toNumber: toNumber,
|
|
dynamicVariables: {
|
|
EVENT_NAME: "Test Call with Agent",
|
|
EVENT_DATE: "Monday, January 15, 2025",
|
|
EVENT_TIME: "2:00 PM",
|
|
EVENT_END_TIME: "2:30 PM",
|
|
TIMEZONE: timeZone,
|
|
LOCATION: "Phone Call",
|
|
ORGANIZER_NAME: "Cal.com AI Agent",
|
|
ATTENDEE_NAME: "Test User",
|
|
ATTENDEE_FIRST_NAME: "Test",
|
|
ATTENDEE_LAST_NAME: "User",
|
|
ATTENDEE_EMAIL: "testuser@example.com",
|
|
ATTENDEE_TIMEZONE: timeZone,
|
|
ADDITIONAL_NOTES: "This is a test call to verify the AI phone agent",
|
|
EVENT_START_TIME_IN_ATTENDEE_TIMEZONE: "2:00 PM",
|
|
EVENT_END_TIME_IN_ATTENDEE_TIMEZONE: "2:30 PM",
|
|
eventTypeId: eventTypeId.toString(),
|
|
},
|
|
});
|
|
|
|
return {
|
|
callId: call.call_id,
|
|
status: call.call_status,
|
|
message: `Call initiated to ${toNumber} with call_id ${call.call_id}`,
|
|
};
|
|
}
|
|
|
|
private async validateCreditsForTestCall({ userId, teamId }: { userId: number; teamId?: number }) {
|
|
try {
|
|
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
|
|
const creditService = new CreditService();
|
|
const hasCredits = await creditService.hasAvailableCredits({
|
|
userId: userId || undefined,
|
|
teamId: teamId || undefined,
|
|
});
|
|
|
|
if (!hasCredits) {
|
|
throw new HttpError({
|
|
statusCode: 403,
|
|
message: `Insufficient credits to make test call. Please purchase more credits.`,
|
|
});
|
|
}
|
|
} catch (error) {
|
|
// Re-throw HTTP errors (like insufficient credits) as-is
|
|
if (error instanceof HttpError) {
|
|
throw error;
|
|
}
|
|
|
|
this.logger.error("Failed to validate credits for test call", {
|
|
userId,
|
|
teamId,
|
|
error,
|
|
});
|
|
throw new HttpError({
|
|
statusCode: 500,
|
|
message: "Unable to validate credits. Please try again.",
|
|
});
|
|
}
|
|
}
|
|
}
|