feat: Cal.ai Self Serve #2 (#22995)

* 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 <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>

* 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 <[email protected]>
Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-08-29 05:04:05 +01:00
1 parent 6defa1cd7d
commit d4bff9d6b1
118 files changed
+6650 -918

No files matched your search

@@ -10,7 +10,9 @@ export const SystemField = z.enum([
"rescheduleReason",
"smsReminderNumber",
"attendeePhoneNumber",
"aiAgentCallPhoneNumber",
]);
export const SMS_REMINDER_NUMBER_FIELD = "smsReminderNumber";
export const CAL_AI_AGENT_PHONE_NUMBER_FIELD = "aiAgentCallPhoneNumber";
export const TITLE_FIELD = "title";
@@ -1,7 +1,10 @@
import type { EventTypeCustomInput, EventType } from "@prisma/client";
import type { z } from "zod";
import { SMS_REMINDER_NUMBER_FIELD } from "@calcom/features/bookings/lib/SystemField";
import {
SMS_REMINDER_NUMBER_FIELD,
CAL_AI_AGENT_PHONE_NUMBER_FIELD,
} from "@calcom/features/bookings/lib/SystemField";
import type { Workflow } from "@calcom/features/ee/workflows/lib/types";
import { fieldsThatSupportLabelAsSafeHtml } from "@calcom/features/form-builder/fieldsThatSupportLabelAsSafeHtml";
import { getFieldIdentifier } from "@calcom/features/form-builder/utils/getFieldIdentifier";
@@ -52,6 +55,29 @@ export const getSmsReminderNumberSource = ({
editUrl: `/workflows/${workflowId}`,
});
export const getAIAgentCallPhoneNumberField = () =>
({
name: CAL_AI_AGENT_PHONE_NUMBER_FIELD,
type: "phone",
defaultLabel: "phone_number_for_ai_call",
defaultPlaceholder: "enter_phone_number",
editable: "system",
} as const);
export const getAIAgentCallPhoneNumberSource = ({
workflowId,
isAIAgentCallPhoneNumberRequired,
}: {
workflowId: Workflow["id"];
isAIAgentCallPhoneNumberRequired: boolean;
}) => ({
id: `${workflowId}`,
type: "workflow",
label: "Workflow",
fieldRequired: isAIAgentCallPhoneNumberRequired,
editUrl: `/workflows/${workflowId}`,
});
/**
* This fn is the key to ensure on the fly mapping of customInputs to bookingFields and ensuring that all the systems fields are present and correctly ordered in bookingFields
*/
@@ -102,7 +102,7 @@ describe("AIPhoneServiceRegistry", () => {
AIPhoneServiceRegistry.initialize();
expect(AIPhoneServiceRegistry.isInitialized()).toBe(true);
expect(AIPhoneServiceRegistry.getDefaultProvider()).toBeNull();
expect(AIPhoneServiceRegistry.getDefaultProvider()).toBe(AIPhoneServiceProviderType.RETELL_AI);
});
});
@@ -114,10 +114,10 @@ describe("AIPhoneServiceRegistry", () => {
expect(AIPhoneServiceRegistry.getAvailableProviders()).toContain("test-provider");
});
it("should set first registered provider as default", () => {
it("should keep default as retellAI even after registering provider", () => {
AIPhoneServiceRegistry.registerProvider("test-provider", mockFactory);
expect(AIPhoneServiceRegistry.getDefaultProvider()).toBe("test-provider");
expect(AIPhoneServiceRegistry.getDefaultProvider()).toBe(AIPhoneServiceProviderType.RETELL_AI);
});
it("should allow overriding existing provider", () => {
@@ -190,12 +190,12 @@ describe("AIPhoneServiceRegistry", () => {
expect(provider).toBe(mockProvider);
});
it("should throw error when no default provider is set", () => {
it("should throw error when default provider is not registered", () => {
const config: AIPhoneServiceProviderConfig = { apiKey: "test-key" };
expect(() => {
AIPhoneServiceRegistry.createDefaultProvider(config);
}).toThrow("No default provider set");
}).toThrow("AI phone service provider 'retellAI' not found");
});
});
@@ -225,8 +225,8 @@ describe("AIPhoneServiceRegistry", () => {
expect(AIPhoneServiceRegistry.getDefaultProvider()).toBe("test-provider");
});
it("should return null when no default provider is set", () => {
expect(AIPhoneServiceRegistry.getDefaultProvider()).toBeNull();
it("should return retellAI as default provider", () => {
expect(AIPhoneServiceRegistry.getDefaultProvider()).toBe(AIPhoneServiceProviderType.RETELL_AI);
});
});
@@ -296,19 +296,19 @@ describe("createAIPhoneServiceProvider", () => {
};
});
it("should throw error when registry is not initialized", () => {
it("should automatically initialize registry when not initialized", () => {
// Registry starts uninitialized
expect(AIPhoneServiceRegistry.isInitialized()).toBe(false);
// Should throw error for uninitialized registry
// Should automatically initialize the registry and create provider
expect(() => {
createAIPhoneServiceProvider({
config: { apiKey: "test-key" },
});
}).toThrow("AIPhoneServiceRegistry not initialized");
}).not.toThrow();
// Registry should still be uninitialized
expect(AIPhoneServiceRegistry.isInitialized()).toBe(false);
// Registry should now be initialized
expect(AIPhoneServiceRegistry.isInitialized()).toBe(true);
});
it("should create provider with specified type and config", () => {
@@ -376,12 +376,12 @@ describe("createAIPhoneServiceProvider", () => {
});
});
it("should throw error when no provider type and no default provider", () => {
it("should throw error when default provider is not registered", () => {
AIPhoneServiceRegistry.initialize(); // Initialize without providers
expect(() => {
createAIPhoneServiceProvider();
}).toThrow("No provider type specified and no default provider configured");
}).toThrow("AI phone service provider 'retellAI' not found");
});
});
@@ -1,3 +1,4 @@
import { ensureAIPhoneServiceRegistryInitialized } from "./initializeRegistry";
import { AIPhoneServiceProviderType } from "./interfaces/AIPhoneService.interface";
import type {
AIPhoneServiceProvider,
@@ -22,7 +23,7 @@ interface RegistryConfiguration {
*/
export class AIPhoneServiceRegistry {
private static factories: Map<string, AIPhoneServiceProviderFactory> = new Map();
private static defaultProvider: string | null = null;
private static defaultProvider: string = AIPhoneServiceProviderType.RETELL_AI;
private static initialized = false;
/**
@@ -81,7 +82,7 @@ export class AIPhoneServiceRegistry {
"No default provider set. Please initialize the registry with a default provider or register at least one provider."
);
}
return this.createProvider(this.defaultProvider, config);
return this.createProvider(AIPhoneServiceRegistry.defaultProvider, config);
}
static setDefaultProvider(type: string): void {
@@ -92,7 +93,7 @@ export class AIPhoneServiceRegistry {
}
static getDefaultProvider(): string | null {
return this.defaultProvider;
return AIPhoneServiceRegistry.defaultProvider;
}
static getAvailableProviders(): string[] {
@@ -108,12 +109,12 @@ export class AIPhoneServiceRegistry {
*/
static clearProviders(): void {
this.factories.clear();
this.defaultProvider = null;
this.defaultProvider = AIPhoneServiceProviderType.RETELL_AI;
this.initialized = false;
}
static isInitialized(): boolean {
return this.initialized;
return AIPhoneServiceRegistry.initialized;
}
}
@@ -156,12 +157,8 @@ interface CreateProviderOptions {
}
export function createAIPhoneServiceProvider(options: CreateProviderOptions = {}): AIPhoneServiceProvider {
// Require explicit initialization
if (!AIPhoneServiceRegistry.isInitialized()) {
throw new Error(
"AIPhoneServiceRegistry not initialized. Please call initializeAIPhoneServiceRegistry() or AIPhoneServiceRegistry.initialize() during application startup."
);
}
// Ensure the registry is initialized before creating a provider
ensureAIPhoneServiceRegistryInitialized();
const { providerType, config } = options;
@@ -7,7 +7,6 @@ import { RetellAIPhoneServiceProviderFactory } from "./providers/retellAI";
* This function should be called during application startup
*/
export function initializeAIPhoneServiceRegistry(): void {
// Use Retell AI as the default provider
const defaultProvider = AIPhoneServiceProviderType.RETELL_AI;
// Build providers configuration - only Retell AI for now
@@ -18,7 +17,6 @@ export function initializeAIPhoneServiceRegistry(): void {
},
];
// Initialize the registry
AIPhoneServiceRegistry.initialize({
defaultProvider,
providers,
@@ -120,7 +120,7 @@ export interface AIPhoneServiceAgentListItem {
name: string;
providerAgentId: string;
enabled: boolean;
userId: number;
userId: number | null;
teamId: number | null;
createdAt: Date;
updatedAt: Date;
@@ -138,7 +138,7 @@ export interface AIPhoneServiceAgentListItem {
user: {
id: number;
name: string | null | undefined;
email: string | undefined;
email: string | null;
} | null;
}
@@ -191,7 +191,9 @@ export interface AIPhoneServiceProvider<T extends AIPhoneServiceProviderType = A
/**
* Create a phone number
*/
createPhoneNumber(data: AIPhoneServiceCreatePhoneNumberParams<T>): Promise<AIPhoneServicePhoneNumber<T>>;
createPhoneNumber(
data: AIPhoneServiceCreatePhoneNumberParams<T>
): Promise<AIPhoneServicePhoneNumber<T> & { provider: string }>;
/**
* Delete a phone number
@@ -295,6 +297,7 @@ export interface AIPhoneServiceProvider<T extends AIPhoneServiceProviderType = A
updateAgentConfiguration(params: {
id: string;
userId: number;
teamId?: number;
name?: string;
enabled?: boolean;
generalPrompt?: string | null;
@@ -316,11 +319,26 @@ export interface AIPhoneServiceProvider<T extends AIPhoneServiceProviderType = A
phoneNumber?: string;
userId: number;
teamId?: number;
timeZone: string;
eventTypeId: number;
}): Promise<{
callId: string;
status: string;
message: string;
}>;
/**
* Update tools from event type ID
*/
updateToolsFromAgentId(
agentId: string,
data: { eventTypeId: number | null; timeZone: string; userId: number | null; teamId?: number | null }
): Promise<void>;
/**
* Remove tools for event types
*/
removeToolsForEventTypes(agentId: string, eventTypeIds: number[]): Promise<void>;
}
/**
@@ -0,0 +1,92 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import type Stripe from "stripe";
import { z } from "zod";
import { CHECKOUT_SESSION_TYPES } from "@calcom/features/ee/billing/constants";
import stripe from "@calcom/features/ee/payments/server/stripe";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
const querySchema = z.object({
session_id: z.string().min(1),
});
const log = logger.getSubLogger({ prefix: ["[calAIPhone] subscription/success"] });
const checkoutSessionMetadataSchema = z.object({
userId: z.coerce.number().int().positive(),
teamId: z.coerce.number().int().optional(),
eventTypeId: z.coerce.number().int().positive().optional(),
agentId: z.string().optional(),
workflowId: z.string().optional(),
type: z.literal(CHECKOUT_SESSION_TYPES.PHONE_NUMBER_SUBSCRIPTION),
});
type CheckoutSessionMetadata = z.infer<typeof checkoutSessionMetadataSchema>;
async function handler(request: NextRequest) {
try {
const { session_id } = querySchema.parse(Object.fromEntries(request.nextUrl.searchParams));
const checkoutSession = await getCheckoutSession(session_id);
const metadata = validateAndExtractMetadata(checkoutSession);
return redirectToSuccess(metadata);
} catch (error) {
return handleError(error);
}
}
async function getCheckoutSession(sessionId: string) {
const session = await stripe.checkout.sessions.retrieve(sessionId, { expand: ["subscription"] });
if (!session) {
throw new HttpError({ statusCode: 404, message: "Checkout session not found" });
}
return session;
}
function validateAndExtractMetadata(session: Stripe.Checkout.Session): CheckoutSessionMetadata {
if (session.payment_status !== "paid") {
throw new HttpError({ statusCode: 402, message: "Payment required" });
}
if (!session.subscription) {
throw new HttpError({ statusCode: 400, message: "No subscription found in checkout session" });
}
const result = checkoutSessionMetadataSchema.safeParse(session.metadata);
if (!result.success) {
log.error(`Invalid checkout session metadata: ${safeStringify(result.error.issues)}`);
throw new HttpError({
statusCode: 400,
message: "Invalid checkout session metadata",
});
}
return result.data;
}
function redirectToSuccess(metadata: CheckoutSessionMetadata) {
const basePath = metadata.workflowId
? `${WEBAPP_URL}/workflows/${metadata.workflowId}`
: `${WEBAPP_URL}/workflows`;
return NextResponse.redirect(basePath);
}
function handleError(error: unknown) {
log.error("Error handling phone number subscription success:", safeStringify(error));
const url = new URL(`${WEBAPP_URL}/workflows`);
url.searchParams.set("error", "true");
if (error instanceof HttpError) {
url.searchParams.set("message", error.message);
} else {
url.searchParams.set("message", "An error occurred while processing your subscription");
}
return NextResponse.redirect(url.toString());
}
export default handler;
@@ -47,13 +47,13 @@ export const DEFAULT_PROMPT_VALUE = `## You are helping user set up a call with
## Task Steps
1. I am here to learn more about your issue and help schedule an appointment with our support team.
2. If {{email}} is not unknown then Use name {{name}} and email {{email}} for creating booking else Ask for user name and email and Confirm the name and email with user by reading it back to user.
2. If {{ATTENDEE_EMAIL}} is not unknown then Use name {{ATTENDEE_NAME}} and email {{ATTENDEE_EMAIL}} for creating booking else Ask for user name and email and Confirm the name and email with user by reading it back to user.
3. Ask user for \"When would you want to meet with one of our representatives\".
4. Call function check_availability to check for availability in the user provided time range.
4. Call function check_availability_{{eventTypeId}} to check for availability in the user provided time range.
- if availability exists, inform user about the availability range (do not repeat the detailed available slot) and ask user to choose from it. Make sure user chose a slot within detailed available slot.
- if availability does not exist, ask user to select another time range for the appointment, repeat this step 3.
5. Confirm the date and time selected by user: \"Just to confirm, you want to book the appointment at ...\".
6. Once confirmed, call function book_appointment to book the appointment.
6. Once confirmed, call function book_appointment_{{eventTypeId}} to book the appointment.
- if booking returned booking detail, it means booking is successful, proceed to step 7.
- if booking returned error message, let user know why the booking was not successful, and maybe start over with step 3.
7. Inform the user booking is successful, and ask if user have any questions. Answer them if there are any.
@@ -1,6 +1,5 @@
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
import prisma from "@calcom/prisma";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type {
PhoneNumberRepositoryInterface,
@@ -41,7 +40,7 @@ export class PrismaPhoneNumberRepositoryAdapter implements PhoneNumberRepository
async createPhoneNumber(params: {
phoneNumber: string;
provider?: string;
provider: string;
userId: number;
teamId?: number;
outboundAgentId?: string | null;
@@ -22,6 +22,10 @@ export class PrismaTransactionAdapter implements TransactionInterface {
provider: params.provider,
teamId: params.teamId,
outboundAgentId: params.outboundAgentId,
providerPhoneNumberId: params.providerPhoneNumberId,
subscriptionStatus: params.subscriptionStatus,
stripeCustomerId: params.stripeCustomerId,
stripeSubscriptionId: params.stripeSubscriptionId,
},
});
},
@@ -79,7 +79,7 @@ export interface AgentData {
name: string;
providerAgentId: string;
enabled: boolean;
userId: number;
userId: number | null;
teamId: number | null;
createdAt: Date;
updatedAt: Date;
@@ -1,4 +1,4 @@
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
/**
* Abstract interface for Phone Number repository operations
@@ -46,6 +46,10 @@ export interface PhoneNumberRepositoryInterface {
userId: number;
teamId?: number;
outboundAgentId?: string | null;
providerPhoneNumberId?: string;
subscriptionStatus?: import("@calcom/prisma/enums").PhoneNumberSubscriptionStatus;
stripeCustomerId?: string;
stripeSubscriptionId?: string;
}): Promise<PhoneNumberData>;
/**
@@ -34,5 +34,9 @@ export interface TransactionalPhoneNumberRepository {
provider: string;
teamId?: number;
outboundAgentId?: string | null;
providerPhoneNumberId?: string;
subscriptionStatus?: import("@calcom/prisma/enums").PhoneNumberSubscriptionStatus;
stripeCustomerId?: string;
stripeSubscriptionId?: string;
}): Promise<void>;
}
@@ -67,7 +67,7 @@ describe("RetellAIPhoneServiceProvider", () => {
deleteAgent: vi.fn().mockResolvedValue(undefined),
// Phone number operations
createPhoneNumber: vi.fn().mockResolvedValue({ phone_number: "+1234567890" }),
createPhoneNumber: vi.fn().mockResolvedValue({ phone_number: "+1234567890", provider: "retellAI" }),
importPhoneNumber: vi.fn().mockResolvedValue({ phone_number: "+1234567890" }),
deletePhoneNumber: vi.fn().mockResolvedValue(undefined),
getPhoneNumber: vi.fn().mockResolvedValue({ phone_number: "+1234567890" }),
@@ -379,9 +379,9 @@ describe("RetellAIPhoneServiceProvider", () => {
it("should create phone call", async () => {
const callData: AIPhoneServiceCallData = {
from_number: "+1234567890",
to_number: "+0987654321",
retell_llm_dynamic_variables: {
fromNumber: "+1234567890",
toNumber: "+0987654321",
dynamicVariables: {
name: "John Doe",
email: "[email protected]",
},
@@ -395,8 +395,8 @@ describe("RetellAIPhoneServiceProvider", () => {
it("should handle call data without dynamic variables", async () => {
const callData: AIPhoneServiceCallData = {
from_number: "+1234567890",
to_number: "+0987654321",
fromNumber: "+1234567890",
toNumber: "+0987654321",
};
await testProvider.createPhoneCall(callData);
@@ -411,7 +411,9 @@ describe("RetellAIPhoneServiceProvider", () => {
let createPhoneNumberMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
createPhoneNumberMock = vi.fn().mockResolvedValue({ phone_number: "+1234567890" });
createPhoneNumberMock = vi
.fn()
.mockResolvedValue({ phone_number: "+1234567890", provider: "retellAI" });
mockService = createMockRetellAIService({
createPhoneNumber: createPhoneNumberMock,
@@ -442,7 +444,7 @@ describe("RetellAIPhoneServiceProvider", () => {
inbound_agent_id: "inbound-agent-id",
outbound_agent_id: "outbound-agent-id",
});
expect(result).toEqual({ phone_number: "+1234567890" });
expect(result).toEqual({ phone_number: "+1234567890", provider: "retellAI" });
});
it("should handle optional parameters in phone number creation", async () => {
@@ -12,7 +12,6 @@ import type {
AIPhoneServiceUpdateModelParams,
AIPhoneServiceUpdateAgentParams,
AIPhoneServiceCreatePhoneNumberParams,
AIPhoneServiceImportPhoneNumberParams,
AIPhoneServiceUpdatePhoneNumberParams,
AIPhoneServiceAgentListItem,
AIPhoneServiceImportPhoneNumberParamsExtended,
@@ -23,7 +22,7 @@ import type { AgentRepositoryInterface } from "../interfaces/AgentRepositoryInte
import type { PhoneNumberRepositoryInterface } from "../interfaces/PhoneNumberRepositoryInterface";
import type { TransactionInterface } from "../interfaces/TransactionInterface";
import { RetellAIService } from "./RetellAIService";
import type { RetellAIRepository, RetellAgentWithDetails, RetellLLMGeneralTools } from "./types";
import type { RetellAIRepository } from "./types";
export class RetellAIPhoneServiceProvider
implements AIPhoneServiceProvider<AIPhoneServiceProviderType.RETELL_AI>
@@ -114,7 +113,7 @@ export class RetellAIPhoneServiceProvider
async createPhoneNumber(
data: AIPhoneServiceCreatePhoneNumberParams<AIPhoneServiceProviderType.RETELL_AI>
): Promise<AIPhoneServicePhoneNumber<AIPhoneServiceProviderType.RETELL_AI>> {
): Promise<AIPhoneServicePhoneNumber<AIPhoneServiceProviderType.RETELL_AI> & { provider: string }> {
const result = await this.service.createPhoneNumber({
area_code: data.area_code,
nickname: data.nickname,
@@ -237,6 +236,7 @@ export class RetellAIPhoneServiceProvider
async updateAgentConfiguration(params: {
id: string;
userId: number;
teamId?: number;
name?: string;
enabled?: boolean;
generalPrompt?: string | null;
@@ -256,6 +256,8 @@ export class RetellAIPhoneServiceProvider
phoneNumber?: string;
userId: number;
teamId?: number;
timeZone: string;
eventTypeId: number;
}): Promise<{
callId: string;
status: string;
@@ -263,4 +265,15 @@ export class RetellAIPhoneServiceProvider
}> {
return await this.service.createTestCall(params);
}
async updateToolsFromAgentId(
agentId: string,
data: { eventTypeId: number | null; timeZone: string; userId: number | null; teamId?: number | null }
): Promise<void> {
return await this.service.updateToolsFromAgentId(agentId, data);
}
async removeToolsForEventTypes(agentId: string, eventTypeIds: number[]): Promise<void> {
return await this.service.removeToolsForEventTypes(agentId, eventTypeIds);
}
}
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type { AgentRepositoryInterface } from "../interfaces/AgentRepositoryInterface";
@@ -7,6 +8,7 @@ import type { PhoneNumberRepositoryInterface } from "../interfaces/PhoneNumberRe
import type { TransactionInterface } from "../interfaces/TransactionInterface";
import { RetellAIService } from "./RetellAIService";
import { RetellAIError } from "./errors";
import { createMockDatabaseAgent } from "./services/__tests__/test-utils";
import type { RetellAIRepository } from "./types";
vi.mock("@calcom/lib/server/repository/PrismaPhoneNumberRepository", () => ({
@@ -55,16 +57,25 @@ vi.mock("@calcom/features/ee/payments/server/stripe", () => ({
},
}));
const mockGetAllCredits = vi.fn();
const mockHasAvailableCredits = vi.fn();
const mockCreditService = vi.fn().mockImplementation(() => ({
getAllCredits: mockGetAllCredits,
hasAvailableCredits: mockHasAvailableCredits,
}));
vi.mock("@calcom/features/ee/billing/credit-service", () => ({
CreditService: vi.fn().mockImplementation(() => ({
getAllCredits: vi.fn(),
})),
CreditService: mockCreditService,
}));
vi.mock("@calcom/lib/checkRateLimitAndThrowError", () => ({
checkRateLimitAndThrowError: vi.fn(),
}));
vi.mock("@calcom/ee/api-keys/lib/apiKeys", () => ({
generateUniqueAPIKey: vi.fn().mockReturnValue(["hashed-key", "api-key"]),
}));
// Mock Prisma client with transaction support
vi.mock("@calcom/prisma", () => ({
default: {
@@ -72,6 +83,9 @@ vi.mock("@calcom/prisma", () => ({
calAiPhoneNumber: {
create: vi.fn(),
},
apiKey: {
create: vi.fn().mockResolvedValue({ id: "api-key-123" }),
},
},
}));
@@ -353,7 +367,11 @@ describe("RetellAIService", () => {
describe("importPhoneNumber", () => {
it("should import phone number and create DB record using transaction", async () => {
const mockImportedNumber = { phone_number: "+1234567890" };
const mockAgent = createMockDatabaseAgent();
mockAgentRepository.findByIdWithUserAccess.mockResolvedValue(mockAgent);
mockRepository.importPhoneNumber.mockResolvedValue(mockImportedNumber);
mockRepository.updatePhoneNumber.mockResolvedValue(mockImportedNumber);
const result = await service.importPhoneNumber({
phone_number: "+1234567890",
@@ -361,6 +379,7 @@ describe("RetellAIService", () => {
sip_trunk_auth_username: "user",
sip_trunk_auth_password: "pass",
userId: 1,
agentId: "agent-123",
});
expect(result).toEqual(mockImportedNumber);
@@ -434,6 +453,9 @@ describe("RetellAIService", () => {
it("should handle transaction rollback when database creation fails with successful cleanup", async () => {
const mockImportedNumber = { phone_number: "+1234567890" };
const mockAgent = createMockDatabaseAgent();
mockAgentRepository.findByIdWithUserAccess.mockResolvedValue(mockAgent);
mockRepository.importPhoneNumber.mockResolvedValue(mockImportedNumber);
mockRepository.deletePhoneNumber.mockResolvedValue(undefined);
@@ -454,6 +476,7 @@ describe("RetellAIService", () => {
sip_trunk_auth_username: "user",
sip_trunk_auth_password: "pass",
userId: 1,
agentId: "agent-123",
})
).rejects.toThrow("Database connection failed");
@@ -466,6 +489,9 @@ describe("RetellAIService", () => {
it("should handle compensation failure and throw critical error", async () => {
const mockImportedNumber = { phone_number: "+1234567890" };
const mockAgent = createMockDatabaseAgent();
mockAgentRepository.findByIdWithUserAccess.mockResolvedValue(mockAgent);
mockRepository.importPhoneNumber.mockResolvedValue(mockImportedNumber);
// Mock compensation failure
@@ -488,6 +514,7 @@ describe("RetellAIService", () => {
sip_trunk_auth_username: "user",
sip_trunk_auth_password: "pass",
userId: 1,
agentId: "agent-123",
})
).rejects.toThrow(
"Failed to cleanup Retell phone number +1234567890 after transaction failure. Manual cleanup required."
@@ -505,9 +532,9 @@ describe("RetellAIService", () => {
mockRepository.createPhoneCall.mockResolvedValue(mockCall);
const result = await service.createPhoneCall({
from_number: "+1234567890",
to_number: "+0987654321",
retell_llm_dynamic_variables: {
fromNumber: "+1234567890",
toNumber: "+0987654321",
dynamicVariables: {
name: "John",
email: "[email protected]",
},
@@ -515,9 +542,9 @@ describe("RetellAIService", () => {
expect(result).toEqual(mockCall);
expect(mockRepository.createPhoneCall).toHaveBeenCalledWith({
from_number: "+1234567890",
to_number: "+0987654321",
retell_llm_dynamic_variables: {
fromNumber: "+1234567890",
toNumber: "+0987654321",
dynamicVariables: {
name: "John",
email: "[email protected]",
},
@@ -596,7 +623,10 @@ describe("RetellAIService", () => {
nickname: "Test Phone",
});
expect(result).toEqual(mockPhoneNumber);
expect(result).toEqual({
...mockPhoneNumber,
provider: "retellAI",
});
expect(mockRepository.createPhoneNumber).toHaveBeenCalledWith({
area_code: 415,
nickname: "Test Phone",
@@ -842,18 +872,14 @@ describe("RetellAIService", () => {
describe("createTestCall", () => {
it("should create test call successfully with sufficient credits", async () => {
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
const { checkRateLimitAndThrowError } = await import("@calcom/lib/checkRateLimitAndThrowError");
// Mock credit service to return sufficient credits
const mockGetAllCredits = vi.fn().mockResolvedValue({
totalRemainingMonthlyCredits: 10,
additionalCredits: 5,
});
const mockHasAvailableCredits = vi.fn().mockResolvedValue(true);
(CreditService as any).mockImplementation(() => ({
getAllCredits: mockGetAllCredits,
hasAvailableCredits: mockHasAvailableCredits,
}));
(checkRateLimitAndThrowError as any).mockResolvedValue(undefined);
// Mock rate limiting like the working example
vi.mocked(checkRateLimitAndThrowError).mockResolvedValueOnce(undefined as any);
mockAgentRepository.findByIdWithCallAccess.mockResolvedValue({
id: "1",
name: "Test Agent",
@@ -870,18 +896,51 @@ describe("RetellAIService", () => {
call_status: "initiated",
});
mockRepository.getAgent.mockResolvedValue({
agent_id: "agent-123",
agent_name: "Test Agent",
voice_id: "test-voice",
response_engine: {
type: "retell-llm",
llm_id: "llm-123",
},
language: "en",
responsiveness: 1,
interruption_sensitivity: 1,
});
mockRepository.getLLM.mockResolvedValue({
llm_id: "llm-123",
general_prompt: "Test prompt",
begin_message: "Hello",
general_tools: [],
});
mockRepository.updateLLM.mockResolvedValue({
llm_id: "llm-123",
general_prompt: "Test prompt",
begin_message: "Hello",
general_tools: [
{
type: "check_availability_cal",
name: "check_availability",
event_type_id: 123,
cal_api_key: "test-key",
timezone: "America/New_York",
},
],
});
const result = await service.createTestCall({
agentId: "1",
phoneNumber: "+14155555678",
userId: 1,
teamId: 2,
timeZone: "America/New_York",
eventTypeId: 123,
});
expect(mockGetAllCredits).toHaveBeenCalledWith({
userId: 1,
teamId: 2,
});
expect(checkRateLimitAndThrowError).toHaveBeenCalledWith({
expect(vi.mocked(checkRateLimitAndThrowError)).toHaveBeenCalledWith({
rateLimitingType: "core",
identifier: "test-call:1",
});
@@ -892,41 +951,13 @@ describe("RetellAIService", () => {
});
});
it("should throw error if insufficient credits", async () => {
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
// Mock credit service to return insufficient credits
const mockGetAllCredits = vi.fn().mockResolvedValue({
totalRemainingMonthlyCredits: 2,
additionalCredits: 1,
});
(CreditService as any).mockImplementation(() => ({
getAllCredits: mockGetAllCredits,
}));
await expect(
service.createTestCall({
agentId: "1",
phoneNumber: "+14155555678",
userId: 1,
})
).rejects.toThrow(
"Insufficient credits to make test call. Need 5 credits, have 3. Please purchase more credits."
);
expect(mockGetAllCredits).toHaveBeenCalledWith({
userId: 1,
teamId: undefined,
});
});
it("should handle null/undefined credits gracefully", async () => {
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
// Mock credit service to return null credits
const mockGetAllCredits = vi.fn().mockResolvedValue(null);
// Mock credit service to return false (no credits)
const mockHasAvailableCredits = vi.fn().mockResolvedValue(false);
(CreditService as any).mockImplementation(() => ({
getAllCredits: mockGetAllCredits,
hasAvailableCredits: mockHasAvailableCredits,
}));
await expect(
@@ -934,10 +965,10 @@ describe("RetellAIService", () => {
agentId: "1",
phoneNumber: "+14155555678",
userId: 1,
timeZone: "America/New_York",
eventTypeId: 123,
})
).rejects.toThrow(
"Insufficient credits to make test call. Need 5 credits, have 0. Please purchase more credits."
);
).rejects.toThrow("Insufficient credits to make test call. Please purchase more credits.");
});
it("should throw error if no phone number provided", async () => {
@@ -945,12 +976,9 @@ describe("RetellAIService", () => {
const { checkRateLimitAndThrowError } = await import("@calcom/lib/checkRateLimitAndThrowError");
// Mock sufficient credits to get past credit check
const mockGetAllCredits = vi.fn().mockResolvedValue({
totalRemainingMonthlyCredits: 10,
additionalCredits: 0,
});
const mockHasAvailableCredits = vi.fn().mockResolvedValue(true);
(CreditService as any).mockImplementation(() => ({
getAllCredits: mockGetAllCredits,
hasAvailableCredits: mockHasAvailableCredits,
}));
(checkRateLimitAndThrowError as any).mockResolvedValue(undefined);
@@ -959,6 +987,8 @@ describe("RetellAIService", () => {
service.createTestCall({
agentId: "1",
userId: 1,
timeZone: "America/New_York",
eventTypeId: 123,
})
).rejects.toThrow("Phone number is required for test call");
});
@@ -969,12 +999,9 @@ describe("RetellAIService", () => {
const { PrismaAgentRepository } = await import("@calcom/lib/server/repository/PrismaAgentRepository");
// Mock sufficient credits
const mockGetAllCredits = vi.fn().mockResolvedValue({
totalRemainingMonthlyCredits: 10,
additionalCredits: 0,
});
const mockHasAvailableCredits = vi.fn().mockResolvedValue(true);
(CreditService as any).mockImplementation(() => ({
getAllCredits: mockGetAllCredits,
hasAvailableCredits: mockHasAvailableCredits,
}));
(checkRateLimitAndThrowError as any).mockResolvedValue(undefined);
@@ -985,6 +1012,8 @@ describe("RetellAIService", () => {
agentId: "1",
phoneNumber: "+14155555678",
userId: 1,
timeZone: "America/New_York",
eventTypeId: 123,
})
).rejects.toThrow("Agent not found or you don't have permission to use it.");
});
@@ -994,12 +1023,9 @@ describe("RetellAIService", () => {
const { checkRateLimitAndThrowError } = await import("@calcom/lib/checkRateLimitAndThrowError");
// Mock sufficient credits
const mockGetAllCredits = vi.fn().mockResolvedValue({
totalRemainingMonthlyCredits: 10,
additionalCredits: 0,
});
const mockHasAvailableCredits = vi.fn().mockResolvedValue(true);
(CreditService as any).mockImplementation(() => ({
getAllCredits: mockGetAllCredits,
hasAvailableCredits: mockHasAvailableCredits,
}));
(checkRateLimitAndThrowError as any).mockResolvedValue(undefined);
@@ -1020,6 +1046,8 @@ describe("RetellAIService", () => {
agentId: "1",
phoneNumber: "+14155555678",
userId: 1,
timeZone: "America/New_York",
eventTypeId: 123,
})
).rejects.toThrow("Agent must have a phone number assigned to make calls.");
});
@@ -49,6 +49,9 @@ export class RetellAIService {
phoneNumberRepository,
transactionManager
);
// Inject RetellAIService reference into CallService
this.callService.setRetellAIService(this);
}
async setupAIConfiguration(config: AIConfigurationSetup): Promise<{ llmId: string; agentId: string }> {
@@ -74,7 +77,9 @@ export class RetellAIService {
return this.phoneNumberService.importPhoneNumber(data);
}
async createPhoneNumber(data: AIPhoneServiceCreatePhoneNumberParams): Promise<RetellPhoneNumber> {
async createPhoneNumber(
data: AIPhoneServiceCreatePhoneNumberParams
): Promise<RetellPhoneNumber & { provider: string }> {
return this.phoneNumberService.createPhoneNumber(data);
}
@@ -160,6 +165,7 @@ export class RetellAIService {
async updateAgentConfiguration(params: {
id: string;
userId: number;
teamId?: number;
name?: string;
generalPrompt?: string | null;
beginMessage?: string | null;
@@ -175,22 +181,42 @@ export class RetellAIService {
});
}
async updateToolsFromAgentId(
agentId: string,
data: { eventTypeId: number | null; timeZone: string; userId: number | null; teamId?: number | null }
): Promise<void> {
return this.agentService.updateToolsFromAgentId(agentId, data);
}
async removeToolsForEventTypes(agentId: string, eventTypeIds: number[]): Promise<void> {
return this.agentService.removeToolsForEventTypes(agentId, eventTypeIds);
}
async deleteAgent(params: { id: string; userId: number; teamId?: number }) {
return this.agentService.deleteAgent({
...params,
deleteAIConfiguration: (config) => this.deleteAIConfiguration(config),
deleteAIConfiguration: async (config) => {
await this.deleteAIConfiguration(config);
},
});
}
async createPhoneCall(data: {
from_number: string;
to_number: string;
retell_llm_dynamic_variables?: RetellDynamicVariables;
fromNumber: string;
toNumber: string;
dynamicVariables?: RetellDynamicVariables;
}): Promise<RetellCall> {
return this.callService.createPhoneCall(data);
}
async createTestCall(params: { agentId: string; phoneNumber?: string; userId: number; teamId?: number }) {
async createTestCall(params: {
agentId: string;
phoneNumber?: string;
userId: number;
teamId?: number;
timeZone: string;
eventTypeId: number;
}) {
return this.callService.createTestCall(params);
}
@@ -8,6 +8,7 @@ import type {
AIPhoneServiceTools,
AIPhoneServiceProviderType,
} from "../../interfaces/AIPhoneService.interface";
import type { AgentWithDetailsData } from "../interfaces/AgentRepositoryInterface";
import type {
RetellLLMGeneralTools,
UpdateLLMRequest,
@@ -16,7 +17,6 @@ import type {
UpdateAgentRequest,
RetellAgentWithDetails,
Language,
Agent,
RetellAgent,
RetellLLM,
} from "./types";
@@ -142,7 +142,7 @@ export class RetellAIServiceMapper {
/**
* Format agent for listing response
*/
static formatAgentForList(agent: Agent) {
static formatAgentForList(agent: AgentWithDetailsData) {
return {
id: agent.id,
name: agent.name,
@@ -162,7 +162,7 @@ export class RetellAIServiceMapper {
* Format agent details response
*/
static formatAgentDetails(
agent: Agent,
agent: AgentWithDetailsData,
retellAgent: RetellAgent,
llmDetails: RetellLLM
): RetellAgentWithDetails {
@@ -114,8 +114,8 @@ describe("RetellSDKClient", () => {
beforeAll(async () => {
// Reset modules and reimport with mocked env var
vi.resetModules();
const module = await import("./RetellSDKClient");
RetellSDKClient = module.RetellSDKClient;
const moduleImport = await import("./RetellSDKClient");
RetellSDKClient = moduleImport.RetellSDKClient;
});
it("should create client with default logger when no custom logger provided", () => {
@@ -373,9 +373,9 @@ describe("RetellSDKClient", () => {
describe("createPhoneCall", () => {
it("should create phone call", async () => {
const callData = {
from_number: "+14155551234",
to_number: "+14155555678",
retell_llm_dynamic_variables: {
fromNumber: "+14155551234",
toNumber: "+14155555678",
dynamicVariables: {
name: "John Doe",
email: "[email protected]",
} as RetellDynamicVariables,
@@ -386,15 +386,22 @@ describe("RetellSDKClient", () => {
const result = await client.createPhoneCall(callData);
expect(mockRetellInstance.call.createPhoneCall).toHaveBeenCalledWith(callData);
expect(mockRetellInstance.call.createPhoneCall).toHaveBeenCalledWith({
from_number: "+14155551234",
to_number: "+14155555678",
retell_llm_dynamic_variables: {
name: "John Doe",
email: "[email protected]",
},
});
expect(result).toEqual(mockResponse);
});
it("should handle undefined dynamic variables", async () => {
const callData = {
from_number: "+14155551234",
to_number: "+14155555678",
retell_llm_dynamic_variables: undefined,
fromNumber: "+14155551234",
toNumber: "+14155555678",
dynamicVariables: undefined,
};
const mockResponse = { call_id: "test-call-id" };
@@ -402,7 +409,11 @@ describe("RetellSDKClient", () => {
const result = await client.createPhoneCall(callData);
expect(mockRetellInstance.call.createPhoneCall).toHaveBeenCalledWith(callData);
expect(mockRetellInstance.call.createPhoneCall).toHaveBeenCalledWith({
from_number: "+14155551234",
to_number: "+14155555678",
retell_llm_dynamic_variables: undefined,
});
expect(result).toEqual(mockResponse);
});
});
@@ -11,7 +11,7 @@ import type {
UpdateAgentRequest,
RetellAgent,
CreatePhoneNumberParams,
RetellDynamicVariables,
CreatePhoneCallParams,
ImportPhoneNumberParams,
} from "./types";
@@ -221,16 +221,12 @@ export class RetellSDKClient implements RetellAIRepository {
}
}
async createPhoneCall(data: {
from_number: string;
to_number: string;
retell_llm_dynamic_variables?: RetellDynamicVariables;
}) {
async createPhoneCall(data: CreatePhoneCallParams) {
try {
const response = await this.client.call.createPhoneCall({
from_number: data.from_number,
to_number: data.to_number,
retell_llm_dynamic_variables: data.retell_llm_dynamic_variables,
from_number: data.fromNumber,
to_number: data.toNumber,
retell_llm_dynamic_variables: data.dynamicVariables,
});
return response;
} catch (error) {
@@ -1,3 +1,26 @@
import type {
RetellAIRepository,
CreateLLMRequest,
CreateAgentRequest,
UpdateLLMRequest,
AIConfigurationSetup,
AIConfigurationDeletion,
DeletionResult,
RetellLLM,
RetellAgent,
RetellCall,
CreatePhoneCallParams,
RetellPhoneNumber,
UpdatePhoneNumberParams,
CreatePhoneNumberParams,
ImportPhoneNumberParams,
UpdateAgentRequest,
RetellLLMGeneralTools,
RetellAgentWithDetails,
Language,
RetellDynamicVariables,
} from "./types";
export { RetellAIService } from "./RetellAIService";
export { AIConfigurationService } from "./services/AIConfigurationService";
@@ -38,7 +61,7 @@ export type {
RetellAgentWithDetails,
Language,
RetellDynamicVariables,
} from "./types";
};
export interface RetellAIPhoneServiceProviderTypeMap {
Configuration: AIConfigurationSetup;
@@ -52,7 +75,7 @@ export interface RetellAIPhoneServiceProviderTypeMap {
ImportPhoneNumberParams: ImportPhoneNumberParams;
UpdateAgentParams: UpdateAgentRequest;
Tools: RetellLLMGeneralTools;
CreatePhoneCallParams: CreatePhoneCallParams;
CreatePhoneCallParams: { fromNumber: string; toNumber: string; dynamicVariables?: RetellDynamicVariables };
AgentWithDetails: RetellAgentWithDetails;
}
@@ -66,7 +89,7 @@ import { RetellAIService } from '@calcom/features/calAIPhone/providers/retellAI'
const service = new RetellAIService(
repository,
agentRepository,
phoneNumberRepository,
phoneNumberRepository,
transactionManager
);
@@ -97,17 +120,17 @@ const service = new RetellAIService(
const result = await service.importPhoneNumber(phoneNumberData);
// 3. INDIVIDUAL SERVICES - Advanced usage for specific needs
import {
import {
AIConfigurationService,
PhoneNumberService,
BillingService
BillingService
} from '@calcom/features/calAIPhone/providers/retellAI';
// Use only what you need
const aiConfigService = new AIConfigurationService(repository);
const phoneService = new PhoneNumberService(
repository,
agentRepository,
agentRepository,
phoneNumberRepository,
transactionManager
);
@@ -127,7 +150,7 @@ const { modelId, agentId } = await provider.setupConfiguration({
// Benefits of the refactored architecture:
// ✅ Single Responsibility - Each service has one clear purpose
// ✅ Easier Testing - Test services in isolation
// ✅ Better Maintainability - Changes to billing don't affect phone operations
// ✅ Better Maintainability - Changes to billing don't affect phone operations
// ✅ Reusability - Compose services differently for different use cases
// ✅ Code Navigation - ~150 lines per service vs 849 lines in god class
// ✅ Backward Compatibility - All existing code continues to work
@@ -1,7 +1,10 @@
import { v4 as uuidv4 } from "uuid";
import { generateUniqueAPIKey as generateHashedApiKey } from "@calcom/ee/api-keys/lib/apiKeys";
import { timeZoneSchema } from "@calcom/lib/dayjs/timeZone.schema";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
import type {
AIPhoneServiceUpdateModelParams,
@@ -9,11 +12,11 @@ import type {
AIPhoneServiceAgent,
AIPhoneServiceModel,
AIPhoneServiceTools,
} from "../../interfaces/AIPhoneService.interface";
} from "../../../interfaces/AIPhoneService.interface";
import type { AgentRepositoryInterface } from "../../interfaces/AgentRepositoryInterface";
import { RetellAIServiceMapper } from "../RetellAIServiceMapper";
import type { RetellAIRepository } from "../types";
import { getLlmId, Language } from "../types";
import type { RetellAIRepository, Language } from "../types";
import { getLlmId } from "../types";
export class AgentService {
private logger = logger.getSubLogger({ prefix: ["AgentService"] });
@@ -23,6 +26,27 @@ export class AgentService {
private agentRepository: AgentRepositoryInterface
) {}
private async createApiKey({ userId, teamId }: { userId: number; teamId?: number }) {
const [hashedApiKey, apiKey] = generateHashedApiKey();
await prisma.apiKey.create({
data: {
id: uuidv4(),
userId,
teamId,
// And here we pass a null to expiresAt if never expires is true
expiresAt: null,
hashedKey: hashedApiKey,
note: `Cal AI Phone API Key for agent ${userId} ${teamId ? `for team ${teamId}` : ""}`,
},
});
const apiKeyPrefix = process.env.API_KEY_PREFIX ?? "cal_";
const prefixedApiKey = `${apiKeyPrefix}${apiKey}`;
return prefixedApiKey;
}
async getAgent(agentId: string): Promise<AIPhoneServiceAgent<AIPhoneServiceProviderType.RETELL_AI>> {
if (!agentId?.trim()) {
throw new HttpError({
@@ -45,6 +69,262 @@ export class AgentService {
}
}
async updateToolsFromAgentId(
agentId: string,
data: { eventTypeId: number | null; timeZone: string; userId: number | null; teamId?: number | null }
) {
if (!agentId?.trim()) {
throw new HttpError({
statusCode: 400,
message: "Agent ID is required and cannot be empty",
});
}
if (!data.eventTypeId || !data.userId) {
throw new HttpError({
statusCode: 400,
message: "Event type ID and user ID are required",
});
}
if (!timeZoneSchema.safeParse(data.timeZone).success) {
throw new HttpError({
statusCode: 400,
message: "Invalid time zone",
});
}
try {
const agent = await this.getAgent(agentId);
const llmId = getLlmId(agent);
if (!llmId) {
throw new HttpError({
statusCode: 404,
message: "Agent does not have an LLM configured.",
});
}
const llmDetails = await this.retellRepository.getLLM(llmId);
if (!llmDetails) {
throw new HttpError({ statusCode: 404, message: "LLM details not found." });
}
const existing = llmDetails?.general_tools ?? [];
const hasCheck = existing.some((t) => t.name === `check_availability_${data.eventTypeId}`);
const hasBook = existing.some((t) => t.name === `book_appointment_${data.eventTypeId}`);
// If both already exist and end_call also exists, nothing to do
const hasEndCallAlready = existing.some((t) => t.type === "end_call");
if (hasCheck && hasBook && hasEndCallAlready) {
return;
}
const reusableKey = existing.find(
(t): t is Extract<typeof t, { cal_api_key: string }> =>
"cal_api_key" in t && typeof t.cal_api_key === "string"
)?.cal_api_key;
const apiKey =
reusableKey ??
(await this.createApiKey({
userId: data.userId,
teamId: data.teamId || undefined,
}));
const newEventTools: NonNullable<AIPhoneServiceTools<AIPhoneServiceProviderType.RETELL_AI>> = [];
if (!hasCheck) {
newEventTools.push({
name: `check_availability_${data.eventTypeId}`,
type: "check_availability_cal",
event_type_id: data.eventTypeId,
cal_api_key: apiKey,
timezone: data.timeZone,
});
}
if (!hasBook) {
newEventTools.push({
name: `book_appointment_${data.eventTypeId}`,
type: "book_appointment_cal",
event_type_id: data.eventTypeId,
cal_api_key: apiKey,
timezone: data.timeZone,
});
}
if (!hasEndCallAlready) {
newEventTools.unshift({
type: "end_call",
name: "end_call",
description: "Hang up the call, triggered only after appointment successfully scheduled.",
});
}
const updatedGeneralTools = [...existing, ...newEventTools];
await this.retellRepository.updateLLM(llmId, { general_tools: updatedGeneralTools });
} catch (error) {
if (error instanceof HttpError) {
throw error;
}
this.logger.error("Failed to update agent general tools in external AI service", {
agentId,
error,
});
throw new HttpError({
statusCode: 500,
message: `Failed to update agent general tools ${agentId}: ${
error instanceof Error ? error.message : "Unknown error"
}`,
});
}
}
async removeToolsForEventTypes(agentId: string, eventTypeIds: number[]) {
if (!agentId?.trim()) {
throw new HttpError({
statusCode: 400,
message: "Agent ID is required and cannot be empty",
});
}
if (!eventTypeIds.length) {
return;
}
try {
const agent = await this.getAgent(agentId);
const llmId = getLlmId(agent);
if (!llmId) {
throw new HttpError({
statusCode: 404,
message: "Agent does not have an LLM configured.",
});
}
const llmDetails = await this.retellRepository.getLLM(llmId);
if (!llmDetails) {
throw new HttpError({ statusCode: 404, message: "LLM details not found." });
}
const existing = llmDetails?.general_tools ?? [];
const toolNamesToRemove = eventTypeIds.flatMap((eventTypeId) => [
`check_availability_${eventTypeId}`,
`book_appointment_${eventTypeId}`,
]);
const filteredTools = existing.filter((tool) => !toolNamesToRemove.includes(tool.name));
if (filteredTools.length !== existing.length) {
await this.retellRepository.updateLLM(llmId, { general_tools: filteredTools });
this.logger.info("Removed event-specific tools from agent", {
agentId,
llmId,
removedEventTypes: eventTypeIds,
toolsRemoved: existing.length - filteredTools.length,
});
}
} catch (error) {
if (error instanceof HttpError) {
throw error;
}
this.logger.error("Failed to remove event-specific tools from agent", {
agentId,
eventTypeIds,
error,
});
throw new HttpError({
statusCode: 500,
message: `Failed to remove tools for agent ${agentId}`,
});
}
}
async cleanupUnusedTools(agentId: string, activeEventTypeIds: number[] = []) {
if (!agentId?.trim()) {
throw new HttpError({
statusCode: 400,
message: "Agent ID is required and cannot be empty",
});
}
try {
const agent = await this.getAgent(agentId);
const llmId = getLlmId(agent);
if (!llmId) {
throw new HttpError({
statusCode: 404,
message: "Agent does not have an LLM configured.",
});
}
const llmDetails = await this.retellRepository.getLLM(llmId);
if (!llmDetails) {
throw new HttpError({ statusCode: 404, message: "LLM details not found." });
}
const existing = llmDetails?.general_tools ?? [];
const eventSpecificTools = existing.filter(
(tool) => tool.name.includes("check_availability_") || tool.name.includes("book_appointment_")
);
const toolsToRemove = eventSpecificTools.filter((tool) => {
// Extract event type ID from tool name
const eventTypeIdMatch = tool.name.match(/_(\d+)$/);
if (!eventTypeIdMatch) return false;
const eventTypeId = parseInt(eventTypeIdMatch[1]);
return !activeEventTypeIds.includes(eventTypeId);
});
if (toolsToRemove.length > 0) {
const toolNamesToRemove = toolsToRemove.map((tool) => tool.name);
const filteredTools = existing.filter((tool) => !toolNamesToRemove.includes(tool.name));
await this.retellRepository.updateLLM(llmId, { general_tools: filteredTools });
this.logger.info("Cleaned up unused event-specific tools", {
agentId,
llmId,
removedTools: toolsToRemove.length,
toolNames: toolNamesToRemove,
});
return {
removedCount: toolsToRemove.length,
removedTools: toolNamesToRemove,
};
}
return {
removedCount: 0,
removedTools: [],
};
} catch (error) {
if (error instanceof HttpError) {
throw error;
}
this.logger.error("Failed to cleanup unused tools for agent", {
agentId,
activeEventTypeIds,
error,
});
throw new HttpError({
statusCode: 500,
message: `Failed to cleanup tools for agent ${agentId}`,
});
}
}
async updateAgent(
agentId: string,
data: {
@@ -56,11 +336,11 @@ export class AgentService {
}
): Promise<AIPhoneServiceAgent<AIPhoneServiceProviderType.RETELL_AI>> {
if (!agentId?.trim()) {
throw new Error("Agent ID is required and cannot be empty");
throw new HttpError({ statusCode: 400, message: "Agent ID is required and cannot be empty" });
}
if (!data || Object.keys(data).length === 0) {
throw new Error("Update data is required");
throw new HttpError({ statusCode: 400, message: "Update data is required" });
}
try {
@@ -72,7 +352,10 @@ export class AgentService {
data,
error,
});
throw new Error(`Failed to update agent ${agentId}`);
throw new HttpError({
statusCode: 500,
message: `Failed to update agent ${agentId}`,
});
}
}
@@ -200,6 +483,7 @@ export class AgentService {
async updateAgentConfiguration({
id,
userId,
teamId,
name,
generalPrompt,
beginMessage,
@@ -209,6 +493,7 @@ export class AgentService {
}: {
id: string;
userId: number;
teamId?: number;
name?: string;
generalPrompt?: string | null;
beginMessage?: string | null;
@@ -222,6 +507,7 @@ export class AgentService {
const agent = await this.agentRepository.findByIdWithAdminAccess({
id,
userId,
teamId,
});
if (!agent) {
@@ -1,5 +1,6 @@
import { getStripeCustomerIdFromUserId } from "@calcom/app-store/stripepayment/lib/customer";
import { getPhoneNumberMonthlyPriceId } from "@calcom/app-store/stripepayment/lib/utils";
import { CHECKOUT_SESSION_TYPES } from "@calcom/features/ee/billing/constants";
import stripe from "@calcom/features/ee/payments/server/stripe";
import { WEBAPP_URL, IS_PRODUCTION } from "@calcom/lib/constants";
import { HttpError } from "@calcom/lib/http-error";
@@ -33,7 +34,7 @@ export class BillingService {
if (!phoneNumberPriceId) {
throw new HttpError({
statusCode: 500,
message: "Phone number price ID not configured. Please contact support.",
message: "Phone number price ID not configured",
});
}
@@ -55,7 +56,7 @@ export class BillingService {
quantity: 1,
},
],
success_url: `${WEBAPP_URL}/api/phone-numbers/subscription/success?session_id={CHECKOUT_SESSION_ID}`,
success_url: `${WEBAPP_URL}/api/calAIPhone/subscription/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${WEBAPP_URL}/workflows/${workflowId}`,
allow_promotion_codes: true,
customer_update: {
@@ -69,7 +70,7 @@ export class BillingService {
teamId: teamId?.toString() || "",
agentId: agentId || "",
workflowId: workflowId || "",
type: "phone_number_subscription",
type: CHECKOUT_SESSION_TYPES.PHONE_NUMBER_SUBSCRIPTION,
},
subscription_data: {
metadata: {
@@ -77,7 +78,7 @@ export class BillingService {
teamId: teamId?.toString() || "",
agentId: agentId || "",
workflowId: workflowId || "",
type: "phone_number_subscription",
type: CHECKOUT_SESSION_TYPES.PHONE_NUMBER_SUBSCRIPTION,
},
},
});
@@ -5,54 +5,66 @@ import logger from "@calcom/lib/logger";
import type {
AIPhoneServiceProviderType,
AIPhoneServiceCall,
} from "../../interfaces/AIPhoneService.interface";
} from "../../../interfaces/AIPhoneService.interface";
import type { AgentRepositoryInterface } from "../../interfaces/AgentRepositoryInterface";
import type { RetellAIRepository, RetellDynamicVariables } from "../types";
const MIN_CREDIT_REQUIRED_FOR_TEST_CALL = 5;
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: {
from_number: string;
to_number: string;
retell_llm_dynamic_variables?: RetellDynamicVariables;
fromNumber: string;
toNumber: string;
dynamicVariables?: RetellDynamicVariables;
}): Promise<AIPhoneServiceCall<AIPhoneServiceProviderType.RETELL_AI>> {
if (!data.from_number?.trim()) {
if (!data.fromNumber?.trim()) {
throw new HttpError({
statusCode: 400,
message: "From phone number is required and cannot be empty",
});
}
if (!data.to_number?.trim()) {
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({
from_number: data.from_number,
to_number: data.to_number,
retell_llm_dynamic_variables: data.retell_llm_dynamic_variables,
fromNumber,
toNumber,
dynamicVariables,
});
} catch (error) {
this.logger.error("Failed to create phone call in external AI service", {
fromNumber: data.from_number,
toNumber: data.to_number,
fromNumber: data.fromNumber,
toNumber: data.toNumber,
error,
});
throw new HttpError({
statusCode: 500,
message: `Failed to create phone call from ${data.from_number} to ${data.to_number}`,
message: `Failed to create phone call from ${data.fromNumber} to ${data.toNumber}`,
});
}
}
@@ -62,11 +74,15 @@ export class CallService {
phoneNumber,
userId,
teamId,
timeZone,
eventTypeId,
}: {
agentId: string;
phoneNumber?: string;
userId: number;
teamId?: number;
timeZone: string;
eventTypeId: number;
}) {
if (!agentId?.trim()) {
throw new HttpError({
@@ -111,9 +127,35 @@ export class CallService {
});
}
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({
from_number: agentPhoneNumber,
to_number: toNumber,
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: "[email protected]",
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 {
@@ -127,18 +169,15 @@ export class CallService {
try {
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
const creditService = new CreditService();
const credits = await creditService.getAllCredits({
userId,
teamId,
const hasCredits = await creditService.hasAvailableCredits({
userId: userId || undefined,
teamId: teamId || undefined,
});
const availableCredits =
(credits?.totalRemainingMonthlyCredits || 0) + (credits?.additionalCredits || 0);
if (availableCredits < MIN_CREDIT_REQUIRED_FOR_TEST_CALL) {
if (!hasCredits) {
throw new HttpError({
statusCode: 403,
message: `Insufficient credits to make test call. Need ${MIN_CREDIT_REQUIRED_FOR_TEST_CALL} credits, have ${availableCredits}. Please purchase more credits.`,
message: `Insufficient credits to make test call. Please purchase more credits.`,
});
}
} catch (error) {
@@ -2,10 +2,10 @@ import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import { AIPhoneServiceProviderType } from "../../../interfaces/AIPhoneService.interface";
import type {
AIPhoneServiceCreatePhoneNumberParams,
AIPhoneServiceImportPhoneNumberParamsExtended,
AIPhoneServiceProviderType,
AIPhoneServicePhoneNumber,
} from "../../../interfaces/AIPhoneService.interface";
import type { AgentRepositoryInterface } from "../../interfaces/AgentRepositoryInterface";
@@ -39,7 +39,7 @@ export class PhoneNumberService {
await this.validateTeamPermissions(userId, teamId);
const agent = await this.validateAgentPermissions(userId, agentId);
let transactionState = {
const transactionState = {
retellPhoneNumber: null as AIPhoneServicePhoneNumber<AIPhoneServiceProviderType.RETELL_AI> | null,
databaseRecordCreated: false,
agentAssigned: false,
@@ -81,9 +81,13 @@ export class PhoneNumberService {
async createPhoneNumber(
data: AIPhoneServiceCreatePhoneNumberParams
): Promise<AIPhoneServicePhoneNumber<AIPhoneServiceProviderType.RETELL_AI>> {
): Promise<AIPhoneServicePhoneNumber<AIPhoneServiceProviderType.RETELL_AI> & { provider: string }> {
try {
return await this.retellRepository.createPhoneNumber(data);
const phoneNumber = await this.retellRepository.createPhoneNumber(data);
return {
...phoneNumber,
provider: AIPhoneServiceProviderType.RETELL_AI,
};
} catch (error) {
this.logger.error("Failed to create phone number in external AI service", {
data,
@@ -305,7 +309,14 @@ export class PhoneNumberService {
}
}
private async validateAgentPermissions(userId: number, agentId?: string) {
private async validateAgentPermissions(userId: number, agentId?: string | null) {
if (!agentId) {
throw new HttpError({
statusCode: 400,
message: "Agent ID is required and cannot be empty",
});
}
let agent = null;
if (agentId) {
agent = await this.agentRepository.findByIdWithUserAccess({
@@ -358,7 +369,7 @@ export class PhoneNumberService {
agentAssigned: boolean;
},
error: unknown,
context: { userId: number; teamId?: number; agentId?: string }
context: { userId: number; teamId?: number; agentId?: string | null | undefined }
) {
if (transactionState.retellPhoneNumber?.phone_number) {
try {
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { HttpError } from "@calcom/lib/http-error";
import { CHECKOUT_SESSION_TYPES } from "@calcom/features/ee/billing/constants";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import { BillingService } from "../BillingService";
@@ -74,12 +74,12 @@ describe("BillingService", () => {
expect.objectContaining({
mode: "subscription",
success_url:
"https://app.cal.com/api/phone-numbers/subscription/success?session_id={CHECKOUT_SESSION_ID}",
"https://app.cal.com/api/calAIPhone/subscription/success?session_id={CHECKOUT_SESSION_ID}",
cancel_url: "https://app.cal.com/workflows/workflow-123",
metadata: expect.objectContaining({
userId: "1",
workflowId: "workflow-123",
type: "phone_number_subscription",
type: CHECKOUT_SESSION_TYPES.PHONE_NUMBER_SUBSCRIPTION,
}),
})
);
@@ -1,7 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import { HttpError } from "@calcom/lib/http-error";
import { CallService } from "../CallService";
import { setupBasicMocks, createMockCall, createMockDatabaseAgent, TestError } from "./test-utils";
@@ -17,6 +16,7 @@ vi.mock("@calcom/lib/checkRateLimitAndThrowError", () => ({
describe("CallService", () => {
let service: CallService;
let mocks: ReturnType<typeof setupBasicMocks>;
let mockRetellAIService: any;
beforeEach(async () => {
vi.clearAllMocks();
@@ -27,15 +27,17 @@ describe("CallService", () => {
const { checkRateLimitAndThrowError } = await import("@calcom/lib/checkRateLimitAndThrowError");
vi.mocked(CreditService).mockImplementation(() => ({
getAllCredits: vi.fn().mockResolvedValue({
totalRemainingMonthlyCredits: 100,
additionalCredits: 50,
}),
hasAvailableCredits: vi.fn().mockResolvedValue(true),
}));
vi.mocked(checkRateLimitAndThrowError).mockResolvedValue(undefined);
mockRetellAIService = {
updateToolsFromAgentId: vi.fn().mockResolvedValue(undefined),
};
service = new CallService(mocks.mockRetellRepository, mocks.mockAgentRepository);
service.setRetellAIService(mockRetellAIService);
});
afterEach(() => {
@@ -44,8 +46,8 @@ describe("CallService", () => {
describe("createPhoneCall", () => {
const validCallData = {
from_number: "+1234567890",
to_number: "+0987654321",
fromNumber: "+1234567890",
toNumber: "+0987654321",
};
it("should successfully create phone call", async () => {
@@ -55,7 +57,11 @@ describe("CallService", () => {
const result = await service.createPhoneCall(validCallData);
expect(result).toEqual(mockCall);
expect(mocks.mockRetellRepository.createPhoneCall).toHaveBeenCalledWith(validCallData);
expect(mocks.mockRetellRepository.createPhoneCall).toHaveBeenCalledWith({
fromNumber: "+1234567890",
toNumber: "+0987654321",
dynamicVariables: undefined,
});
});
it("should create phone call with dynamic variables", async () => {
@@ -64,7 +70,7 @@ describe("CallService", () => {
const callDataWithVariables = {
...validCallData,
retell_llm_dynamic_variables: {
dynamicVariables: {
name: "John Doe",
company: "Acme Corp",
},
@@ -72,7 +78,14 @@ describe("CallService", () => {
await service.createPhoneCall(callDataWithVariables);
expect(mocks.mockRetellRepository.createPhoneCall).toHaveBeenCalledWith(callDataWithVariables);
expect(mocks.mockRetellRepository.createPhoneCall).toHaveBeenCalledWith({
fromNumber: "+1234567890",
toNumber: "+0987654321",
dynamicVariables: {
name: "John Doe",
company: "Acme Corp",
},
});
});
it("should handle Retell API errors", async () => {
@@ -89,6 +102,8 @@ describe("CallService", () => {
agentId: "agent-123",
phoneNumber: "+0987654321",
userId: 1,
timeZone: "America/New_York",
eventTypeId: 123,
};
const mockAgentWithPhoneNumber = createMockDatabaseAgent({
@@ -114,8 +129,12 @@ describe("CallService", () => {
});
expect(mocks.mockRetellRepository.createPhoneCall).toHaveBeenCalledWith({
from_number: "+1234567890",
to_number: "+0987654321",
fromNumber: "+1234567890",
toNumber: "+0987654321",
dynamicVariables: expect.objectContaining({
EVENT_NAME: "Test Call with Agent",
TIMEZONE: "America/New_York",
}),
});
});
@@ -135,25 +154,13 @@ describe("CallService", () => {
});
});
it("should throw error if insufficient credits", async () => {
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
vi.mocked(CreditService).mockImplementation(() => ({
getAllCredits: vi.fn().mockResolvedValue({
totalRemainingMonthlyCredits: 2,
additionalCredits: 1,
}),
}));
await expect(service.createTestCall(validTestCallData)).rejects.toThrow(
"Insufficient credits to make test call. Need 5 credits, have 3"
);
});
it("should throw error if no phone number provided", async () => {
await expect(
service.createTestCall({
agentId: "agent-123",
userId: 1,
timeZone: "America/New_York",
eventTypeId: 123,
})
).rejects.toThrow("Phone number is required for test call");
});
@@ -238,14 +245,11 @@ describe("CallService", () => {
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
vi.mocked(CreditService).mockImplementation(() => ({
getAllCredits: vi.fn().mockResolvedValue({
totalRemainingMonthlyCredits: 2,
additionalCredits: 1,
}),
hasAvailableCredits: vi.fn().mockResolvedValue(false),
}));
await expect(service.createTestCall(validTestCallData)).rejects.toThrow(
"Insufficient credits to make test call. Need 5 credits, have 3"
"Insufficient credits to make test call. Please purchase more credits."
);
});
@@ -255,14 +259,11 @@ describe("CallService", () => {
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
vi.mocked(CreditService).mockImplementation(() => ({
getAllCredits: vi.fn().mockResolvedValue({
totalRemainingMonthlyCredits: null,
additionalCredits: null,
}),
hasAvailableCredits: vi.fn().mockResolvedValue(false),
}));
await expect(service.createTestCall(validTestCallData)).rejects.toThrow(
"Insufficient credits to make test call. Need 5 credits, have 0"
"Insufficient credits to make test call. Please purchase more credits."
);
});
});
@@ -40,11 +40,16 @@ describe("PhoneNumberService", () => {
sip_trunk_auth_password: "pass",
userId: 1,
nickname: "Test Number",
agentId: "agent-123",
};
it("should successfully import phone number without agent", async () => {
it("should successfully import phone number with agent", async () => {
const mockPhoneNumber = createMockPhoneNumber();
const mockAgent = createMockDatabaseAgent();
mocks.mockRetellRepository.importPhoneNumber.mockResolvedValue(mockPhoneNumber);
mocks.mockAgentRepository.findByIdWithUserAccess.mockResolvedValue(mockAgent);
mocks.mockRetellRepository.updatePhoneNumber.mockResolvedValue(mockPhoneNumber);
const result = await service.importPhoneNumber(validImportData);
@@ -56,26 +61,10 @@ describe("PhoneNumberService", () => {
sip_trunk_auth_password: "pass",
nickname: "Test Number",
});
expect(mocks.mockTransactionManager.executeInTransaction).toHaveBeenCalled();
});
it("should successfully import phone number with agent", async () => {
const mockPhoneNumber = createMockPhoneNumber();
const mockAgent = createMockDatabaseAgent();
mocks.mockRetellRepository.importPhoneNumber.mockResolvedValue(mockPhoneNumber);
mocks.mockAgentRepository.findByIdWithUserAccess.mockResolvedValue(mockAgent);
mocks.mockRetellRepository.updatePhoneNumber.mockResolvedValue(mockPhoneNumber);
const result = await service.importPhoneNumber({
...validImportData,
agentId: "agent-123",
});
expect(result).toEqual(mockPhoneNumber);
expect(mocks.mockRetellRepository.updatePhoneNumber).toHaveBeenCalledWith("+1234567890", {
outbound_agent_id: mockAgent.providerAgentId,
});
expect(mocks.mockTransactionManager.executeInTransaction).toHaveBeenCalled();
});
it("should validate team permissions when teamId provided", async () => {
@@ -112,6 +101,9 @@ describe("PhoneNumberService", () => {
it("should handle transaction rollback with successful cleanup", async () => {
const mockPhoneNumber = createMockPhoneNumber();
const mockAgent = createMockDatabaseAgent();
mocks.mockAgentRepository.findByIdWithUserAccess.mockResolvedValue(mockAgent);
mocks.mockRetellRepository.importPhoneNumber.mockResolvedValue(mockPhoneNumber);
mocks.mockRetellRepository.deletePhoneNumber.mockResolvedValue(undefined);
@@ -133,6 +125,9 @@ describe("PhoneNumberService", () => {
it("should handle compensation failure and throw critical error", async () => {
const mockPhoneNumber = createMockPhoneNumber();
const mockAgent = createMockDatabaseAgent();
mocks.mockAgentRepository.findByIdWithUserAccess.mockResolvedValue(mockAgent);
mocks.mockRetellRepository.importPhoneNumber.mockResolvedValue(mockPhoneNumber);
// Mock both database failure and cleanup failure
@@ -81,7 +81,11 @@ export type Language =
// Request/response types
export type CreateLLMRequest = Retell.LlmCreateParams;
export type CreatePhoneNumberParams = Retell.PhoneNumberCreateParams;
export type CreatePhoneCallParams = Retell.CallCreatePhoneCallParams;
export type CreatePhoneCallParams = {
fromNumber: string;
toNumber: string;
dynamicVariables?: RetellDynamicVariables;
};
export type UpdatePhoneNumberParams = Retell.PhoneNumberUpdateParams;
export type ImportPhoneNumberParams = Retell.PhoneNumberImportParams;
export type RetellLLMGeneralTools = Retell.LlmCreateParams["general_tools"];
@@ -97,9 +101,14 @@ export type RetellAgentWithDetails = {
name: string;
providerAgentId: string;
enabled: boolean;
userId: number;
userId: number | null;
teamId: number | null;
outboundPhoneNumbers: Agent["outboundPhoneNumbers"];
outboundPhoneNumbers: Array<{
id: number;
phoneNumber: string;
subscriptionStatus: string | null;
provider: string | null;
}>;
retellData: {
agentId: RetellAgent["agent_id"];
agentName: RetellAgent["agent_name"];
@@ -1,11 +1,23 @@
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
import stripe from "@calcom/features/ee/payments/server/stripe";
import { PrismaAgentRepository } from "@calcom/lib/server/repository/PrismaAgentRepository";
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import { prisma } from "@calcom/prisma";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import { CHECKOUT_SESSION_TYPES } from "../../constants";
import type { SWHMap } from "./__handler";
import { HttpCode } from "./__handler";
const handler = async (data: SWHMap["checkout.session.completed"]["data"]) => {
const session = data.object;
if (session.metadata?.type === CHECKOUT_SESSION_TYPES.PHONE_NUMBER_SUBSCRIPTION) {
return await handleCalAIPhoneNumberSubscription(session);
}
// Handle credit purchases (existing logic)
if (!session.amount_total) {
throw new HttpCode(400, "Missing required payment details");
}
@@ -64,4 +76,112 @@ async function saveToCreditBalance({
});
}
}
async function handleCalAIPhoneNumberSubscription(
session: SWHMap["checkout.session.completed"]["data"]["object"]
) {
const userId = session.metadata?.userId ? parseInt(session.metadata.userId, 10) : null;
const teamId = session.metadata?.teamId ? parseInt(session.metadata.teamId, 10) : null;
const agentId = session.metadata?.agentId || null;
if (!userId || !session.subscription) {
console.error("Missing required data for phone number subscription", {
userId,
hasSubscription: !!session.subscription,
});
throw new HttpCode(400, "Missing required data for phone number subscription");
}
if (!agentId || agentId?.trim() === "") {
console.error("Missing agentId for phone number subscription", {
userId,
teamId,
});
throw new HttpCode(400, "Missing agentId for phone number subscription");
}
const agent = await PrismaAgentRepository.findByIdWithUserAccess({
agentId,
userId,
teamId: teamId ?? undefined,
});
if (!agent) {
console.error("Agent not found or user does not have access", { agentId, userId });
throw new HttpCode(404, "Agent not found or user does not have access to it");
}
const aiService = createDefaultAIPhoneServiceProvider();
const calAIPhoneNumber = await aiService.createPhoneNumber({
nickname: `userId:${userId}${teamId ? `-teamId:${teamId}` : ""}-${Date.now()}`,
});
if (!calAIPhoneNumber?.phone_number) {
console.error("Failed to create phone number - invalid response from Retell");
throw new HttpCode(500, "Failed to create phone number - invalid response");
}
const subscriptionId =
typeof session.subscription === "string" ? session.subscription : session.subscription?.id;
if (!subscriptionId) {
console.error("Invalid subscription data", { subscription: session.subscription });
throw new HttpCode(400, "Invalid subscription data");
}
const newNumber = await PrismaPhoneNumberRepository.createPhoneNumber({
userId,
teamId: teamId ?? undefined,
phoneNumber: calAIPhoneNumber.phone_number,
provider: calAIPhoneNumber.provider,
stripeCustomerId: session.customer as string,
stripeSubscriptionId: subscriptionId,
subscriptionStatus: PhoneNumberSubscriptionStatus.ACTIVE,
providerPhoneNumberId: calAIPhoneNumber.phone_number,
});
try {
console.log("Attempting to link agent to phone number:", { agentId, phoneNumberId: newNumber.id });
const agent = await PrismaAgentRepository.findByIdWithUserAccess({
agentId,
userId,
});
if (!agent) {
console.error("Agent not found or user does not have access", { agentId, userId });
throw new HttpCode(404, "Agent not found or user does not have access to it");
}
console.log("Found agent:", { agentId: agent.id, providerAgentId: agent.providerAgentId });
// Assign agent to the new number via Retell API
await aiService.updatePhoneNumber(calAIPhoneNumber.phone_number, {
outbound_agent_id: agent.providerAgentId,
});
// Link the new number to the agent in our database
await prisma.calAiPhoneNumber.update({
where: { id: newNumber.id },
data: {
outboundAgent: {
connect: { id: agentId },
},
},
});
console.log("Phone number successfully linked to agent");
} catch (error) {
console.error("Agent linking error details:", {
error,
agentId,
phoneNumber: calAIPhoneNumber.phone_number,
userId,
});
}
return { success: true, phoneNumber: newNumber.phoneNumber };
}
export default handler;
@@ -1,4 +1,8 @@
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
import type { LazyModule, SWHMap } from "./__handler";
import { HttpCode } from "./__handler";
type Data = SWHMap["customer.subscription.deleted"]["data"];
@@ -8,6 +12,16 @@ const STRIPE_TEAM_PRODUCT_ID = process.env.STRIPE_TEAM_PRODUCT_ID || "";
const stripeWebhookProductHandler = (handlers: Handlers) => async (data: Data) => {
const subscription = data.object;
const phoneNumber = await PrismaPhoneNumberRepository.findByStripeSubscriptionId({
stripeSubscriptionId: subscription.id,
});
if (phoneNumber) {
return await handleCalAIPhoneNumberSubscriptionDeleted(subscription, phoneNumber);
}
// Fall back to product-based handling for other subscriptions
let productId: string | null = null;
// @ts-expect-error - support legacy just in case.
if (subscription.plan) {
@@ -46,6 +60,33 @@ const stripeWebhookProductHandler = (handlers: Handlers) => async (data: Data) =
return await handler(data);
};
async function handleCalAIPhoneNumberSubscriptionDeleted(
subscription: Data["object"],
phoneNumber: NonNullable<Awaited<ReturnType<typeof PrismaPhoneNumberRepository.findByStripeSubscriptionId>>>
) {
if (!subscription.id) {
throw new HttpCode(400, "Subscription ID not found");
}
if (!phoneNumber.userId) {
throw new HttpCode(400, "Phone number does not belong to a user");
}
try {
const aiService = createDefaultAIPhoneServiceProvider();
await aiService.cancelPhoneNumberSubscription({
phoneNumberId: phoneNumber.id,
userId: phoneNumber.userId,
teamId: phoneNumber.teamId ?? undefined,
});
return { success: true, subscriptionId: subscription.id };
} catch (error) {
console.error("Failed to update phone number subscription:", error);
throw new HttpCode(500, "Failed to update phone number subscription");
}
}
export default stripeWebhookProductHandler({
[STRIPE_TEAM_PRODUCT_ID]: () => import("./_customer.subscription.deleted.team-plan"),
});
@@ -0,0 +1,60 @@
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
import { prisma } from "@calcom/prisma";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/client";
import type { SWHMap } from "./__handler";
import { HttpCode } from "./__handler";
type Data = SWHMap["customer.subscription.updated"]["data"];
const handler = async (data: Data) => {
const subscription = data.object;
if (!subscription.id) {
throw new HttpCode(400, "Subscription ID not found");
}
const phoneNumber = await PrismaPhoneNumberRepository.findByStripeSubscriptionId({
stripeSubscriptionId: subscription.id,
});
if (!phoneNumber) {
throw new HttpCode(202, "Phone number not found");
}
return await handleCalAIPhoneNumberSubscriptionUpdate(subscription, phoneNumber);
};
type Subscription = Data["object"];
async function handleCalAIPhoneNumberSubscriptionUpdate(
subscription: Subscription,
phoneNumber: { id: number; phoneNumber: string }
) {
// Map Stripe subscription status to our enum
const statusMap: Record<string, PhoneNumberSubscriptionStatus> = {
active: PhoneNumberSubscriptionStatus.ACTIVE,
past_due: PhoneNumberSubscriptionStatus.PAST_DUE,
canceled: PhoneNumberSubscriptionStatus.CANCELLED,
incomplete: PhoneNumberSubscriptionStatus.INCOMPLETE,
incomplete_expired: PhoneNumberSubscriptionStatus.INCOMPLETE_EXPIRED,
trialing: PhoneNumberSubscriptionStatus.TRIALING,
unpaid: PhoneNumberSubscriptionStatus.UNPAID,
paused: PhoneNumberSubscriptionStatus.CANCELLED,
};
const subscriptionStatus = statusMap[subscription.status] || PhoneNumberSubscriptionStatus.UNPAID;
await prisma.calAiPhoneNumber.update({
where: {
id: phoneNumber.id,
},
data: {
subscriptionStatus,
},
});
return { success: true, subscriptionId: subscription.id, status: subscriptionStatus };
}
export default handler;
@@ -7,6 +7,7 @@ import { stripeWebhookHandler } from "./__handler";
const handlers = {
"payment_intent.succeeded": () => import("./_payment_intent.succeeded"),
"customer.subscription.deleted": () => import("./_customer.subscription.deleted"),
"customer.subscription.updated": () => import("./_customer.subscription.updated"),
"invoice.paid": () => import("./_invoice.paid"),
"checkout.session.completed": () => import("./_checkout.session.completed"),
};
@@ -0,0 +1,9 @@
/**
* Stripe checkout session metadata types
* Used to identify the type of subscription/purchase in webhook handlers
*/
export const CHECKOUT_SESSION_TYPES = {
PHONE_NUMBER_SUBSCRIPTION: "phone_number_subscription",
} as const;
export type CheckoutSessionType = (typeof CHECKOUT_SESSION_TYPES)[keyof typeof CHECKOUT_SESSION_TYPES];
@@ -111,6 +111,8 @@ describe("CreditService", () => {
};
(Stripe as any).mockImplementation(() => stripeMock);
creditService = new CreditService();
vi.mocked(CreditsRepository.findCreditExpenseLogByExternalRef).mockResolvedValue(null);
});
describe("Team credits", () => {
@@ -421,6 +423,7 @@ describe("CreditService", () => {
});
it("should calculate credits based on active members and price", async () => {
vi.stubEnv("STRIPE_TEAM_MONTHLY_PRICE_ID", "price_team_monthly");
const mockTeamRepo = {
findTeamWithMembers: vi.fn().mockResolvedValue({
id: 1,
@@ -446,6 +449,35 @@ describe("CreditService", () => {
const result = await creditService.getMonthlyCredits(1);
expect(result).toBe(1500); // (3 members * 1000 price) / 2
});
it("should calculate credits with 20% multiplier for organizations", async () => {
vi.stubEnv("STRIPE_ORG_MONTHLY_PRICE_ID", "price_org_monthly");
const mockTeamRepo = {
findTeamWithMembers: vi.fn().mockResolvedValue({
id: 1,
isOrganization: true,
members: [{ accepted: true }, { accepted: true }],
}),
};
vi.mocked(TeamRepository).mockImplementation(() => mockTeamRepo as any);
const mockTeamBillingService = {
getSubscriptionStatus: vi.fn().mockResolvedValue("active"),
};
vi.spyOn(InternalTeamBilling.prototype, "getSubscriptionStatus").mockImplementation(
mockTeamBillingService.getSubscriptionStatus
);
const mockStripeBillingService = {
getPrice: vi.fn().mockResolvedValue({ unit_amount: 3700 }),
};
vi.spyOn(StripeBillingService.prototype, "getPrice").mockImplementation(
mockStripeBillingService.getPrice
);
const result = await creditService.getMonthlyCredits(1);
expect(result).toBe(1480); // (2 members * 3700 price) * 0.2
});
});
describe("getAllCreditsForTeam", () => {
@@ -684,4 +716,134 @@ describe("CreditService", () => {
expect(CreditsRepository.findCreditBalance).toHaveBeenCalledWith({ teamId: 2 }, MOCK_TX);
});
});
describe("Idempotency", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("should detect duplicate charges by externalRef", async () => {
vi.mocked(CreditsRepository.findCreditExpenseLogByExternalRef).mockResolvedValue({
id: "existing-log-id",
credits: 10,
creditType: CreditType.ADDITIONAL,
date: new Date(),
bookingUid: "booking-123",
});
const result = await creditService.chargeCredits({
userId: 1,
credits: 10,
externalRef: "retell:duplicate-call-123",
});
expect(result).toEqual({
bookingUid: "booking-123",
duplicate: true,
teamId: undefined,
userId: 1,
});
expect(CreditsRepository.findCreditExpenseLogByExternalRef).toHaveBeenCalledWith(
"retell:duplicate-call-123"
);
expect(CreditsRepository.createCreditExpenseLog).not.toHaveBeenCalled();
expect(CreditsRepository.updateCreditBalance).not.toHaveBeenCalled();
});
it("should create expense log with externalRef when not duplicate", async () => {
vi.mocked(CreditsRepository.findCreditExpenseLogByExternalRef).mockResolvedValue(null);
vi.mocked(CreditsRepository.findCreditBalanceWithTeamOrUser).mockResolvedValue({
id: "1",
additionalCredits: 100,
limitReachedAt: null,
warningSentAt: null,
user: {
id: 1,
name: "Test User",
email: "[email protected]",
locale: "en",
},
team: null,
});
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 100,
limitReachedAt: null,
warningSentAt: null,
});
vi.spyOn(CreditService.prototype, "_getUserOrTeamToCharge").mockResolvedValue({
userId: 1,
remainingCredits: 90,
creditType: CreditType.ADDITIONAL,
});
await creditService.chargeCredits({
userId: 1,
credits: 10,
bookingUid: "booking-456",
externalRef: "retell:new-call-456",
});
expect(CreditsRepository.findCreditExpenseLogByExternalRef).toHaveBeenCalledWith("retell:new-call-456");
expect(CreditsRepository.createCreditExpenseLog).toHaveBeenCalledWith(
expect.objectContaining({
credits: 10,
creditType: CreditType.ADDITIONAL,
bookingUid: "booking-456",
externalRef: "retell:new-call-456",
}),
MOCK_TX
);
});
it("should work normally without externalRef", async () => {
vi.mocked(CreditsRepository.findCreditBalanceWithTeamOrUser).mockResolvedValue({
id: "1",
additionalCredits: 100,
limitReachedAt: null,
warningSentAt: null,
team: {
id: 1,
name: "Test Team",
members: [],
},
user: null,
});
vi.mocked(CreditsRepository.findCreditBalance).mockResolvedValue({
id: "1",
additionalCredits: 100,
limitReachedAt: null,
warningSentAt: null,
});
vi.spyOn(CreditService.prototype, "_getAllCreditsForTeam").mockResolvedValue({
totalMonthlyCredits: 500,
totalRemainingMonthlyCredits: 100,
additionalCredits: 100,
});
await creditService.chargeCredits({
teamId: 1,
credits: 10,
bookingUid: "booking-789",
});
expect(CreditsRepository.findCreditExpenseLogByExternalRef).not.toHaveBeenCalled();
expect(CreditsRepository.createCreditExpenseLog).toHaveBeenCalledWith(
expect.objectContaining({
credits: 10,
bookingUid: "booking-789",
externalRef: undefined,
}),
MOCK_TX
);
});
});
});
+45 -6
View File
@@ -15,7 +15,7 @@ import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { TeamRepository } from "@calcom/lib/server/repository/team";
import prisma, { type PrismaTransaction } from "@calcom/prisma";
import { CreditType } from "@calcom/prisma/enums";
import { CreditType, CreditUsageType } from "@calcom/prisma/enums";
const log = logger.getSubLogger({ prefix: ["[CreditService]"] });
@@ -59,6 +59,9 @@ export class CreditService {
bookingUid,
smsSid,
smsSegments,
callDuration,
creditFor,
externalRef,
}: {
userId?: number;
teamId?: number;
@@ -66,7 +69,22 @@ export class CreditService {
bookingUid?: string;
smsSid?: string;
smsSegments?: number;
callDuration?: number;
creditFor?: CreditUsageType;
externalRef?: string;
}) {
if (externalRef) {
const existingLog = await CreditsRepository.findCreditExpenseLogByExternalRef(externalRef);
if (existingLog) {
log.warn("Credit expense log already exists", { externalRef, existingLog });
return {
bookingUid: existingLog.bookingUid,
duplicate: true,
userId,
teamId,
};
}
}
return await prisma
.$transaction(async (tx) => {
let teamIdToCharge = credits === 0 && teamId ? teamId : undefined;
@@ -99,7 +117,10 @@ export class CreditService {
credits,
creditType,
smsSegments,
callDuration,
creditFor,
tx,
externalRef,
});
let lowCreditBalanceResult = null;
@@ -163,7 +184,7 @@ export class CreditService {
);
return true;
}
// limtReachedAt is set and still no available credits
// limitReachedAt is set and still no available credits
return false;
}
@@ -302,9 +323,12 @@ export class CreditService {
credits: number | null;
creditType: CreditType;
smsSegments?: number;
callDuration?: number;
creditFor?: CreditUsageType;
tx: PrismaTransaction;
externalRef?: string;
}) {
const { credits, creditType, bookingUid, smsSid, teamId, userId, smsSegments, tx } = props;
const { credits, creditType, bookingUid, smsSid, teamId, userId, smsSegments, callDuration, creditFor, tx } = props;
let creditBalance: { id: string; additionalCredits: number } | null | undefined =
await CreditsRepository.findCreditBalance({ teamId, userId }, tx);
@@ -341,10 +365,13 @@ export class CreditService {
creditBalanceId: creditBalance.id,
credits,
creditType,
creditFor,
date: new Date(),
bookingUid,
smsSid,
smsSegments,
callDuration,
externalRef: props.externalRef,
},
tx
);
@@ -550,9 +577,21 @@ export class CreditService {
const billingService = new StripeBillingService();
const teamMonthlyPrice = await billingService.getPrice(process.env.STRIPE_TEAM_MONTHLY_PRICE_ID || "");
const pricePerSeat = teamMonthlyPrice.unit_amount ?? 0;
totalMonthlyCredits = (activeMembers * pricePerSeat) / 2;
const priceId = team.isOrganization
? process.env.STRIPE_ORG_MONTHLY_PRICE_ID
: process.env.STRIPE_TEAM_MONTHLY_PRICE_ID;
if (!priceId) {
log.warn("Monthly price ID not configured", { teamId, isOrganization: team.isOrganization });
return 0;
}
const monthlyPrice = await billingService.getPrice(priceId || "");
const pricePerSeat = monthlyPrice.unit_amount ?? 0;
// Teams get 50% of the price as credits, organizations get 20%
const creditMultiplier = team.isOrganization ? 0.2 : 0.5;
totalMonthlyCredits = activeMembers * pricePerSeat * creditMultiplier;
return totalMonthlyCredits;
}
File diff suppressed because it is too large. Load diff
@@ -4,10 +4,10 @@ import { CreateButtonWithTeamsList } from "@calcom/features/ee/teams/components/
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import { trpc } from "@calcom/trpc/react";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { EmptyScreen as ClassicEmptyScreen } from "@calcom/ui/components/empty-screen";
import { Icon } from "@calcom/ui/components/icon";
import type { IconName } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
type WorkflowExampleType = {
Icon: IconName;
@@ -48,7 +48,7 @@ export default function EmptyScreen(props: { isFilteredView: boolean }) {
}
if (err.data?.code === "UNAUTHORIZED") {
const message = `${err.data.code}: You are not authorized to create this workflow`;
const message = `${err.data.code}: ${t("unauthorized_create_workflow")}`;
showToast(message, "error");
}
},
@@ -0,0 +1,92 @@
import { useState } from "react";
import type { UseFormReturn } from "react-hook-form";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import PhoneInput from "@calcom/features/components/phone-input";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
import { Label } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import type { FormValues } from "../pages/workflow";
interface TestAgentDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
agentId: string;
teamId?: number;
form: UseFormReturn<FormValues>;
}
export function TestAgentDialog({ open, onOpenChange, agentId, teamId, form }: TestAgentDialogProps) {
const { t } = useLocale();
const [testPhoneNumber, setTestPhoneNumber] = useState("");
const testCallMutation = trpc.viewer.aiVoiceAgent.testCall.useMutation({
onSuccess: async (data) => {
showToast(data?.message ?? t("call_initiated_successfully"), "success");
onOpenChange(false);
setTestPhoneNumber("");
},
onError: (error: { message: string }) => {
showToast(t(error.message), "error");
},
});
const handleTestCall = () => {
if (!testPhoneNumber) {
showToast(t("please_enter_phone_number"), "error");
return;
}
const firstEventTypeId = form.getValues("activeOn")?.[0]?.value;
if (!firstEventTypeId) {
showToast(t("choose_at_least_one_event_type_test_call"), "error");
return;
}
if (agentId) {
testCallMutation.mutate({
agentId: agentId,
phoneNumber: testPhoneNumber,
teamId: teamId,
eventTypeId: parseInt(firstEventTypeId, 10),
});
}
};
return (
// Without modal={false}, the screen freezes when Sheet is open
<Dialog open={open} onOpenChange={onOpenChange} modal={false}>
<DialogContent
type="creation"
title={t("test_cal_ai_agent")}
description={t("make_test_call_to_verify_configuration")}>
<div>
<Label className="mb-1 block text-sm font-medium">{t("call_to")}:</Label>
<PhoneInput
placeholder={t("enter_phone_number_to_test_call")}
value={testPhoneNumber}
onChange={(val) => setTestPhoneNumber(val || "")}
disabled={testCallMutation.isPending}
/>
</div>
<DialogFooter showDivider>
<Button type="button" color="secondary" onClick={() => onOpenChange(false)}>
{t("cancel")}
</Button>
<Button
type="button"
onClick={handleTestCall}
loading={testCallMutation.isPending}
disabled={!testPhoneNumber}>
<Icon name="phone" className="mr-2 h-4 w-4" />
{t("make_test_call")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -15,7 +15,7 @@ import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/compo
import { Label, MultiSelectCheckbox, TextField, CheckboxField } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { isSMSAction } from "../lib/actionHelperFunctions";
import { isSMSAction, isCalAIAction } from "../lib/actionHelperFunctions";
import type { FormValues } from "../pages/workflow";
import { AddActionDialog } from "./AddActionDialog";
import { DeleteDialog } from "./DeleteDialog";
@@ -41,6 +41,7 @@ interface Props {
isOrg: boolean;
allOptions: Option[];
permissions?: WorkflowPermissions;
onSaveWorkflow?: () => Promise<void>;
}
export default function WorkflowDetailsPage(props: Props) {
@@ -57,6 +58,11 @@ export default function WorkflowDetailsPage(props: Props) {
const { t } = useLocale();
const router = useRouter();
const hasCalAIAction = () => {
const steps = form.getValues("steps") || [];
return steps.some((step) => isCalAIAction(step.action));
};
const permissions = _permissions || {
canView: !teamId ? true : !props.readOnly,
canUpdate: !teamId ? true : !props.readOnly,
@@ -165,25 +171,27 @@ export default function WorkflowDetailsPage(props: Props) {
);
}}
/>
<div className="mt-3">
<Controller
name="selectAll"
render={({ field: { value, onChange } }) => (
<CheckboxField
description={isOrg ? t("apply_to_all_teams") : t("apply_to_all_event_types")}
disabled={props.readOnly}
onChange={(e) => {
onChange(e);
if (e.target.value) {
setSelectedOptions(allOptions);
form.setValue("activeOn", allOptions);
}
}}
checked={value}
/>
)}
/>
</div>
{!hasCalAIAction() && (
<div className="mt-3">
<Controller
name="selectAll"
render={({ field: { value, onChange } }) => (
<CheckboxField
description={isOrg ? t("apply_to_all_teams") : t("apply_to_all_event_types")}
disabled={props.readOnly}
onChange={(e) => {
onChange(e);
if (e.target.value) {
setSelectedOptions(allOptions);
form.setValue("activeOn", allOptions);
}
}}
checked={value}
/>
)}
/>
</div>
)}
<div className="md:border-subtle my-7 border-transparent md:border-t" />
{permissions.canDelete && (
<Button
@@ -207,6 +215,8 @@ export default function WorkflowDetailsPage(props: Props) {
user={props.user}
teamId={teamId}
readOnly={props.readOnly}
isOrganization={isOrg}
onSaveWorkflow={props.onSaveWorkflow}
/>
</div>
)}
@@ -223,6 +233,8 @@ export default function WorkflowDetailsPage(props: Props) {
setReload={setReload}
teamId={teamId}
readOnly={props.readOnly}
isOrganization={isOrg}
onSaveWorkflow={props.onSaveWorkflow}
/>
);
})}
@@ -260,7 +260,7 @@ export default function WorkflowListPage({ workflows }: Props) {
variant="icon"
StartIcon="pencil"
disabled={
workflow.permissions ? !workflow.permissions.canUpdate : workflow.readOnly
workflow.permissions ? !workflow.permissions?.canUpdate : workflow.readOnly
}
onClick={async () => await router.replace(`/workflows/${workflow.id}`)}
data-testid="edit-button"
@@ -275,7 +275,7 @@ export default function WorkflowListPage({ workflows }: Props) {
color="secondary"
variant="icon"
disabled={
workflow.permissions ? !workflow.permissions.canDelete : workflow.readOnly
workflow.permissions ? !workflow.permissions?.canDelete : workflow.readOnly
}
StartIcon="trash-2"
data-testid="delete-button"
@@ -293,7 +293,7 @@ export default function WorkflowListPage({ workflows }: Props) {
</DropdownMenuTrigger>
<DropdownMenuContent>
{(workflow.permissions
? workflow.permissions.canUpdate
? workflow.permissions?.canUpdate
: !workflow.readOnly) && (
<DropdownMenuItem>
<DropdownItem
@@ -305,7 +305,7 @@ export default function WorkflowListPage({ workflows }: Props) {
</DropdownMenuItem>
)}
{(workflow.permissions
? workflow.permissions.canDelete
? workflow.permissions?.canDelete
: !workflow.readOnly) && (
<DropdownMenuItem>
<DropdownItem
File diff suppressed because it is too large. Load diff
@@ -34,6 +34,10 @@ export function isSMSOrWhatsappAction(action: WorkflowActions) {
return isSMSAction(action) || isWhatsappAction(action);
}
export function isCalAIAction(action: WorkflowActions) {
return action === WorkflowActions.CAL_AI_PHONE_CALL;
}
export function isEmailAction(action: WorkflowActions) {
return (
action === WorkflowActions.EMAIL_ADDRESS ||
@@ -1,9 +1,14 @@
import type { TFunction } from "i18next";
import { WorkflowActions } from "@calcom/prisma/enums";
import type { WorkflowActions } from "@calcom/prisma/enums";
import { WorkflowTemplates, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import { isSMSOrWhatsappAction, isWhatsappAction, isEmailToAttendeeAction } from "./actionHelperFunctions";
import {
isSMSOrWhatsappAction,
isWhatsappAction,
isEmailToAttendeeAction,
isCalAIAction,
} from "./actionHelperFunctions";
import {
WHATSAPP_WORKFLOW_TEMPLATES,
WORKFLOW_ACTIONS,
@@ -13,13 +18,13 @@ import {
} from "./constants";
export function getWorkflowActionOptions(t: TFunction, isOrgsPlan?: boolean) {
return WORKFLOW_ACTIONS.filter((action) => action !== WorkflowActions.CAL_AI_PHONE_CALL).map((action) => {
return WORKFLOW_ACTIONS.map((action) => {
const actionString = t(`${action.toLowerCase()}_action`);
return {
label: actionString.charAt(0).toUpperCase() + actionString.slice(1),
value: action,
needsCredits: !isOrgsPlan && isSMSOrWhatsappAction(action),
needsCredits: (!isOrgsPlan && isSMSOrWhatsappAction(action)) || isCalAIAction(action),
};
});
}
@@ -0,0 +1,342 @@
import { v4 as uuidv4 } from "uuid";
import dayjs from "@calcom/dayjs";
import { CAL_AI_AGENT_PHONE_NUMBER_FIELD } from "@calcom/features/bookings/lib/SystemField";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import tasker from "@calcom/features/tasker";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
import { WorkflowMethods, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import type { TimeUnit } from "@calcom/prisma/enums";
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type { BookingInfo } from "./smsReminderManager";
type timeUnitLowerCase = "day" | "hour" | "minute";
function extractPhoneNumber(responses: BookingInfo["responses"]): string | undefined {
if (!responses) return undefined;
// Priority 1: CAL_AI_AGENT_PHONE_NUMBER_FIELD first
const aiAgentPhoneResponse = responses[CAL_AI_AGENT_PHONE_NUMBER_FIELD];
if (aiAgentPhoneResponse && typeof aiAgentPhoneResponse === "object" && "value" in aiAgentPhoneResponse) {
return aiAgentPhoneResponse.value as string;
}
// Priority 2: attendeePhoneNumber as fallback
const attendeePhoneResponse = responses.attendeePhoneNumber;
if (
attendeePhoneResponse &&
typeof attendeePhoneResponse === "object" &&
"value" in attendeePhoneResponse
) {
return attendeePhoneResponse.value as string;
}
return undefined;
}
interface CreateWorkflowReminderAndExtractPhoneArgs {
evt: BookingInfo;
workflowStepId: number;
scheduledDate: dayjs.Dayjs;
seatReferenceUid?: string;
}
interface CreateWorkflowReminderAndExtractPhoneResult {
workflowReminder: { id: number; uuid: string | null };
attendeePhoneNumber: string;
}
const createWorkflowReminderAndExtractPhone = async (
args: CreateWorkflowReminderAndExtractPhoneArgs
): Promise<CreateWorkflowReminderAndExtractPhoneResult> => {
const { evt, workflowStepId, scheduledDate, seatReferenceUid } = args;
// 1) Determine attendee phone first (fail early)
let attendeePhoneNumber = extractPhoneNumber(evt.responses);
if (!attendeePhoneNumber) {
const attendeePhone = evt.attendees?.[0]?.phoneNumber;
if (attendeePhone) {
attendeePhoneNumber = attendeePhone;
} else {
throw new Error(`No attendee phone number found for workflow step ${workflowStepId}`);
}
}
const workflowReminder = await prisma.workflowReminder.create({
data: {
bookingUid: evt.uid as string,
workflowStepId,
method: WorkflowMethods.AI_PHONE_CALL,
scheduledDate: scheduledDate.toDate(),
scheduled: true,
seatReferenceId: seatReferenceUid,
},
});
return { workflowReminder, attendeePhoneNumber };
};
interface ScheduleAIPhoneCallArgs {
evt: BookingInfo;
triggerEvent: WorkflowTriggerEvents;
timeSpan: {
time: number | null;
timeUnit: TimeUnit | null;
};
workflowStepId: number | undefined;
userId: number | null;
teamId: number | null;
seatReferenceUid?: string;
verifiedAt: Date | null;
}
export const scheduleAIPhoneCall = async (args: ScheduleAIPhoneCallArgs) => {
const { evt, triggerEvent, timeSpan, workflowStepId, userId, teamId, seatReferenceUid, verifiedAt } = args;
if (!verifiedAt || !workflowStepId) {
logger.warn(`Workflow step ${workflowStepId} not yet verified or not found`);
return;
}
// Get the workflow step to check if it has an agent configured
const workflowStep = await prisma.workflowStep.findUnique({
where: { id: workflowStepId },
select: {
agent: {
select: {
id: true,
providerAgentId: true,
outboundPhoneNumbers: {
select: {
phoneNumber: true,
subscriptionStatus: true,
},
},
},
},
},
});
const activePhoneNumbers = workflowStep?.agent?.outboundPhoneNumbers?.filter(
(phoneNumber) =>
phoneNumber.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE ||
phoneNumber.subscriptionStatus === null ||
phoneNumber.subscriptionStatus === undefined
);
if (!workflowStep?.agent) {
logger.warn(`No agent configured for workflow step ${workflowStepId}`);
return;
}
if (!workflowStep.agent.outboundPhoneNumbers?.length || !activePhoneNumbers?.length) {
logger.warn(`No active outbound phone number configured for agent ${workflowStep.agent.id}`);
return;
}
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 { startTime, endTime } = evt;
const uid = evt.uid as string;
const currentDate = dayjs();
const timeUnit: timeUnitLowerCase | undefined = timeSpan.timeUnit?.toLocaleLowerCase() as timeUnitLowerCase;
let scheduledDate = null;
// Calculate when the AI phone call should be made
if (triggerEvent === WorkflowTriggerEvents.BEFORE_EVENT) {
scheduledDate = timeSpan.time && timeUnit ? dayjs(startTime).subtract(timeSpan.time, timeUnit) : null;
} else if (triggerEvent === WorkflowTriggerEvents.AFTER_EVENT) {
scheduledDate = timeSpan.time && timeUnit ? dayjs(endTime).add(timeSpan.time, timeUnit) : null;
}
// For immediate triggers (like NEW_EVENT, EVENT_CANCELLED, etc.), schedule immediately
if (!scheduledDate) {
scheduledDate = currentDate;
}
// Determine if we should execute immediately or schedule for later
const shouldExecuteImmediately =
// Immediate triggers (NEW_EVENT, EVENT_CANCELLED, etc.)
!timeSpan.time ||
!timeSpan.timeUnit ||
// Or if the scheduled time has already passed
(scheduledDate && currentDate.isAfter(scheduledDate));
if (!shouldExecuteImmediately) {
try {
const { workflowReminder, attendeePhoneNumber } = await createWorkflowReminderAndExtractPhone({
evt,
workflowStepId,
scheduledDate,
seatReferenceUid,
});
// Schedule the actual AI phone call
await scheduleAIPhoneCallTask({
workflowReminderId: workflowReminder.id,
scheduledDate: scheduledDate.toDate(),
agentId: workflowStep.agent.id,
phoneNumber: activePhoneNumbers[0].phoneNumber,
attendeePhoneNumber,
bookingUid: uid,
userId,
teamId,
providerAgentId: workflowStep.agent.providerAgentId,
referenceUid: workflowReminder.uuid || uuidv4(),
});
logger.info(`AI phone call scheduled for workflow step ${workflowStepId} at ${scheduledDate}`);
} catch (error) {
logger.error(`Error scheduling AI phone call with error ${error}`);
}
} else {
// Execute immediately
try {
const { workflowReminder, attendeePhoneNumber } = await createWorkflowReminderAndExtractPhone({
evt,
workflowStepId,
scheduledDate: currentDate,
seatReferenceUid,
});
// Schedule the actual AI phone call immediatel
// Should i execute the task immediately or schedule it for later?
await scheduleAIPhoneCallTask({
workflowReminderId: workflowReminder.id,
scheduledDate: currentDate.toDate(),
agentId: workflowStep.agent.id,
phoneNumber: activePhoneNumbers[0].phoneNumber,
attendeePhoneNumber,
bookingUid: uid,
userId,
teamId,
providerAgentId: workflowStep.agent.providerAgentId,
referenceUid: workflowReminder.uuid || uuidv4(),
});
logger.info(`AI phone call scheduled for immediate execution for workflow step ${workflowStepId}`);
} catch (error) {
logger.error(`Error scheduling immediate AI phone call with error ${error}`);
}
}
};
interface ScheduleAIPhoneCallTaskArgs {
workflowReminderId: number;
scheduledDate: Date;
agentId: string;
phoneNumber: string;
attendeePhoneNumber: string;
bookingUid: string;
userId: number | null;
teamId: number | null;
providerAgentId: string;
referenceUid: string;
}
const scheduleAIPhoneCallTask = async (args: ScheduleAIPhoneCallTaskArgs) => {
const {
workflowReminderId,
scheduledDate,
agentId,
phoneNumber,
attendeePhoneNumber,
bookingUid,
userId,
teamId,
providerAgentId,
referenceUid,
} = args;
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");
return;
}
if (userId) {
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: `ai-phone-call:${userId}`,
});
}
try {
await tasker.create(
"executeAIPhoneCall",
{
workflowReminderId,
agentId,
fromNumber: phoneNumber,
toNumber: attendeePhoneNumber,
bookingUid,
userId,
teamId,
providerAgentId,
},
{
scheduledAt: scheduledDate,
maxAttempts: 1,
referenceUid,
}
);
} catch (error) {
console.error("Error creating AI phone call task:", error);
throw error;
}
};
export const deleteScheduledAIPhoneCall = async (reminderId: number, referenceId: string | null) => {
const workflowReminder = await prisma.workflowReminder.findUnique({
where: {
id: reminderId,
},
});
if (!workflowReminder) {
logger.error("AI Phone Call workflow reminder not found");
return;
}
const { uuid } = workflowReminder;
const taskReferenceId = referenceId || uuid;
if (taskReferenceId) {
try {
const taskId = await tasker.cancelWithReference(taskReferenceId, "executeAIPhoneCall");
if (taskId) {
await prisma.workflowReminder.delete({
where: {
id: reminderId,
},
});
logger.info(`AI phone call reminder ${reminderId} cancelled and deleted`);
return;
}
} catch (error) {
logger.error(`Error canceling/deleting AI phone call reminder with tasker. Error: ${error}`);
}
}
// Fallback: If tasker cancellation fails or uuid is not found, just delete the reminder
try {
await prisma.workflowReminder.delete({
where: {
id: reminderId,
},
});
logger.info(`AI phone call reminder ${reminderId} deleted (no task to cancel)`);
} catch (error) {
logger.error(`Error deleting AI phone call reminder ${reminderId}: ${error}`);
}
};
@@ -3,6 +3,7 @@ import {
isSMSAction,
isSMSOrWhatsappAction,
isWhatsappAction,
isCalAIAction,
} from "@calcom/features/ee/workflows/lib/actionHelperFunctions";
import { sendOrScheduleWorkflowEmails } from "@calcom/features/ee/workflows/lib/reminders/providers/emailProvider";
import * as twilio from "@calcom/features/ee/workflows/lib/reminders/providers/twilioProvider";
@@ -16,6 +17,7 @@ import { SchedulingType } from "@calcom/prisma/enums";
import { WorkflowActions, WorkflowMethods, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { scheduleAIPhoneCall } from "./aiPhoneCallManager";
import { scheduleEmailReminder } from "./emailReminderManager";
import { scheduleSMSReminder } from "./smsReminderManager";
import type { ScheduleTextReminderAction } from "./smsReminderManager";
@@ -180,6 +182,20 @@ const processWorkflowStep = async (
seatReferenceUid,
verifiedAt: step.verifiedAt,
});
} else if (isCalAIAction(step.action)) {
await scheduleAIPhoneCall({
evt,
triggerEvent: workflow.trigger,
timeSpan: {
time: workflow.time,
timeUnit: workflow.timeUnit,
},
workflowStepId: step.id,
userId: workflow.userId,
teamId: workflow.teamId,
seatReferenceUid,
verifiedAt: step.verifiedAt,
});
}
};
+2 -1
View File
@@ -38,7 +38,8 @@ export const formSchema = z.object({
.refine((val) => onlyLettersNumbersSpaces(val))
.optional()
.nullable(),
senderName: z.string().optional().nullable(),
senderName: z.string().nullish(),
agentId: z.string().nullish(),
})
.array(),
selectAll: z.boolean(),
@@ -1,5 +1,7 @@
import { describe, beforeEach, vi, test, expect } from "vitest";
import { CreditUsageType } from "@calcom/prisma/enums";
vi.mock("@calcom/lib/constants", async () => {
const actual = await vi.importActual<typeof import("@calcom/lib/constants")>("@calcom/lib/constants");
return {
@@ -78,6 +80,7 @@ describe("Twilio Webhook Handler", () => {
bookingUid: undefined,
smsSid: "SM123",
credits: 0,
creditFor: CreditUsageType.SMS,
});
});
@@ -115,6 +118,7 @@ describe("Twilio Webhook Handler", () => {
bookingUid: undefined,
smsSid: "SM123",
credits: 0,
creditFor: CreditUsageType.SMS,
});
});
@@ -151,6 +155,9 @@ describe("Twilio Webhook Handler", () => {
bookingUid: undefined,
smsSid: "SM123",
credits: null,
creditFor: CreditUsageType.SMS,
smsSegments: undefined,
teamId: undefined,
});
});
});
+167 -105
View File
@@ -10,6 +10,7 @@ import Shell, { ShellMain } from "@calcom/features/shell/Shell";
import { SENDER_ID } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import type { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import type { TimeUnit, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import { WorkflowActions } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
@@ -26,14 +27,14 @@ import { showToast } from "@calcom/ui/components/toast";
import LicenseRequired from "../../common/components/LicenseRequired";
import SkeletonLoader from "../components/SkeletonLoaderEdit";
import WorkflowDetailsPage from "../components/WorkflowDetailsPage";
import { isSMSAction, isSMSOrWhatsappAction } from "../lib/actionHelperFunctions";
import { isSMSAction, isSMSOrWhatsappAction, isCalAIAction } from "../lib/actionHelperFunctions";
import { formSchema } from "../lib/schema";
import { getTranslatedText, translateVariablesToEnglish } from "../lib/variableTranslations";
export type FormValues = {
name: string;
activeOn: Option[];
steps: (WorkflowStep & { senderName: string | null })[];
steps: (WorkflowStep & { senderName: string | null; agentId?: string | null })[];
trigger: WorkflowTriggerEvents;
time?: number;
timeUnit?: TimeUnit;
@@ -42,9 +43,17 @@ export type FormValues = {
type PageProps = {
workflow: number;
workflowData?: Awaited<ReturnType<typeof WorkflowRepository.getById>>;
verifiedNumbers?: Awaited<ReturnType<typeof WorkflowRepository.getVerifiedNumbers>>;
verifiedEmails?: Awaited<ReturnType<typeof WorkflowRepository.getVerifiedEmails>>;
};
function WorkflowPage({ workflow: workflowId }: PageProps) {
function WorkflowPage({
workflow: workflowId,
workflowData: workflowDataProp,
verifiedNumbers: verifiedNumbersProp,
verifiedEmails: verifiedEmailsProp,
}: PageProps) {
const { t, i18n } = useLocale();
const session = useSession();
@@ -64,23 +73,35 @@ function WorkflowPage({ workflow: workflowId }: PageProps) {
const {
data: workflowData,
isError,
isError: _isError,
error,
isPending: isPendingWorkflow,
} = trpc.viewer.workflows.get.useQuery({ id: +workflowId });
const workflow = workflowData;
const { data: verifiedNumbers } = trpc.viewer.workflows.getVerifiedNumbers.useQuery(
{ teamId: workflow?.team?.id },
isPending: _isPendingWorkflow,
} = trpc.viewer.workflows.get.useQuery(
{ id: +workflowId },
{
enabled: !!workflow?.id,
enabled: workflowDataProp ? false : !!workflowId,
}
);
const { data: verifiedEmails } = trpc.viewer.workflows.getVerifiedEmails.useQuery({
teamId: workflow?.team?.id,
});
const workflow = workflowDataProp || workflowData;
const isPendingWorkflow = workflowDataProp ? false : _isPendingWorkflow;
const isError = workflowDataProp ? false : _isError;
const { data: verifiedNumbersData } = trpc.viewer.workflows.getVerifiedNumbers.useQuery(
{ teamId: workflow?.team?.id },
{
enabled: verifiedNumbersProp ? false : !!workflow?.id,
}
);
const verifiedNumbers = verifiedNumbersProp || verifiedNumbersData;
const { data: verifiedEmailsData } = trpc.viewer.workflows.getVerifiedEmails.useQuery(
{
teamId: workflow?.team?.id,
},
{ enabled: !verifiedEmailsProp }
);
const verifiedEmails = verifiedEmailsProp || verifiedEmailsData;
const isOrg = workflow?.team?.isOrganization ?? false;
@@ -105,7 +126,11 @@ function WorkflowPage({ workflow: workflowId }: PageProps) {
});
}
const readOnly = !workflow?.permissions.canUpdate;
const hasPermissions = (w: typeof workflow): w is RouterOutputs["viewer"]["workflows"]["get"] => {
return w !== null && w !== undefined && "permissions" in w;
};
const readOnly = workflow && hasPermissions(workflow) ? !workflow.permissions?.canUpdate : true;
const isPending = isPendingWorkflow || isPendingEventTypes;
@@ -120,7 +145,22 @@ function WorkflowPage({ workflow: workflowId }: PageProps) {
useEffect(() => {
if (!isPending) {
setFormData(workflow);
if (hasPermissions(workflow)) {
setFormData(workflow);
} else if (workflow) {
const workflowWithDefaults = {
...workflow,
permissions: {
canUpdate: false,
canView: false,
canDelete: false,
canManage: false,
readOnly: true,
},
readOnly: true,
} as RouterOutputs["viewer"]["workflows"]["get"];
setFormData(workflowWithDefaults);
}
}
}, [isPending]);
@@ -195,16 +235,14 @@ function WorkflowPage({ workflow: workflowId }: PageProps) {
const updateMutation = trpc.viewer.workflows.update.useMutation({
onSuccess: async ({ workflow }) => {
if (workflow) {
await utils.viewer.workflows.get.invalidate({ id: +workflow.id });
showToast(
t("workflow_updated_successfully", {
workflowName: workflow.name,
}),
"success"
);
}
utils.viewer.workflows.get.setData({ id: +workflow.id }, workflow);
setFormData(workflow);
showToast(
t("workflow_updated_successfully", {
workflowName: workflow.name,
}),
"success"
);
},
onError: (err) => {
if (err instanceof HttpError) {
@@ -214,89 +252,112 @@ function WorkflowPage({ workflow: workflowId }: PageProps) {
},
});
const validateAndSubmitWorkflow = async (values: FormValues): Promise<void> => {
let activeOnIds: number[] = [];
let isEmpty = false;
let isVerified = true;
values.steps.forEach((step) => {
const strippedHtml = step.reminderBody?.replace(/<[^>]+>/g, "") || "";
const isBodyEmpty =
!isSMSOrWhatsappAction(step.action) && !isCalAIAction(step.action) && strippedHtml.length <= 1;
if (isBodyEmpty) {
form.setError(`steps.${step.stepNumber - 1}.reminderBody`, {
type: "custom",
message: t("fill_this_field"),
});
}
if (step.reminderBody) {
step.reminderBody = translateVariablesToEnglish(step.reminderBody, {
locale: i18n.language,
t,
});
}
if (step.emailSubject) {
step.emailSubject = translateVariablesToEnglish(step.emailSubject, {
locale: i18n.language,
t,
});
}
isEmpty = !isEmpty ? isBodyEmpty : isEmpty;
//check if phone number is verified
if (
(step.action === WorkflowActions.SMS_NUMBER || step.action === WorkflowActions.WHATSAPP_NUMBER) &&
!verifiedNumbers?.find((verifiedNumber) => verifiedNumber.phoneNumber === step.sendTo)
) {
isVerified = false;
form.setError(`steps.${step.stepNumber - 1}.sendTo`, {
type: "custom",
message: t("not_verified"),
});
}
if (
step.action === WorkflowActions.EMAIL_ADDRESS &&
!verifiedEmails?.find((verifiedEmail) => verifiedEmail === step.sendTo)
) {
isVerified = false;
form.setError(`steps.${step.stepNumber - 1}.sendTo`, {
type: "custom",
message: t("not_verified"),
});
}
});
if (!isEmpty && isVerified) {
if (values.activeOn) {
activeOnIds = values.activeOn
.filter((option) => option.value !== "all")
.map((option) => {
return parseInt(option.value, 10);
});
}
await updateMutation.mutateAsync({
id: workflowId,
name: values.name,
activeOn: activeOnIds,
steps: values.steps,
trigger: values.trigger,
time: values.time || null,
timeUnit: values.timeUnit || null,
isActiveOnAll: values.selectAll || false,
});
utils.viewer.workflows.getVerifiedNumbers.invalidate();
} else {
const validationErrors: string[] = [];
if (isEmpty) {
validationErrors.push(t("workflow_validation_empty_fields"));
}
if (!isVerified) {
validationErrors.push(t("workflow_validation_unverified_contacts"));
}
throw new Error(`${t("workflow_validation_failed")}: ${validationErrors.join("; ")}`);
}
};
const handleSaveWorkflow = async (): Promise<void> => {
const values = form.getValues();
await validateAndSubmitWorkflow(values);
};
return session.data ? (
<Shell withoutMain backPath="/workflows">
<LicenseRequired>
<Form
form={form}
handleSubmit={async (values) => {
let activeOnIds: number[] = [];
let isEmpty = false;
let isVerified = true;
values.steps.forEach((step) => {
const strippedHtml = step.reminderBody?.replace(/<[^>]+>/g, "") || "";
const isBodyEmpty = !isSMSOrWhatsappAction(step.action) && strippedHtml.length <= 1;
if (isBodyEmpty) {
form.setError(`steps.${step.stepNumber - 1}.reminderBody`, {
type: "custom",
message: t("fill_this_field"),
});
}
if (step.reminderBody) {
step.reminderBody = translateVariablesToEnglish(step.reminderBody, {
locale: i18n.language,
t,
});
}
if (step.emailSubject) {
step.emailSubject = translateVariablesToEnglish(step.emailSubject, {
locale: i18n.language,
t,
});
}
isEmpty = !isEmpty ? isBodyEmpty : isEmpty;
//check if phone number is verified
if (
(step.action === WorkflowActions.SMS_NUMBER ||
step.action === WorkflowActions.WHATSAPP_NUMBER) &&
!verifiedNumbers?.find((verifiedNumber) => verifiedNumber.phoneNumber === step.sendTo)
) {
isVerified = false;
form.setError(`steps.${step.stepNumber - 1}.sendTo`, {
type: "custom",
message: t("not_verified"),
});
}
if (
step.action === WorkflowActions.EMAIL_ADDRESS &&
!verifiedEmails?.find((verifiedEmail) => verifiedEmail === step.sendTo)
) {
isVerified = false;
form.setError(`steps.${step.stepNumber - 1}.sendTo`, {
type: "custom",
message: t("not_verified"),
});
}
});
if (!isEmpty && isVerified) {
if (values.activeOn) {
activeOnIds = values.activeOn
.filter((option) => option.value !== "all")
.map((option) => {
return parseInt(option.value, 10);
});
}
updateMutation.mutate({
id: workflowId,
name: values.name,
activeOn: activeOnIds,
steps: values.steps,
trigger: values.trigger,
time: values.time || null,
timeUnit: values.timeUnit || null,
isActiveOnAll: values.selectAll || false,
});
utils.viewer.workflows.getVerifiedNumbers.invalidate();
}
await validateAndSubmitWorkflow(values);
}}>
<ShellMain
backPath="/workflows"
@@ -334,7 +395,7 @@ function WorkflowPage({ workflow: workflowId }: PageProps) {
{isAllDataLoaded && user ? (
<>
<WorkflowDetailsPage
permissions={workflow?.permissions}
permissions={workflow && hasPermissions(workflow) ? workflow.permissions : undefined}
form={form}
workflowId={+workflowId}
user={user}
@@ -344,6 +405,7 @@ function WorkflowPage({ workflow: workflowId }: PageProps) {
readOnly={readOnly}
isOrg={isOrg}
allOptions={isOrg ? teamOptions : allEventTypeOptions}
onSaveWorkflow={handleSaveWorkflow}
/>
</>
) : (
+1
View File
@@ -24,6 +24,7 @@ export type AppFlags = {
pbac: boolean;
"restriction-schedule": boolean;
"team-booking-page-cache": boolean;
"cal-ai-voice-agents": boolean;
};
export type TeamFeatures = Record<keyof AppFlags, boolean>;
+1
View File
@@ -23,6 +23,7 @@ const initialData: AppFlags = {
pbac: false,
"restriction-schedule": false,
"team-booking-page-cache": false,
"cal-ai-voice-agents": false,
};
if (process.env.NEXT_PUBLIC_IS_E2E) {
+5 -5
View File
@@ -1,7 +1,7 @@
import { PROMPT_TEMPLATES } from "@calcom/features/calAIPhone/promptTemplates";
import { RetellAIService, validatePhoneNumber } from "@calcom/features/calAIPhone/retellAIService";
import { templateTypeEnum } from "@calcom/features/calAIPhone/zod-utils";
import type { TCreatePhoneCallSchema } from "@calcom/features/calAIPhone/zod-utils";
import { PROMPT_TEMPLATES, LegacyRetellAIService } from "@calcom/features/calAIPhone";
import { validatePhoneNumber } from "@calcom/features/calAIPhone/retellAIService";
import { templateTypeEnum } from "@calcom/features/calAIPhone";
import type { TCreatePhoneCallSchema } from "@calcom/features/calAIPhone";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
@@ -45,7 +45,7 @@ export const handleCreatePhoneCall = async ({
? userCustomPrompt
: PROMPT_TEMPLATES[templateType]?.generalPrompt;
const retellAI = new RetellAIService({
const retellAI = new LegacyRetellAIService({
templateType,
generalPrompt: generalPrompt ?? "",
beginMessage: beginMessage ?? null,
+2 -1
View File
@@ -36,7 +36,8 @@ export class InternalTasker implements Tasker {
await Task.retry({
taskId: task.id,
lastError: error instanceof Error ? error.message : "Unknown error",
minRetryIntervalMins: taskConfig?.minRetryIntervalMins ?? null,
minRetryIntervalMins:
taskConfig && "minRetryIntervalMins" in taskConfig ? taskConfig.minRetryIntervalMins : null,
});
});
});
+10
View File
@@ -21,6 +21,16 @@ type TaskPayloads = {
sendWorkflowEmails: z.infer<typeof import("./tasks/sendWorkflowEmails").ZSendWorkflowEmailsSchema>;
scanWorkflowBody: z.infer<typeof import("./tasks/scanWorkflowBody").scanWorkflowBodySchema>;
sendAnalyticsEvent: z.infer<typeof import("./tasks/analytics/schema").sendAnalyticsEventSchema>;
executeAIPhoneCall: {
workflowReminderId: number;
agentId: string;
fromNumber: string;
toNumber: string;
bookingUid: string;
userId: number | null;
teamId: number | null;
providerAgentId: string;
};
};
export type TaskTypes = keyof TaskPayloads;
export type TaskHandler = (payload: string) => Promise<void>;
@@ -0,0 +1,246 @@
import dayjs from "@calcom/dayjs";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
interface ExecuteAIPhoneCallPayload {
workflowReminderId: number;
agentId: string;
fromNumber: string;
toNumber: string;
bookingUid: string;
userId: number | null;
teamId: number | null;
providerAgentId: string;
}
const log = logger.getSubLogger({ prefix: [`[[executeAIPhoneCall] `] });
export async function executeAIPhoneCall(payload: string) {
let data: ExecuteAIPhoneCallPayload;
try {
data = JSON.parse(payload);
} catch (error) {
log.error("Failed to parse AI phone call payload", { error, payload });
throw new Error("Invalid JSON payload");
}
const featuresRepository = new FeaturesRepository(prisma);
const calAIVoiceAgents = await featuresRepository.checkIfFeatureIsEnabledGlobally("cal-ai-voice-agents");
if (!calAIVoiceAgents) {
log.warn("Cal AI voice agents are disabled - skipping AI phone call");
return;
}
log.info(`Executing AI phone call for workflow reminder ${data.workflowReminderId}`, data);
try {
// Check if the workflow reminder still exists and is scheduled
const workflowReminder = await prisma.workflowReminder.findUnique({
where: { id: data.workflowReminderId },
select: {
id: true,
scheduled: true,
referenceId: true,
workflowStep: {
select: {
agent: {
select: {
outboundPhoneNumbers: {
select: {
phoneNumber: true,
},
},
},
},
},
},
booking: {
select: {
uid: true,
startTime: true,
endTime: true,
eventTypeId: true,
responses: true,
location: true,
description: true,
attendees: {
select: {
name: true,
email: true,
phoneNumber: true,
timeZone: true,
},
},
eventType: {
select: {
title: true,
bookingFields: true,
},
},
user: {
select: {
name: true,
timeZone: true,
},
},
},
},
},
});
if (!workflowReminder || !workflowReminder.scheduled) {
log.warn(`Workflow reminder ${data.workflowReminderId} not found or not scheduled`);
throw new Error("Reminder not found or not scheduled");
}
if (data.userId || data.teamId) {
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
const creditService = new CreditService();
const hasCredits = await creditService.hasAvailableCredits({
userId: data.userId || undefined,
teamId: data.teamId || undefined,
});
if (!hasCredits) {
log.warn(`Insufficient credits for AI phone call`, {
userId: data.userId,
teamId: data.teamId,
workflowReminderId: data.workflowReminderId,
bookingUid: workflowReminder.booking?.uid,
});
throw new Error(
`Insufficient credits to make AI phone call. Please purchase more credits. user: ${data?.userId}, team: ${data?.teamId}`
);
}
}
const rateLimitIdentifier = data.teamId
? `ai-phone-call:team:${data.teamId}`
: data.userId
? `ai-phone-call:user:${data.userId}`
: null;
if (!rateLimitIdentifier) {
log.warn(`No rate limit identifier found for AI phone call. This should not happen.`, {
userId: data.userId,
teamId: data.teamId,
workflowReminderId: data.workflowReminderId,
});
throw new Error("No rate limit identifier found for AI phone call. This should not happen.");
}
// TODO: add better rate limiting for AI phone calls
if (rateLimitIdentifier) {
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: rateLimitIdentifier,
});
}
const booking = workflowReminder.booking;
if (!booking) {
log.warn(`No booking found for workflow reminder ${data.workflowReminderId}`);
throw new Error("No booking found");
}
const numberToCall = data.toNumber;
if (!numberToCall) {
log.warn(`No phone number found for attendee in booking ${booking.uid}`);
throw new Error("No phone number found for attendee");
}
const attendee = booking.attendees[0];
const timeZone = booking.user?.timeZone || attendee?.timeZone || "UTC";
const { responses } = getCalEventResponses({
bookingFields: booking.eventType?.bookingFields ?? null,
booking: {
...booking,
customInputs: null,
},
});
const attendeeNameWords = attendee?.name?.trim().split(" ") || [];
const attendeeNameWordCount = attendeeNameWords.length;
const attendeeFirstName = attendeeNameWords[0] || "";
const attendeeLastName = attendeeNameWordCount > 1 ? attendeeNameWords[attendeeNameWordCount - 1] : "";
const dynamicVariables = {
EVENT_NAME: booking.eventType?.title || "",
EVENT_DATE: dayjs(booking.startTime).tz(timeZone).format("dddd, MMMM D, YYYY"),
EVENT_TIME: dayjs(booking.startTime).tz(timeZone).format("h:mm A"),
EVENT_END_TIME: dayjs(booking.endTime).tz(timeZone).format("h:mm A"),
TIMEZONE: timeZone,
LOCATION: booking.location || "",
ORGANIZER_NAME: booking.user?.name || "",
ATTENDEE_NAME: attendee?.name || "",
ATTENDEE_FIRST_NAME: attendeeFirstName,
ATTENDEE_LAST_NAME: attendeeLastName,
ATTENDEE_EMAIL: attendee?.email || "",
ATTENDEE_TIMEZONE: attendee?.timeZone || "",
ADDITIONAL_NOTES: booking.description || "",
EVENT_START_TIME_IN_ATTENDEE_TIMEZONE: dayjs(booking.startTime)
.tz(attendee?.timeZone || timeZone)
.format("h:mm A"),
EVENT_END_TIME_IN_ATTENDEE_TIMEZONE: dayjs(booking.endTime)
.tz(attendee?.timeZone || timeZone)
.format("h:mm A"),
// DO NOT REMOVE THIS FIELD. It is used for conditional tool routing in prompts
eventTypeId: booking.eventTypeId?.toString() || "",
// Include any custom form responses
...Object.fromEntries(
Object.entries(responses || {}).map(([key, value]) => [
key
.replace(/[^a-zA-Z0-9 ]/g, "")
.trim()
.replaceAll(" ", "_")
.toUpperCase(),
value.value?.toString() || "",
])
),
};
const aiService = createDefaultAIPhoneServiceProvider();
await aiService.updateToolsFromAgentId(data.providerAgentId, {
eventTypeId: booking.eventTypeId,
timeZone: attendee?.timeZone ?? "Europe/London",
userId: data.userId,
teamId: data.teamId,
});
const call = await aiService.createPhoneCall({
fromNumber: data.fromNumber,
toNumber: numberToCall,
dynamicVariables,
});
log.info("AI phone call created successfully:", call);
// Update the workflow reminder with the call reference
await prisma.workflowReminder.update({
where: { id: data.workflowReminderId },
data: {
referenceId: call.call_id,
scheduled: true,
},
});
log.info(`AI phone call executed successfully for workflow reminder ${data.workflowReminderId}`, {
callId: call.call_id,
agentId: data.agentId,
fromNumber: data.fromNumber,
toNumber: numberToCall,
bookingUid: data.bookingUid,
});
} catch (error) {
log.error("Error executing AI phone call:", error);
throw error;
}
}
+4
View File
@@ -26,6 +26,7 @@ const tasks: Record<TaskTypes, () => Promise<TaskHandler>> = {
scanWorkflowBody: () => import("./scanWorkflowBody").then((module) => module.scanWorkflowBody),
sendAnalyticsEvent: () =>
import("./analytics/sendAnalyticsEvent").then((module) => module.sendAnalyticsEvent),
executeAIPhoneCall: () => import("./executeAIPhoneCall").then((module) => module.executeAIPhoneCall),
};
export const tasksConfig = {
@@ -33,5 +34,8 @@ export const tasksConfig = {
minRetryIntervalMins: IS_PRODUCTION ? 10 : 1,
maxAttempts: 10,
},
executeAIPhoneCall: {
maxAttempts: 1,
},
};
export default tasks;