* 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:
118 files changed
+6650
-918
No files matched your search
+14
-1
@@ -383,10 +383,23 @@ TASKER_ENABLE_EMAILS=0
|
||||
# Ratelimiting via unkey
|
||||
UNKEY_ROOT_KEY=
|
||||
|
||||
# Used for Cal.ai Enterprise Voice AI Agents
|
||||
# Used for Cal.ai Voice AI Agents
|
||||
# https://retellai.com
|
||||
RETELL_AI_KEY=
|
||||
|
||||
# Used for buying phone number for cal ai voice agent
|
||||
STRIPE_PHONE_NUMBER_MONTHLY_PRICE_ID=
|
||||
|
||||
|
||||
CAL_AI_CALL_RATE_PER_MINUTE=0.29
|
||||
|
||||
|
||||
STRIPE_WEBHOOK_SECRET_BILLING=
|
||||
|
||||
|
||||
# Price for buying a phone number for cal.ai voice agent (Default is 5)
|
||||
NEXT_PUBLIC_CAL_AI_PHONE_NUMBER_MONTHLY_PRICE=
|
||||
|
||||
# Used for the huddle01 integration
|
||||
HUDDLE01_API_TOKEN=
|
||||
|
||||
|
||||
@@ -97,3 +97,5 @@ apps/auth
|
||||
!.yarn/sdks
|
||||
!.yarn/versions
|
||||
i18n.cache
|
||||
|
||||
.claude
|
||||
@@ -0,0 +1,5 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
|
||||
import handler from "@calcom/features/calAIPhone/phoneNumberSubscriptionWebhook";
|
||||
|
||||
export const GET = defaultResponderForAppDir(handler);
|
||||
@@ -0,0 +1,686 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { Retell } from "retell-sdk";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
|
||||
import type { CalAiPhoneNumber, User, Team } from "@calcom/prisma/client";
|
||||
|
||||
import { POST } from "../route";
|
||||
|
||||
type MockPhoneNumberWithUser = Omit<CalAiPhoneNumber, "user" | "team"> & {
|
||||
user: Pick<User, "id" | "email" | "name">;
|
||||
team: null;
|
||||
};
|
||||
|
||||
type MockPhoneNumberWithTeam = Omit<CalAiPhoneNumber, "user" | "team"> & {
|
||||
user: null;
|
||||
team: Pick<Team, "id" | "name">;
|
||||
};
|
||||
|
||||
type RetellWebhookBody = {
|
||||
event: "call_started" | "call_ended" | "call_analyzed";
|
||||
call: {
|
||||
call_id: string;
|
||||
agent_id?: string;
|
||||
from_number?: string;
|
||||
to_number?: string;
|
||||
direction?: "inbound" | "outbound";
|
||||
call_status?: string;
|
||||
start_timestamp?: number;
|
||||
end_timestamp?: number;
|
||||
disconnection_reason?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
retell_llm_dynamic_variables?: Record<string, unknown>;
|
||||
transcript?: string;
|
||||
opt_out_sensitive_data_storage?: boolean;
|
||||
call_cost?: {
|
||||
product_costs?: Array<{
|
||||
product: string;
|
||||
unitPrice?: number;
|
||||
cost?: number;
|
||||
}>;
|
||||
total_duration_seconds?: number;
|
||||
total_duration_unit_price?: number;
|
||||
total_one_time_price?: number;
|
||||
combined_cost?: number;
|
||||
};
|
||||
call_analysis?: {
|
||||
call_summary?: string;
|
||||
in_voicemail?: boolean;
|
||||
user_sentiment?: string;
|
||||
call_successful?: boolean;
|
||||
custom_analysis_data?: Record<string, unknown>;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
vi.mock("app/api/defaultResponderForAppDir", () => ({
|
||||
defaultResponderForAppDir:
|
||||
(
|
||||
handler: (req: NextRequest, context: { params: Promise<Record<string, string>> }) => Promise<Response>
|
||||
) =>
|
||||
async (req: NextRequest, context?: { params: Promise<Record<string, string>> }) =>
|
||||
await handler(req, context || { params: Promise.resolve({}) }),
|
||||
}));
|
||||
|
||||
vi.mock("retell-sdk", () => ({
|
||||
Retell: {
|
||||
verify: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockHasAvailableCredits = vi.fn();
|
||||
const mockChargeCredits = vi.fn();
|
||||
|
||||
vi.mock("@calcom/features/ee/billing/credit-service", () => ({
|
||||
CreditService: vi.fn().mockImplementation(() => ({
|
||||
hasAvailableCredits: mockHasAvailableCredits,
|
||||
chargeCredits: mockChargeCredits,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/server/repository/PrismaPhoneNumberRepository", () => ({
|
||||
PrismaPhoneNumberRepository: {
|
||||
findByPhoneNumber: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("next/server", () => ({
|
||||
NextResponse: {
|
||||
json: vi.fn((data, options) => ({
|
||||
json: () => Promise.resolve(data),
|
||||
status: options?.status || 200,
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
const createMockRequest = (body: RetellWebhookBody, signature?: string): NextRequest => {
|
||||
const request = {
|
||||
text: vi.fn().mockResolvedValue(JSON.stringify(body)),
|
||||
headers: {
|
||||
get: vi.fn((name: string) => (name === "x-retell-signature" ? signature : null)),
|
||||
},
|
||||
} as unknown as NextRequest;
|
||||
return request;
|
||||
};
|
||||
|
||||
const callPOST = (request: NextRequest) => POST(request, { params: Promise.resolve({}) });
|
||||
|
||||
describe("Retell AI Webhook Handler", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubEnv("RETELL_AI_KEY", "test-api-key");
|
||||
vi.stubEnv("CAL_AI_CALL_RATE_PER_MINUTE", "0.29");
|
||||
});
|
||||
|
||||
it("should return 401 when signature is missing", async () => {
|
||||
const request = createMockRequest(
|
||||
{ event: "call_analyzed", call: { call_id: "test-call-id" } },
|
||||
"some-signature"
|
||||
);
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
|
||||
it("should return 401 when API key is not configured", async () => {
|
||||
vi.unstubAllEnvs();
|
||||
|
||||
const request = createMockRequest(
|
||||
{ event: "call_analyzed", call: { call_id: "test-call-id" } },
|
||||
"some-signature"
|
||||
);
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
|
||||
// Restore the stubbed env for subsequent tests
|
||||
vi.stubEnv("RETELL_AI_KEY", "test-api-key");
|
||||
});
|
||||
|
||||
it("should return 401 when signature is invalid", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(false);
|
||||
|
||||
const request = createMockRequest(
|
||||
{ event: "call_analyzed", call: { call_id: "test-call-id" } },
|
||||
"invalid-signature"
|
||||
);
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
|
||||
it("should handle non-call_analyzed events", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_started",
|
||||
call: { call_id: "test-call-id" },
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const data = await response.json();
|
||||
expect(data.success).toBe(true);
|
||||
expect(data.message).toContain("No handling for call_started");
|
||||
});
|
||||
|
||||
it("should process call_analyzed event with valid phone number and sufficient credits", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 1,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "[email protected]", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 120,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const data = await response.json();
|
||||
expect(data.success).toBe(true);
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 1,
|
||||
teamId: undefined,
|
||||
credits: 58, // 120 seconds = 2 minutes * $0.29 = $0.58 = 58 credits
|
||||
callDuration: 120,
|
||||
externalRef: "retell:test-call-id",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle team phone numbers", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const mockTeamPhoneNumber: MockPhoneNumberWithTeam = {
|
||||
id: 2,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: null,
|
||||
teamId: 5,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id-2",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
team: { id: 5, name: "Test Team" },
|
||||
user: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockTeamPhoneNumber);
|
||||
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 50,
|
||||
total_duration_seconds: 180,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: undefined,
|
||||
teamId: 5,
|
||||
credits: 87, // 180 seconds = 3 minutes * $0.29 = $0.87 = 87 credits
|
||||
callDuration: 180,
|
||||
externalRef: "retell:test-call-id",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle missing total_duration_seconds", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
// missing total_duration_seconds
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(PrismaPhoneNumberRepository.findByPhoneNumber).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle phone number not found", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(null);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 90,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockChargeCredits).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle insufficient credits", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 3,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id-3",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "[email protected]", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
mockHasAvailableCredits.mockResolvedValue(false);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 150,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it("should handle schema validation errors", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
// Missing required fields like from_number, to_number, etc.
|
||||
call_id: "test-call-id",
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const data = await response.json();
|
||||
expect(data.error).toBe("Internal server error");
|
||||
});
|
||||
|
||||
it("should calculate credits correctly based on duration", async () => {
|
||||
const testCases = [
|
||||
{ durationSeconds: 60, expectedCredits: 29 }, // 1 minute * $0.29 = $0.29 = 29 credits
|
||||
{ durationSeconds: 120, expectedCredits: 58 }, // 2 minutes * $0.29 = $0.58 = 58 credits
|
||||
{ durationSeconds: 150, expectedCredits: 73 }, // 2.5 minutes * $0.29 = $0.725 = 73 credits (rounded up)
|
||||
{ durationSeconds: 30, expectedCredits: 15 }, // 0.5 minutes * $0.29 = $0.145 = 15 credits (rounded up)
|
||||
];
|
||||
|
||||
for (const { durationSeconds, expectedCredits } of testCases) {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 4,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id-4",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "[email protected]", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: `test-call-${durationSeconds}s`,
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100, // This is ignored now
|
||||
total_duration_seconds: durationSeconds,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
await callPOST(request);
|
||||
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 1,
|
||||
teamId: undefined,
|
||||
credits: expectedCredits,
|
||||
callDuration: durationSeconds,
|
||||
externalRef: expect.stringMatching(/^retell:test-call-/),
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("should pass callDuration to chargeCredits when provided", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 10,
|
||||
phoneNumber: "+15550001111",
|
||||
userId: 42,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "prov-10",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 42, email: "[email protected]", name: "U" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockHasAvailableCredits.mockResolvedValue(true);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "call-dur",
|
||||
from_number: "+15550002222",
|
||||
to_number: "+15550001111",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 123,
|
||||
call_cost: {
|
||||
combined_cost: 12, // This is ignored now
|
||||
total_duration_seconds: 125,
|
||||
},
|
||||
},
|
||||
};
|
||||
const response = await callPOST(createMockRequest(body, "valid-signature"));
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ userId: 42, credits: 61, callDuration: 125 }) // 125s = 2.083 minutes * $0.29 = $0.604 = 61 credits (rounded up)
|
||||
);
|
||||
});
|
||||
|
||||
describe("Idempotency", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should pass externalRef with correct format to chargeCredits", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 1,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "[email protected]", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
mockChargeCredits.mockResolvedValue({ userId: 1 });
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "test-idempotency-call",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 60,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const response = await callPOST(createMockRequest(body, "valid-signature"));
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 1,
|
||||
teamId: undefined,
|
||||
credits: 29, // 60 seconds = 1 minute * $0.29 = $0.29 = 29 credits
|
||||
callDuration: 60,
|
||||
externalRef: "retell:test-idempotency-call",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle duplicate webhook calls idempotently", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 1,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "[email protected]", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "duplicate-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 60,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// First call - should charge normally
|
||||
mockChargeCredits.mockResolvedValue({ userId: 1 });
|
||||
const response1 = await callPOST(createMockRequest(body, "valid-signature"));
|
||||
expect(response1.status).toBe(200);
|
||||
const data1 = await response1.json();
|
||||
expect(data1.success).toBe(true);
|
||||
expect(data1.message).toContain("Successfully charged 29 credits");
|
||||
|
||||
// Second call - should return duplicate
|
||||
mockChargeCredits.mockResolvedValue({ bookingUid: null, duplicate: true });
|
||||
const response2 = await callPOST(createMockRequest(body, "valid-signature"));
|
||||
expect(response2.status).toBe(200);
|
||||
const data2 = await response2.json();
|
||||
expect(data2.success).toBe(true);
|
||||
expect(data2.message).toContain("Successfully charged 29 credits");
|
||||
|
||||
// Verify chargeCredits was called twice with same externalRef
|
||||
expect(mockChargeCredits).toHaveBeenCalledTimes(2);
|
||||
expect(mockChargeCredits).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ externalRef: "retell:duplicate-call-id" })
|
||||
);
|
||||
expect(mockChargeCredits).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ externalRef: "retell:duplicate-call-id" })
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle errors from chargeCredits gracefully", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
const mockPhoneNumber: MockPhoneNumberWithUser = {
|
||||
id: 1,
|
||||
phoneNumber: "+1234567890",
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
provider: "test-provider",
|
||||
providerPhoneNumberId: "test-provider-id",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
subscriptionStatus: null,
|
||||
inboundAgentId: null,
|
||||
outboundAgentId: null,
|
||||
user: { id: 1, email: "[email protected]", name: "Test User" },
|
||||
team: null,
|
||||
};
|
||||
vi.mocked(PrismaPhoneNumberRepository.findByPhoneNumber).mockResolvedValue(mockPhoneNumber);
|
||||
|
||||
// Mock chargeCredits to throw an error
|
||||
mockChargeCredits.mockRejectedValue(new Error("Credit service error"));
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "error-call-id",
|
||||
from_number: "+1234567890",
|
||||
to_number: "+0987654321",
|
||||
direction: "outbound",
|
||||
call_status: "completed",
|
||||
start_timestamp: 1234567890,
|
||||
call_cost: {
|
||||
combined_cost: 100,
|
||||
total_duration_seconds: 60,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const response = await callPOST(createMockRequest(body, "valid-signature"));
|
||||
|
||||
// Should still return 200 to prevent retries
|
||||
expect(response.status).toBe(200);
|
||||
const data = await response.json();
|
||||
expect(data.success).toBe(false);
|
||||
expect(data.message).toContain("Error charging credits for Retell AI call");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,229 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { Retell } from "retell-sdk";
|
||||
import { z } from "zod";
|
||||
|
||||
import { CreditService } from "@calcom/features/ee/billing/credit-service";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
|
||||
import { CreditUsageType } from "@calcom/prisma/enums";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["retell-ai-webhook"] });
|
||||
|
||||
const RetellWebhookSchema = z.object({
|
||||
event: z.enum(["call_started", "call_ended", "call_analyzed"]),
|
||||
call: z
|
||||
.object({
|
||||
call_id: z.string(),
|
||||
agent_id: z.string().optional(),
|
||||
from_number: z.string(),
|
||||
to_number: z.string(),
|
||||
direction: z.enum(["inbound", "outbound"]),
|
||||
call_status: z.string(),
|
||||
start_timestamp: z.number(),
|
||||
end_timestamp: z.number().optional(),
|
||||
disconnection_reason: z.string().optional(),
|
||||
metadata: z.record(z.any()).optional(),
|
||||
retell_llm_dynamic_variables: z.record(z.any()).optional(),
|
||||
transcript: z.string().optional(),
|
||||
opt_out_sensitive_data_storage: z.boolean().optional(),
|
||||
call_cost: z
|
||||
.object({
|
||||
product_costs: z
|
||||
.array(
|
||||
z.object({
|
||||
product: z.string(),
|
||||
unitPrice: z.number().optional(),
|
||||
cost: z.number().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
total_duration_seconds: z.number().optional(),
|
||||
total_duration_unit_price: z.number().optional(),
|
||||
total_one_time_price: z.number().optional(),
|
||||
combined_cost: z.number().optional(),
|
||||
})
|
||||
.optional(),
|
||||
call_analysis: z
|
||||
.object({
|
||||
call_summary: z.string().optional(),
|
||||
in_voicemail: z.boolean().optional(),
|
||||
user_sentiment: z.string().optional(),
|
||||
call_successful: z.boolean().optional(),
|
||||
custom_analysis_data: z.record(z.any()).optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
});
|
||||
|
||||
async function handleCallAnalyzed(callData: any) {
|
||||
const { from_number, call_id, call_cost } = callData;
|
||||
if (
|
||||
!call_cost ||
|
||||
typeof call_cost.total_duration_seconds !== "number" ||
|
||||
!Number.isFinite(call_cost.total_duration_seconds) ||
|
||||
call_cost.total_duration_seconds <= 0
|
||||
) {
|
||||
log.error(
|
||||
`Invalid or missing call_cost.total_duration_seconds for call ${call_id}: ${safeStringify(call_cost)}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const phoneNumber = await PrismaPhoneNumberRepository.findByPhoneNumber({ phoneNumber: from_number });
|
||||
|
||||
if (!phoneNumber) {
|
||||
log.error(`No phone number found for ${from_number}, cannot deduct credits`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Support both personal and team phone numbers
|
||||
const userId = phoneNumber.userId;
|
||||
const teamId = phoneNumber.teamId;
|
||||
|
||||
if (!userId && !teamId) {
|
||||
log.error(`Phone number ${from_number} has no associated user or team`);
|
||||
return;
|
||||
}
|
||||
|
||||
const rawRatePerMinute = process.env.CAL_AI_CALL_RATE_PER_MINUTE ?? "0.29";
|
||||
const ratePerMinute = Number.parseFloat(rawRatePerMinute);
|
||||
const safeRatePerMinute = Number.isFinite(ratePerMinute) && ratePerMinute > 0 ? ratePerMinute : 0.29;
|
||||
|
||||
const durationInMinutes = call_cost.total_duration_seconds / 60;
|
||||
const callCost = durationInMinutes * safeRatePerMinute;
|
||||
// Convert to cents and round up to ensure we don't undercharge
|
||||
const creditsToDeduct = Math.ceil(callCost * 100);
|
||||
|
||||
const creditService = new CreditService();
|
||||
|
||||
try {
|
||||
await creditService.chargeCredits({
|
||||
userId: userId ?? undefined,
|
||||
teamId: teamId ?? undefined,
|
||||
credits: creditsToDeduct,
|
||||
callDuration: call_cost.total_duration_seconds,
|
||||
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
|
||||
externalRef: `retell:${call_id}`,
|
||||
});
|
||||
} catch (e) {
|
||||
log.error("Error charging credits for Retell AI call", {
|
||||
error: e,
|
||||
call_id,
|
||||
call_cost,
|
||||
userId,
|
||||
teamId,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
message: `Error charging credits for Retell AI call: ${
|
||||
e instanceof Error ? e.message : "Unknown error"
|
||||
}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Successfully charged ${creditsToDeduct} credits (${
|
||||
call_cost.total_duration_seconds
|
||||
}s at $${safeRatePerMinute}/min) for ${teamId ? `team:${teamId}` : ""} ${
|
||||
userId ? `user:${userId}` : ""
|
||||
}, call ${call_id}`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Retell AI Webhook Handler
|
||||
*
|
||||
* Setup Instructions:
|
||||
* 1. Add this webhook URL to your Retell AI dashboard: https://yourdomain.com/api/webhooks/retell-ai
|
||||
* 2. Ensure your domain is accessible from the internet (for local development, use ngrok or similar)
|
||||
* 3. Set the RETELL_AI_KEY environment variable with your Retell API key (must have webhook badge)
|
||||
*
|
||||
* This webhook will:
|
||||
* - Verify webhook signature for security
|
||||
* - Receive call_analyzed events from Retell AI
|
||||
* - Charge credits based on the call cost from the user's or team's credit balance
|
||||
* - Log all transactions for audit purposes
|
||||
*/
|
||||
async function handler(request: NextRequest) {
|
||||
const rawBody = await request.text();
|
||||
const body = JSON.parse(rawBody);
|
||||
|
||||
// Verify webhook signature
|
||||
const signature = request.headers.get("x-retell-signature");
|
||||
const apiKey = process.env.RETELL_AI_KEY;
|
||||
|
||||
if (!signature || !apiKey) {
|
||||
log.error("Missing signature or API key for webhook verification");
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Unauthorized",
|
||||
message: "Missing signature or API key",
|
||||
},
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!Retell.verify(rawBody, apiKey, signature)) {
|
||||
log.error("Invalid webhook signature");
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Unauthorized",
|
||||
message: "Invalid signature",
|
||||
},
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
if (body.event !== "call_analyzed") {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
message: `No handling for ${body.event} for call ${body.call?.call_id ?? "unknown"}`,
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = RetellWebhookSchema.parse(body);
|
||||
const callData = payload.call;
|
||||
if (callData.direction === "inbound") {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
message: `Inbound calls are not charged or supported for now. Ignoring call ${callData.call_id}`,
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
|
||||
log.info(`Received Retell AI webhook: ${payload.event} for call ${callData.call_id}`);
|
||||
|
||||
const result = await handleCallAnalyzed(callData);
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: result?.success ?? true,
|
||||
message: result?.message ?? `Processed ${payload.event} for call ${callData.call_id}`,
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
log.error("Error processing Retell AI webhook:", safeStringify(error));
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Internal server error",
|
||||
message: error instanceof Error ? error.message : "Unknown error",
|
||||
},
|
||||
// we need to return 200 to retell ai to avoid retries
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const POST = defaultResponderForAppDir(handler);
|
||||
@@ -1,11 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useSession } from "next-auth/react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import { useState, useMemo } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { IS_SMS_CREDITS_ENABLED } from "@calcom/lib/constants";
|
||||
import { downloadAsCsv } from "@calcom/lib/csvUtils";
|
||||
@@ -27,7 +29,6 @@ type MonthOption = {
|
||||
endDate: string;
|
||||
};
|
||||
|
||||
// returns the last 12 months starting from May 2025 (when credits were introduced)
|
||||
const getMonthOptions = (): MonthOption[] => {
|
||||
const options: MonthOption[] = [];
|
||||
const minDate = dayjs.utc("2025-05-01");
|
||||
@@ -53,6 +54,9 @@ const getMonthOptions = (): MonthOption[] => {
|
||||
export default function BillingCredits() {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const session = useSession();
|
||||
const orgBranding = useOrgBranding();
|
||||
const monthOptions = useMemo(() => getMonthOptions(), []);
|
||||
const [selectedMonth, setSelectedMonth] = useState<MonthOption>(monthOptions[0]);
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
@@ -66,9 +70,28 @@ export default function BillingCredits() {
|
||||
} = useForm<{ quantity: number }>({ defaultValues: { quantity: 50 } });
|
||||
|
||||
const params = useParamsWithFallback();
|
||||
const teamId = params.id ? Number(params.id) : undefined;
|
||||
const orgId = session.data?.user?.org?.id;
|
||||
|
||||
const { data: creditsData, isLoading } = trpc.viewer.credits.getAllCredits.useQuery({ teamId });
|
||||
const parsedTeamId = Number(params.id);
|
||||
const teamId: number | undefined = Number.isFinite(parsedTeamId)
|
||||
? parsedTeamId
|
||||
: typeof orgId === "number"
|
||||
? orgId
|
||||
: undefined;
|
||||
|
||||
const tokens = (pathname ?? "").split("/").filter(Boolean);
|
||||
const settingsIndex = tokens.indexOf("settings");
|
||||
const isOrgScopedPath =
|
||||
settingsIndex >= 0 && ["organizations", "teams"].includes(tokens[settingsIndex + 1]);
|
||||
|
||||
const shouldRender = IS_SMS_CREDITS_ENABLED && !(orgId && !isOrgScopedPath && !orgBranding?.slug);
|
||||
|
||||
const { data: creditsData, isLoading } = trpc.viewer.credits.getAllCredits.useQuery(
|
||||
{ teamId },
|
||||
{ enabled: shouldRender }
|
||||
);
|
||||
|
||||
if (!shouldRender) return null;
|
||||
|
||||
const buyCreditsMutation = trpc.viewer.credits.buyCredits.useMutation({
|
||||
onSuccess: (data) => {
|
||||
@@ -102,10 +125,6 @@ export default function BillingCredits() {
|
||||
}
|
||||
};
|
||||
|
||||
if (!IS_SMS_CREDITS_ENABLED) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isLoading && teamId) return <BillingCreditsSkeleton />;
|
||||
if (!creditsData) return null;
|
||||
|
||||
@@ -206,7 +225,7 @@ export default function BillingCredits() {
|
||||
<hr className="border-subtle mb-3 mt-3" />
|
||||
</div>
|
||||
<div className="flex">
|
||||
<div className="mr-auto ">
|
||||
<div className="mr-auto">
|
||||
<Label className="mb-4">{t("download_expense_log")}</Label>
|
||||
<div className="mt-2 flex flex-col">
|
||||
<Select
|
||||
|
||||
@@ -18,7 +18,7 @@ vi.mock("next/navigation", () => ({
|
||||
useRouter: vi.fn().mockReturnValue({
|
||||
replace: vi.fn(),
|
||||
}),
|
||||
usePathname: vi.fn(),
|
||||
usePathname: vi.fn().mockReturnValue("/settings/billing"),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/app-store/BookingPageTagManager", () => ({
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createNextApiHandler } from "@calcom/trpc/server/createNextApiHandler";
|
||||
import { aiVoiceAgentRouter } from "@calcom/trpc/server/routers/viewer/aiVoiceAgent/_router";
|
||||
|
||||
export default createNextApiHandler(aiVoiceAgentRouter);
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createNextApiHandler } from "@calcom/trpc/server/createNextApiHandler";
|
||||
import { phoneNumberRouter } from "@calcom/trpc/server/routers/viewer/phoneNumber/_router";
|
||||
|
||||
export default createNextApiHandler(phoneNumberRouter);
|
||||
@@ -2,6 +2,7 @@ import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { z } from "zod";
|
||||
|
||||
import * as twilio from "@calcom/features/ee/workflows/lib/reminders/providers/twilioProvider";
|
||||
import { CreditUsageType } from "@calcom/prisma/enums";
|
||||
import { IS_SMS_CREDITS_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getPublishedOrgIdFromMemberOrTeamId } from "@calcom/lib/getOrgIdFromMemberOrTeamId";
|
||||
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
|
||||
@@ -101,6 +102,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
bookingUid: parsedBookingUid,
|
||||
smsSid,
|
||||
credits: 0,
|
||||
creditFor: CreditUsageType.SMS,
|
||||
});
|
||||
|
||||
return res.status(200).send(`SMS to US and CA are free for teams. Credits set to 0`);
|
||||
@@ -135,6 +137,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
bookingUid: parsedBookingUid,
|
||||
smsSid,
|
||||
credits: 0,
|
||||
creditFor: CreditUsageType.SMS,
|
||||
});
|
||||
|
||||
return res.status(200).send(`SMS are free for organizations. Credits set to 0`);
|
||||
@@ -151,6 +154,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
smsSid,
|
||||
bookingUid: parsedBookingUid,
|
||||
smsSegments: numSegments ?? undefined,
|
||||
creditFor: CreditUsageType.SMS,
|
||||
});
|
||||
|
||||
if (chargedUserOrTeamId) {
|
||||
|
||||
@@ -804,6 +804,40 @@
|
||||
"multiple_duration_timeUnit_short": "{{count}}$t({{unit}}_short)",
|
||||
"minutes": "Minutes",
|
||||
"use_cal_ai_to_make_call_description": "Use Cal.ai to get an AI powered phone number or make calls to guests.",
|
||||
"termination_uri": "Termination URI",
|
||||
"sip_trunk_username": "SIP Trunk User Name",
|
||||
"sip_trunk_password": "SIP Trunk Password",
|
||||
"nickname": "Nickname",
|
||||
"delete_phone_number": "Delete Phone Number",
|
||||
"workflow_validation_failed": "Workflow validation failed",
|
||||
"workflow_validation_empty_fields": "One or more workflow steps have empty message content",
|
||||
"workflow_validation_unverified_contacts": "One or more phone numbers or email addresses are not verified",
|
||||
"phone_number_imported_successfully": "Phone number imported and linked to agent successfully",
|
||||
"phone_number_deleted_successfully": "Phone number deleted successfully",
|
||||
"delete_phone_number_confirmation": "Are you sure you want to delete this phone number? This action cannot be undone.",
|
||||
"yes_delete_phone_number": "Yes, delete phone number",
|
||||
"phone_number_info_tooltip": "The number you are trying to import must be in E.164 format (+country code followed by the number, with no spaces or special characters), e.g. +1234567890",
|
||||
"termination_uri_info_tooltip": "The termination uri to uniquely identify your elastic SIP trunk. This is used for outbound calls. For Twilio elastic SIP trunks it always ends with .pstn.twilio.com.",
|
||||
"sip_trunk_username_info_tooltip": "The username used to authenticate the SIP trunk.",
|
||||
"sip_trunk_password_info_tooltip": "The password used to authenticate the SIP trunk.",
|
||||
"nickname_info_tooltip": "Nickname of the number. This is for your reference only.",
|
||||
"save_and_test_call": "Save and Test Call",
|
||||
"call_initiated_successfully": "Call initiated successfully",
|
||||
"please_enter_phone_number": "Please enter a phone number",
|
||||
"agent_updated_successfully": "Agent updated successfully",
|
||||
"agent_created_successfully": "Agent created successfully",
|
||||
"phone_number_unsubscribed_successfully": "Phone number unsubscribed successfully",
|
||||
"general_prompt_description": "This prompt defines the agent's role and primary objectives",
|
||||
"prompt": "Prompt",
|
||||
"call_to": "Call to",
|
||||
"make_test_call_to_verify_configuration": "Make Test Call to Verify Configuration",
|
||||
"initial_message": "Initial Message",
|
||||
"initial_message_description": "The first message the agent will say when starting a call",
|
||||
"having_trouble_importing": "Having trouble importing?",
|
||||
"learn": "Learn",
|
||||
"learn_how_to_get_your_terminator": "Learn how to get your Termination URI and SIP trunk credentials",
|
||||
"phone_number_subscription_cancelled_successfully": "Phone number subscription canceled successfully",
|
||||
"updating": "Updating",
|
||||
"round_robin": "Round Robin",
|
||||
"round_robin_description": "Cycle meetings between multiple team members.",
|
||||
"managed_event": "Managed Event",
|
||||
@@ -812,6 +846,48 @@
|
||||
"managed": "Managed",
|
||||
"managed_event_url_clarification": "\"username\" will be filled by the username of the members assigned",
|
||||
"assign_to": "Assign to",
|
||||
"enter_phone_number_to_test_call": "Enter phone number to test call",
|
||||
"make_test_call": "Make Test Call",
|
||||
"create_new_workflow_agent": "Create new workflow cal.ai voice agent",
|
||||
"create_new_workflow_agent_description": "Create a new workflow cal.ai voice agent to automate your workflows",
|
||||
"phone_number_for_ai_call": "Phone number (for our agent to call)",
|
||||
"buy_a_phone_number_or_import_one_you_already_have": "Buy a phone number or import one you already have on twilio",
|
||||
"test_agent": "Test Agent",
|
||||
"phone_numbers": "Phone Numbers",
|
||||
"unsubscribe": "Unsubscribe",
|
||||
"delete_workflow_step": "Delete Workflow Step",
|
||||
"unsubscribe_phone_number": "Unsubscribe Phone Number",
|
||||
"buy_a_new_number": "Buy a new number",
|
||||
"only_us_phone_numbers_can_be_purchased_here": "You can only buy US phone numbers. For other countries, you can import your own Twilio phone number.",
|
||||
"buy_number_for_x_per_month": "Buy a US Number for ${{priceInDollars}} per month",
|
||||
"supported_call_destinations": "Supported Call Destinations",
|
||||
"no_phone_number_connected":"No phone number connected",
|
||||
"failed_to_get_workflow_step_id": "Failed to get workflow step ID",
|
||||
"cal_ai_agent": "Cal.ai Agent",
|
||||
"test_cal_ai_agent": "Test Cal.ai Agent",
|
||||
"are_you_sure_you_want_to_delete_workflow_step": "Are you sure you want to delete this workflow step?",
|
||||
"do_you_still_want_to_unsubscribe": "Do you still want to unsubscribe the phone number from this agent?",
|
||||
"the_action_will_disconnect_phone_number": "This action will disconnect the phone number from the agent. The agent will not be able to make calls until a new phone number is connected.",
|
||||
"cal_ai_phone_numbers": "Cal AI Phone Numbers",
|
||||
"connect_phone_number": "Connect Phone Number",
|
||||
"cal_ai_phone_numbers_description": "Manage your Cal AI Phone Numbers",
|
||||
"import_number": "Import Number",
|
||||
"this_action_will_also": "This action will also:",
|
||||
"import_phone_number": "Import Phone Number",
|
||||
"active_subscription": "Active Subscription",
|
||||
"cancel_your_phone_number_subscription": "Cancel your phone number subscription",
|
||||
"delete_associated_phone_number": "Delete the associated phone number",
|
||||
"unauthorized_create_workflow": "You are not authorized to create this workflow",
|
||||
"import_phone_number_description": "Import your Twilio phone number to use with Cal AI Phone",
|
||||
"phone_number_cost": "${{price}}/month",
|
||||
"buy_new_number": "Buy New Number",
|
||||
"buy_number_cost_x_per_month": "Buying a phone number costs ${{priceInDollars}} per month. You will be charged monthly for each active phone number.",
|
||||
"area_code_optional": "Area Code (Optional)",
|
||||
"no_phone_numbers": "No phone numbers",
|
||||
"phone_number_purchased_successfully": "Phone number purchased successfully",
|
||||
"cancel_phone_number_subscription": "Cancel Phone Number Subscription",
|
||||
"yes_cancel_subscription": "Yes, Cancel Subscription",
|
||||
"cancel_phone_number_subscription_confirmation": "Are you sure you want to cancel this phone number subscription? This action cannot be undone and you will lose access to this phone number.",
|
||||
"add_members": "Add members...",
|
||||
"no_assigned_members": "No assigned members",
|
||||
"assigned_to": "Assigned to",
|
||||
@@ -1462,6 +1538,7 @@
|
||||
"open": "Open",
|
||||
"close": "Close",
|
||||
"upgrade": "Upgrade",
|
||||
"buy_us_number_button": "Buy US number for {{priceInDollars}}$/month",
|
||||
"upgrade_to_access_recordings_title": "Upgrade to access recordings",
|
||||
"upgrade_to_access_recordings_description": "Recordings are only available as part of our teams plan. Upgrade to start recording your calls",
|
||||
"upgrade_to_cal_ai_phone_number_description": "Upgrade to Enterprise to generate an AI Agent phone number that can call guests to schedule calls",
|
||||
@@ -2635,6 +2712,9 @@
|
||||
"field_identifiers_as_variables_with_example": "Use field identifiers as variables for your custom event redirect (e.g. {{variable}})",
|
||||
"account_already_linked": "Account is already linked",
|
||||
"send_email": "Send email",
|
||||
"cal_ai_phone_call_action": "Call attendee using Cal.ai Voice Agent",
|
||||
"cal_ai_agent_configuration": "Cal.ai Agent Configuration",
|
||||
"choose_at_least_one_event_type_test_call": "Please choose at least one event type to make a test call.",
|
||||
"mark_as_no_show": "Mark as no-show",
|
||||
"unmark_as_no_show": "Unmark no-show",
|
||||
"account_unlinked_success": "Account unlinked successfully",
|
||||
@@ -2643,6 +2723,7 @@
|
||||
"travel_schedule_description": "Plan your trip ahead to keep your existing schedule in a different timezone and prevent being booked at midnight.",
|
||||
"schedule_timezone_change": "Schedule timezone change",
|
||||
"date": "Date",
|
||||
"enter_the_general_prompt_for_the_agent": "Enter the general prompt for the agent",
|
||||
"overlaps_with_existing_schedule": "This overlaps with an existing schedule. Please select a different date.",
|
||||
"org_admin_no_slots|heading": "No availability found for {{name}}",
|
||||
"org_admin_no_slots|content": "Hello Organization Admins,<br /><br />Please note: It has been brought to our attention that {{username}} has not had any availability when a user has visited {{username}}/{{slug}}<br /><br />There's a few reasons why this could be happening<br />The user does not have any calendars connected<br />Their schedules attached to this event are not enabled<br /> <br />We recommend checking their availability to resolve this.",
|
||||
@@ -3339,6 +3420,7 @@
|
||||
"pbac_desc_update_roles": "Update roles",
|
||||
"pbac_desc_delete_roles": "Delete roles",
|
||||
"pbac_desc_create_workflows": "Create and set up new workflows",
|
||||
"set_up_required": "Set up required",
|
||||
"pbac_desc_view_workflows": "View existing workflows and their configurations",
|
||||
"pbac_desc_update_workflows": "Edit and modify workflow settings",
|
||||
"pbac_desc_delete_workflows": "Remove workflows from the system",
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
PREMIUM_PLAN_PRODUCT_ID,
|
||||
STRIPE_TEAM_MONTHLY_PRICE_ID,
|
||||
PREMIUM_MONTHLY_PLAN_PRICE,
|
||||
STRIPE_PHONE_NUMBER_MONTHLY_PRICE_ID
|
||||
STRIPE_PHONE_NUMBER_MONTHLY_PRICE_ID,
|
||||
} from "./constants";
|
||||
|
||||
export const getPremiumMonthlyPlanPriceId = (): string => {
|
||||
@@ -18,11 +18,13 @@ export function getPerSeatPlanPrice(): string {
|
||||
return STRIPE_TEAM_MONTHLY_PRICE_ID;
|
||||
}
|
||||
|
||||
export function getPhoneNumberMonthlyPriceId(): string {
|
||||
if (!STRIPE_PHONE_NUMBER_MONTHLY_PRICE_ID) {
|
||||
throw new Error("STRIPE_PHONE_NUMBER_MONTHLY_PRICE_ID env var is not set");
|
||||
}
|
||||
return STRIPE_PHONE_NUMBER_MONTHLY_PRICE_ID;
|
||||
}
|
||||
|
||||
export function getPremiumPlanPriceValue() {
|
||||
return "$29/month";
|
||||
}
|
||||
|
||||
|
||||
export function getPhoneNumberMonthlyPriceId(){
|
||||
return STRIPE_PHONE_NUMBER_MONTHLY_PRICE_ID;
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
+2
-3
@@ -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>;
|
||||
}
|
||||
+10
-8
@@ -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 {
|
||||
|
||||
+3
-3
@@ -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,
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
+37
-36
@@ -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."
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+13
-18
@@ -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
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -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>;
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -233,3 +233,9 @@ export const DATABASE_CHUNK_SIZE = parseInt(process.env.DATABASE_CHUNK_SIZE || "
|
||||
export const NEXTJS_CACHE_TTL = 3600; // 1 hour
|
||||
|
||||
export const DEFAULT_GROUP_ID = "default_group_id";
|
||||
|
||||
const _rawCalAiPrice = process.env.NEXT_PUBLIC_CAL_AI_PHONE_NUMBER_MONTHLY_PRICE;
|
||||
export const CAL_AI_PHONE_NUMBER_MONTHLY_PRICE = (() => {
|
||||
const parsed = _rawCalAiPrice && _rawCalAiPrice.trim() !== "" ? Number(_rawCalAiPrice) : NaN;
|
||||
return Number.isFinite(parsed) ? parsed : 5;
|
||||
})();
|
||||
@@ -0,0 +1,6 @@
|
||||
import { parsePhoneNumberWithError } from "libphonenumber-js";
|
||||
|
||||
export const formatPhoneNumber = (phoneNumber: string) => {
|
||||
const parsedPhoneNumber = parsePhoneNumberWithError(phoneNumber);
|
||||
return parsedPhoneNumber?.isValid() ? parsedPhoneNumber.formatInternational() : phoneNumber;
|
||||
};
|
||||
@@ -61,15 +61,33 @@ export class PrismaAgentRepository {
|
||||
return memberships.map((membership) => membership.teamId);
|
||||
}
|
||||
|
||||
static async findByIdWithUserAccess({ agentId, userId }: { agentId: string; userId: number }) {
|
||||
static async findByIdWithUserAccess({
|
||||
agentId,
|
||||
userId,
|
||||
teamId,
|
||||
}: {
|
||||
agentId: string;
|
||||
userId: number;
|
||||
teamId?: number;
|
||||
}) {
|
||||
const accessibleTeamIds = await this.getUserAccessibleTeamIds(userId);
|
||||
|
||||
let whereCondition: Prisma.Sql;
|
||||
if (accessibleTeamIds.length > 0) {
|
||||
if (teamId) {
|
||||
// If teamId is provided, check that the user has access to that specific team
|
||||
if (accessibleTeamIds.includes(teamId)) {
|
||||
whereCondition = Prisma.sql`id = ${agentId} AND "teamId" = ${teamId}`;
|
||||
} else {
|
||||
// If user doesn't have access to the team, only check for personal agents
|
||||
whereCondition = Prisma.sql`id = ${agentId} AND "userId" = ${userId}`;
|
||||
}
|
||||
} else if (accessibleTeamIds.length > 0) {
|
||||
// No specific teamId provided, check both personal and team agents
|
||||
whereCondition = Prisma.sql`id = ${agentId} AND ("userId" = ${userId} OR "teamId" IN (${Prisma.join(
|
||||
accessibleTeamIds
|
||||
)}))`;
|
||||
} else {
|
||||
// User has no team access, only check personal agents
|
||||
whereCondition = Prisma.sql`id = ${agentId} AND "userId" = ${userId}`;
|
||||
}
|
||||
|
||||
@@ -280,16 +298,16 @@ export class PrismaAgentRepository {
|
||||
user: agent.user_id
|
||||
? {
|
||||
id: agent.user_id,
|
||||
name: agent.user_name,
|
||||
email: agent.user_email,
|
||||
name: agent.user_name ?? null,
|
||||
email: agent.user_email ?? null,
|
||||
}
|
||||
: null,
|
||||
team: agent.team_id
|
||||
? {
|
||||
id: agent.team_id,
|
||||
name: agent.team_name,
|
||||
slug: agent.team_slug,
|
||||
logoUrl: agent.team_logo_url,
|
||||
name: agent.team_name ?? null,
|
||||
slug: agent.team_slug ?? null,
|
||||
logoUrl: agent.team_logo_url ?? null,
|
||||
}
|
||||
: null,
|
||||
outboundPhoneNumbers: phoneNumbersByAgent[agent.id] || [],
|
||||
@@ -378,15 +396,15 @@ export class PrismaAgentRepository {
|
||||
user: agent.user_id
|
||||
? {
|
||||
id: agent.user_id,
|
||||
name: agent.user_name,
|
||||
email: agent.user_email,
|
||||
name: agent.user_name ?? null,
|
||||
email: agent.user_email ?? null,
|
||||
}
|
||||
: null,
|
||||
team: agent.team_id
|
||||
? {
|
||||
id: agent.team_id,
|
||||
name: agent.team_name,
|
||||
slug: agent.team_slug,
|
||||
name: agent.team_name ?? null,
|
||||
slug: agent.team_slug ?? null,
|
||||
}
|
||||
: null,
|
||||
outboundPhoneNumbers: phoneNumbers.map((pn) => ({
|
||||
@@ -419,7 +437,15 @@ export class PrismaAgentRepository {
|
||||
});
|
||||
}
|
||||
|
||||
static async findByIdWithAdminAccess({ id, userId, teamId }: { id: string; userId: number; teamId?: number }) {
|
||||
static async findByIdWithAdminAccess({
|
||||
id,
|
||||
userId,
|
||||
teamId,
|
||||
}: {
|
||||
id: string;
|
||||
userId: number;
|
||||
teamId?: number;
|
||||
}) {
|
||||
const adminTeamIds = await this.getUserAdminTeamIds(userId);
|
||||
|
||||
let whereCondition: Prisma.Sql;
|
||||
@@ -533,4 +559,4 @@ export class PrismaAgentRepository {
|
||||
|
||||
return Number(result[0].count) > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
export class PrismaApiKeyRepository {
|
||||
static async findApiKeysFromUserId({ userId }: { userId: number }) {
|
||||
return await prisma.apiKey.findMany({
|
||||
const apiKeys = await prisma.apiKey.findMany({
|
||||
where: {
|
||||
userId,
|
||||
OR: [
|
||||
@@ -18,5 +18,11 @@ export class PrismaApiKeyRepository {
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return apiKeys.filter((apiKey) => {
|
||||
if (apiKey.note?.startsWith("Cal AI Phone API Key")) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -143,11 +143,19 @@ export class PrismaPhoneNumberRepository {
|
||||
provider,
|
||||
userId,
|
||||
teamId,
|
||||
stripeCustomerId,
|
||||
stripeSubscriptionId,
|
||||
subscriptionStatus,
|
||||
providerPhoneNumberId,
|
||||
}: {
|
||||
phoneNumber: string;
|
||||
provider?: string;
|
||||
provider: string;
|
||||
userId: number;
|
||||
teamId?: number;
|
||||
stripeCustomerId?: string;
|
||||
stripeSubscriptionId?: string;
|
||||
subscriptionStatus?: PhoneNumberSubscriptionStatus;
|
||||
providerPhoneNumberId?: string;
|
||||
}) {
|
||||
return await prisma.calAiPhoneNumber.create({
|
||||
select: {
|
||||
@@ -159,12 +167,21 @@ export class PrismaPhoneNumberRepository {
|
||||
subscriptionStatus: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
stripeSubscriptionId: true,
|
||||
stripeCustomerId: true,
|
||||
inboundAgentId: true,
|
||||
outboundAgentId: true,
|
||||
providerPhoneNumberId: true,
|
||||
},
|
||||
data: {
|
||||
provider,
|
||||
userId,
|
||||
teamId,
|
||||
phoneNumber,
|
||||
stripeCustomerId,
|
||||
stripeSubscriptionId,
|
||||
subscriptionStatus,
|
||||
providerPhoneNumberId,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -177,6 +194,24 @@ export class PrismaPhoneNumberRepository {
|
||||
});
|
||||
}
|
||||
|
||||
static async findByStripeSubscriptionId({ stripeSubscriptionId }: { stripeSubscriptionId: string }) {
|
||||
return await prisma.calAiPhoneNumber.findFirst({
|
||||
where: {
|
||||
stripeSubscriptionId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
phoneNumber: true,
|
||||
provider: true,
|
||||
userId: true,
|
||||
teamId: true,
|
||||
subscriptionStatus: true,
|
||||
stripeCustomerId: true,
|
||||
stripeSubscriptionId: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findByIdAndUserId({ id, userId }: { id: number; userId: number }) {
|
||||
return await prisma.calAiPhoneNumber.findFirst({
|
||||
where: {
|
||||
@@ -263,6 +298,7 @@ export class PrismaPhoneNumberRepository {
|
||||
userId: true,
|
||||
teamId: true,
|
||||
subscriptionStatus: true,
|
||||
stripeSubscriptionId: true,
|
||||
stripeCustomerId: true,
|
||||
provider: true,
|
||||
inboundAgentId: true,
|
||||
@@ -479,4 +515,20 @@ export class PrismaPhoneNumberRepository {
|
||||
data: updateData,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
static async findByPhoneNumber({ phoneNumber }: { phoneNumber: string }) {
|
||||
return await prisma.calAiPhoneNumber.findFirst({
|
||||
where: {
|
||||
phoneNumber,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
phoneNumber: true,
|
||||
userId: true,
|
||||
teamId: true,
|
||||
user: { select: { id: true, email: true, name: true } },
|
||||
team: { select: { id: true, name: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -132,6 +132,8 @@ describe("CreditsRepository", () => {
|
||||
bookingUid: true,
|
||||
smsSid: true,
|
||||
smsSegments: true,
|
||||
callDuration: true,
|
||||
externalRef: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -167,6 +169,8 @@ describe("CreditsRepository", () => {
|
||||
bookingUid: true,
|
||||
smsSid: true,
|
||||
smsSegments: true,
|
||||
callDuration: true,
|
||||
externalRef: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import prisma, { type PrismaTransaction } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
import type { CreditType } from "@calcom/prisma/enums";
|
||||
|
||||
export class CreditsRepository {
|
||||
@@ -34,6 +34,20 @@ export class CreditsRepository {
|
||||
}
|
||||
}
|
||||
|
||||
static async findCreditExpenseLogByExternalRef(externalRef: string, tx?: PrismaTransaction) {
|
||||
const prismaClient = tx ?? prisma;
|
||||
return await prismaClient.creditExpenseLog.findUnique({
|
||||
where: { externalRef },
|
||||
select: {
|
||||
id: true,
|
||||
credits: true,
|
||||
creditType: true,
|
||||
date: true,
|
||||
bookingUid: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findCreditBalanceWithTeamOrUser(
|
||||
{
|
||||
teamId,
|
||||
@@ -134,6 +148,8 @@ export class CreditsRepository {
|
||||
bookingUid: true,
|
||||
smsSid: true,
|
||||
smsSegments: true,
|
||||
callDuration: true,
|
||||
externalRef: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -198,9 +214,17 @@ export class CreditsRepository {
|
||||
data: Prisma.CreditExpenseLogUncheckedCreateInput,
|
||||
tx?: PrismaTransaction
|
||||
) {
|
||||
return (tx ?? prisma).creditExpenseLog.create({
|
||||
data,
|
||||
});
|
||||
const prismaClient = tx ?? prisma;
|
||||
try {
|
||||
return await prismaClient.creditExpenseLog.create({
|
||||
data,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
|
||||
throw new Error(`Duplicate external reference - already processed: ${data?.externalRef}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
static async createCreditPurchaseLog(data: { credits: number; creditBalanceId: string }) {
|
||||
|
||||
@@ -1408,4 +1408,16 @@ export class EventTypeRepository {
|
||||
metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
|
||||
};
|
||||
}
|
||||
|
||||
async getFirstEventTypeByUserId({ userId }: { userId: number }) {
|
||||
return await this.prismaClient.eventType.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { WorkflowType } from "@calcom/ee/workflows/components/WorkflowListPage";
|
||||
import { deleteScheduledAIPhoneCall } from "@calcom/ee/workflows/lib/reminders/aiPhoneCallManager";
|
||||
import { deleteScheduledEmailReminder } from "@calcom/ee/workflows/lib/reminders/emailReminderManager";
|
||||
import { deleteScheduledSMSReminder } from "@calcom/ee/workflows/lib/reminders/smsReminderManager";
|
||||
import type { WorkflowStep } from "@calcom/ee/workflows/lib/types";
|
||||
import { hasFilter } from "@calcom/features/filters/lib/hasFilter";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/client";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { WorkflowMethods } from "@calcom/prisma/enums";
|
||||
import type { TFilteredListInputSchema } from "@calcom/trpc/server/routers/viewer/workflows/filteredList.schema";
|
||||
@@ -243,7 +246,7 @@ export class WorkflowRepository {
|
||||
if (!filtered) {
|
||||
const workflowsWithReadOnly: WorkflowType[] = allWorkflows.map((workflow) => {
|
||||
const readOnly = !!workflow.team?.members?.find(
|
||||
(member) => member.userId === userId && member.role === "MEMBER"
|
||||
(member) => member.userId === userId && member.role === MembershipRole.MEMBER
|
||||
);
|
||||
|
||||
return { readOnly, isOrg: workflow.team?.isOrganization ?? false, ...workflow };
|
||||
@@ -295,7 +298,7 @@ export class WorkflowRepository {
|
||||
|
||||
const workflowsWithReadOnly: WorkflowType[] = filteredWorkflows.map((workflow) => {
|
||||
const readOnly = !!workflow.team?.members?.find(
|
||||
(member) => member.userId === userId && member.role === "MEMBER"
|
||||
(member) => member.userId === userId && member.role === MembershipRole.MEMBER
|
||||
);
|
||||
|
||||
return { readOnly, isOrg: workflow.team?.isOrganization ?? false, ...workflow };
|
||||
@@ -383,6 +386,40 @@ export class WorkflowRepository {
|
||||
return remindersToDelete;
|
||||
}
|
||||
|
||||
static async getActiveOnEventTypeIds({
|
||||
workflowId,
|
||||
userId,
|
||||
teamId,
|
||||
}: {
|
||||
workflowId: number;
|
||||
userId: number;
|
||||
teamId?: number | null;
|
||||
}) {
|
||||
const workflow = await prisma.workflow.findFirst({
|
||||
where: {
|
||||
id: workflowId,
|
||||
userId,
|
||||
teamId: teamId ?? undefined,
|
||||
},
|
||||
select: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventTypeId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!workflow) {
|
||||
throw new HttpError({
|
||||
statusCode: 404,
|
||||
message: "Workflow not found",
|
||||
});
|
||||
}
|
||||
|
||||
return workflow.activeOn.map((active) => active.eventTypeId);
|
||||
}
|
||||
|
||||
static async deleteAllWorkflowReminders(
|
||||
remindersToDelete:
|
||||
| {
|
||||
@@ -398,6 +435,7 @@ export class WorkflowRepository {
|
||||
[WorkflowMethods.EMAIL]: (id, referenceId) => deleteScheduledEmailReminder(id),
|
||||
[WorkflowMethods.SMS]: (id, referenceId) => deleteScheduledSMSReminder(id, referenceId),
|
||||
[WorkflowMethods.WHATSAPP]: (id, referenceId) => deleteScheduledWhatsappReminder(id, referenceId),
|
||||
[WorkflowMethods.AI_PHONE_CALL]: (id, referenceId) => deleteScheduledAIPhoneCall(id, referenceId),
|
||||
};
|
||||
|
||||
if (!remindersToDelete) return Promise.resolve();
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
INSERT INTO
|
||||
"Feature" (slug, enabled, description, "type")
|
||||
VALUES
|
||||
(
|
||||
'cal-ai-voice-agents',
|
||||
false,
|
||||
'Enable Cal AI Voice Agents - Allow AI-powered voice agents to make phone calls.',
|
||||
'OPERATIONAL'
|
||||
) ON CONFLICT (slug) DO NOTHING;
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- A unique constraint covering the columns `[externalRef]` on the table `CreditExpenseLog` will be added. If there are existing duplicate values, this will fail.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "CreditExpenseLog" ADD COLUMN "callDuration" INTEGER,
|
||||
ADD COLUMN "externalRef" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "CreditExpenseLog_externalRef_key" ON "CreditExpenseLog"("externalRef");
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CreditUsageType" AS ENUM ('SMS', 'CAL_AI_PHONE_CALL');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "CreditExpenseLog" ADD COLUMN "creditFor" "CreditUsageType";
|
||||
|
||||
-- Add check constraint for CAL_AI_PHONE_CALL requiring callDuration
|
||||
ALTER TABLE "CreditExpenseLog" ADD CONSTRAINT "CreditExpenseLog_cal_ai_phone_call_duration_required"
|
||||
CHECK ("creditFor" != 'CAL_AI_PHONE_CALL' OR "callDuration" IS NOT NULL);
|
||||
@@ -599,6 +599,11 @@ model CreditPurchaseLog {
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
enum CreditUsageType {
|
||||
SMS
|
||||
CAL_AI_PHONE_CALL
|
||||
}
|
||||
|
||||
model CreditExpenseLog {
|
||||
id String @id @default(uuid())
|
||||
creditBalanceId String
|
||||
@@ -610,6 +615,9 @@ model CreditExpenseLog {
|
||||
date DateTime
|
||||
smsSid String?
|
||||
smsSegments Int?
|
||||
callDuration Int?
|
||||
creditFor CreditUsageType?
|
||||
externalRef String? @unique
|
||||
}
|
||||
|
||||
enum CreditType {
|
||||
|
||||
@@ -40,5 +40,7 @@ export const ENDPOINTS = [
|
||||
"routingForms",
|
||||
"credits",
|
||||
"filterSegments",
|
||||
"aiVoiceAgent",
|
||||
"phoneNumber",
|
||||
"pbac",
|
||||
] as const;
|
||||
@@ -9,6 +9,7 @@ import { loggedInViewerRouter } from "../loggedInViewer/_router";
|
||||
import { publicViewerRouter } from "../publicViewer/_router";
|
||||
import { timezonesRouter } from "../publicViewer/timezones/_router";
|
||||
import { adminRouter } from "./admin/_router";
|
||||
import { aiVoiceAgentRouter } from "./aiVoiceAgent/_router";
|
||||
import { apiKeysRouter } from "./apiKeys/_router";
|
||||
import { appsRouter } from "./apps/_router";
|
||||
import { attributesRouter } from "./attributes/_router";
|
||||
@@ -32,6 +33,7 @@ import { oooRouter } from "./ooo/_router";
|
||||
import { viewerOrganizationsRouter } from "./organizations/_router";
|
||||
import { paymentsRouter } from "./payments/_router";
|
||||
import { permissionsRouter } from "./pbac/_router";
|
||||
import { phoneNumberRouter } from "./phoneNumber/_router";
|
||||
import { routingFormsRouter } from "./routing-forms/_router";
|
||||
import { slotsRouter } from "./slots/_router";
|
||||
import { ssoRouter } from "./sso/_router";
|
||||
@@ -82,4 +84,6 @@ export const viewerRouter = router({
|
||||
credits: creditsRouter,
|
||||
ooo: oooRouter,
|
||||
travelSchedules: travelSchedulesRouter,
|
||||
aiVoiceAgent: aiVoiceAgentRouter,
|
||||
phoneNumber: phoneNumberRouter,
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZCreateInputSchema } from "./create.schema";
|
||||
import { ZDeleteInputSchema } from "./delete.schema";
|
||||
import { ZGetInputSchema } from "./get.schema";
|
||||
import { ZListInputSchema } from "./list.schema";
|
||||
import { ZTestCallInputSchema } from "./testCall.schema";
|
||||
import { ZUpdateInputSchema } from "./update.schema";
|
||||
|
||||
export const aiVoiceAgentRouter = router({
|
||||
list: authedProcedure.input(ZListInputSchema).query(async ({ ctx, input }) => {
|
||||
const { listHandler } = await import("./list.handler");
|
||||
|
||||
return listHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
get: authedProcedure.input(ZGetInputSchema).query(async ({ ctx, input }) => {
|
||||
const { getHandler } = await import("./get.handler");
|
||||
|
||||
return getHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
create: authedProcedure.input(ZCreateInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { createHandler } = await import("./create.handler");
|
||||
|
||||
return createHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
update: authedProcedure.input(ZUpdateInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { updateHandler } = await import("./update.handler");
|
||||
|
||||
return updateHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
delete: authedProcedure.input(ZDeleteInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { deleteHandler } = await import("./delete.handler");
|
||||
|
||||
return deleteHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
testCall: authedProcedure.input(ZTestCallInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { testCallHandler } = await import("./testCall.handler");
|
||||
|
||||
return testCallHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
|
||||
import type { RetellLLMGeneralTools } from "@calcom/features/calAIPhone/providers/retellAI/types";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TCreateInputSchema } from "./create.schema";
|
||||
|
||||
type CreateHandlerOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TCreateInputSchema;
|
||||
};
|
||||
|
||||
export const createHandler = async ({ ctx, input }: CreateHandlerOptions) => {
|
||||
const { teamId, name, workflowStepId, ...retellConfig } = input;
|
||||
|
||||
const aiService = createDefaultAIPhoneServiceProvider();
|
||||
|
||||
return await aiService.createAgent({
|
||||
name,
|
||||
userId: ctx.user.id,
|
||||
teamId,
|
||||
workflowStepId,
|
||||
generalPrompt: retellConfig.generalPrompt,
|
||||
beginMessage: retellConfig.beginMessage,
|
||||
generalTools: retellConfig.generalTools as RetellLLMGeneralTools,
|
||||
userTimeZone: ctx.user.timeZone,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZCreateInputSchema = z.object({
|
||||
name: z.string().optional(),
|
||||
teamId: z.number().optional(),
|
||||
workflowStepId: z.number().optional(),
|
||||
generalPrompt: z.string().optional(),
|
||||
beginMessage: z.string().optional(),
|
||||
generalTools: z
|
||||
.array(
|
||||
z.object({
|
||||
type: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().optional(),
|
||||
cal_api_key: z.string().optional(),
|
||||
event_type_id: z.number().optional(),
|
||||
timezone: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
voiceId: z.string().optional().default("11labs-Adrian"),
|
||||
});
|
||||
|
||||
export type TCreateInputSchema = z.infer<typeof ZCreateInputSchema>;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TDeleteInputSchema } from "./delete.schema";
|
||||
|
||||
type DeleteHandlerOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TDeleteInputSchema;
|
||||
};
|
||||
|
||||
export const deleteHandler = async ({ ctx, input }: DeleteHandlerOptions) => {
|
||||
const aiService = createDefaultAIPhoneServiceProvider();
|
||||
|
||||
return await aiService.deleteAgent({
|
||||
id: input.id,
|
||||
userId: ctx.user.id,
|
||||
teamId: input.teamId,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZDeleteInputSchema = z.object({
|
||||
id: z.string(),
|
||||
teamId: z.number().optional(),
|
||||
});
|
||||
|
||||
export type TDeleteInputSchema = z.infer<typeof ZDeleteInputSchema>;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TGetInputSchema } from "./get.schema";
|
||||
|
||||
type GetHandlerOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TGetInputSchema;
|
||||
};
|
||||
|
||||
export const getHandler = async ({ ctx, input }: GetHandlerOptions) => {
|
||||
const aiService = createDefaultAIPhoneServiceProvider();
|
||||
|
||||
return await aiService.getAgentWithDetails({
|
||||
id: input.id,
|
||||
userId: ctx.user.id,
|
||||
teamId: input.teamId,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZGetInputSchema = z.object({
|
||||
id: z.string(),
|
||||
teamId: z.number().optional(),
|
||||
});
|
||||
|
||||
export type TGetInputSchema = z.infer<typeof ZGetInputSchema>;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TListInputSchema } from "./list.schema";
|
||||
|
||||
type ListHandlerOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TListInputSchema;
|
||||
};
|
||||
|
||||
export const listHandler = async ({ ctx, input }: ListHandlerOptions) => {
|
||||
const aiService = createDefaultAIPhoneServiceProvider();
|
||||
|
||||
return await aiService.listAgents({
|
||||
userId: ctx.user.id,
|
||||
teamId: input?.teamId,
|
||||
scope: input?.scope ?? "all",
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZListInputSchema = z
|
||||
.object({
|
||||
teamId: z.number().optional(),
|
||||
scope: z.enum(["personal", "team", "all"]).optional().default("all"),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export type TListInputSchema = z.infer<typeof ZListInputSchema>;
|
||||
@@ -0,0 +1,68 @@
|
||||
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { PrismaAgentRepository } from "@calcom/lib/server/repository/PrismaAgentRepository";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TTestCallInputSchema } from "./testCall.schema";
|
||||
|
||||
type TestCallHandlerOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TTestCallInputSchema;
|
||||
};
|
||||
|
||||
export const testCallHandler = async ({ ctx, input }: TestCallHandlerOptions) => {
|
||||
const timeZone = ctx.user.timeZone ?? "Europe/London";
|
||||
const eventTypeId = input.eventTypeId;
|
||||
|
||||
const featuresRepository = new FeaturesRepository(prisma);
|
||||
const calAIVoiceAgents = await featuresRepository.checkIfFeatureIsEnabledGlobally("cal-ai-voice-agents");
|
||||
if (!calAIVoiceAgents) {
|
||||
logger.warn("Cal AI voice agents are disabled - skipping AI phone call scheduling");
|
||||
return;
|
||||
}
|
||||
|
||||
const agent = await PrismaAgentRepository.findByIdWithCallAccess({
|
||||
id: input.agentId,
|
||||
userId: ctx.user.id,
|
||||
});
|
||||
|
||||
if (!agent?.providerAgentId) {
|
||||
logger.error(`Agent not found with agentId ${input.agentId}`);
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Agent not found",
|
||||
});
|
||||
}
|
||||
|
||||
const aiService = createDefaultAIPhoneServiceProvider();
|
||||
|
||||
try {
|
||||
await aiService.updateToolsFromAgentId(agent.providerAgentId, {
|
||||
eventTypeId,
|
||||
timeZone,
|
||||
userId: ctx.user.id,
|
||||
teamId: input.teamId,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(`Failed to update tools for agent ${agent.providerAgentId}: ${error}`);
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You are not authorized to test the event type. Failed to update tools for agent",
|
||||
});
|
||||
}
|
||||
|
||||
return await aiService.createTestCall({
|
||||
agentId: input.agentId,
|
||||
phoneNumber: input.phoneNumber,
|
||||
userId: ctx.user.id,
|
||||
teamId: input.teamId,
|
||||
timeZone,
|
||||
eventTypeId,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZTestCallInputSchema = z.object({
|
||||
agentId: z.string(),
|
||||
phoneNumber: z.string().optional(),
|
||||
teamId: z.number().optional(),
|
||||
eventTypeId: z.number(),
|
||||
});
|
||||
|
||||
export type TTestCallInputSchema = z.infer<typeof ZTestCallInputSchema>;
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
|
||||
import type { RetellLLMGeneralTools } from "@calcom/features/calAIPhone/providers/retellAI/types";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TUpdateInputSchema } from "./update.schema";
|
||||
|
||||
type UpdateHandlerOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TUpdateInputSchema;
|
||||
};
|
||||
|
||||
export const updateHandler = async ({ ctx, input }: UpdateHandlerOptions) => {
|
||||
const { id, teamId, name, enabled, ...retellUpdates } = input;
|
||||
|
||||
const aiService = createDefaultAIPhoneServiceProvider();
|
||||
|
||||
return await aiService.updateAgentConfiguration({
|
||||
id,
|
||||
userId: ctx.user.id,
|
||||
teamId,
|
||||
name,
|
||||
generalPrompt: retellUpdates.generalPrompt ?? undefined,
|
||||
beginMessage: retellUpdates.beginMessage ?? undefined,
|
||||
generalTools: retellUpdates.generalTools as RetellLLMGeneralTools,
|
||||
voiceId: retellUpdates.voiceId,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZUpdateInputSchema = z.object({
|
||||
id: z.string(),
|
||||
teamId: z.number().optional(),
|
||||
name: z.string().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
generalPrompt: z.string().nullish().default(null),
|
||||
beginMessage: z.string().nullish().default(null),
|
||||
generalTools: z
|
||||
.array(
|
||||
z.object({
|
||||
type: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().nullish().default(null),
|
||||
cal_api_key: z.string().nullish().default(null),
|
||||
event_type_id: z.number().nullish().default(null),
|
||||
timezone: z.string().nullish().default(null),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
voiceId: z.string().optional(),
|
||||
});
|
||||
|
||||
export type TUpdateInputSchema = z.infer<typeof ZUpdateInputSchema>;
|
||||
@@ -1,6 +1,8 @@
|
||||
import { StripeBillingService } from "@calcom/features/ee/billing/stripe-billling-service";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
@@ -43,17 +45,27 @@ export const buyCreditsHandler = async ({ ctx, input }: BuyCreditsOptions) => {
|
||||
}
|
||||
}
|
||||
|
||||
const redirect_uri = teamId
|
||||
? `${WEBAPP_URL}/settings/teams/${teamId}/billing`
|
||||
: `${WEBAPP_URL}/settings/billing`;
|
||||
let redirectUrl = `${WEBAPP_URL}/settings/billing`;
|
||||
|
||||
if (teamId) {
|
||||
// Check if the team is an organization
|
||||
const teamRepository = new TeamRepository(prisma);
|
||||
const team = await teamRepository.findById({ id: teamId });
|
||||
|
||||
if (team?.isOrganization) {
|
||||
redirectUrl = `${WEBAPP_URL}/settings/organizations/billing`;
|
||||
} else {
|
||||
redirectUrl = `${WEBAPP_URL}/settings/teams/${teamId}/billing`;
|
||||
}
|
||||
}
|
||||
|
||||
const billingService = new StripeBillingService();
|
||||
|
||||
const { checkoutUrl } = await billingService.createOneTimeCheckout({
|
||||
priceId: process.env.NEXT_PUBLIC_STRIPE_CREDITS_PRICE_ID,
|
||||
quantity,
|
||||
successUrl: redirect_uri,
|
||||
cancelUrl: redirect_uri,
|
||||
successUrl: redirectUrl,
|
||||
cancelUrl: redirectUrl,
|
||||
metadata: {
|
||||
...(teamId && { teamId: teamId.toString() }),
|
||||
userId: ctx.user.id.toString(),
|
||||
|
||||
@@ -12,7 +12,15 @@ type DownloadExpenseLogOptions = {
|
||||
input: TDownloadExpenseLogSchema;
|
||||
};
|
||||
|
||||
const headers = ["Date", "Credits", "Type", "Booking UID", "Number of Segments"];
|
||||
const headers = [
|
||||
"Date",
|
||||
"Credits",
|
||||
"Type",
|
||||
"Booking UID",
|
||||
"Number of Segments",
|
||||
"Call Duration",
|
||||
"External Ref",
|
||||
];
|
||||
|
||||
export const downloadExpenseLogHandler = async ({ ctx, input }: DownloadExpenseLogOptions) => {
|
||||
const { teamId, startDate, endDate } = input;
|
||||
@@ -44,6 +52,8 @@ export const downloadExpenseLogHandler = async ({ ctx, input }: DownloadExpenseL
|
||||
log.creditType,
|
||||
log.bookingUid ?? "",
|
||||
log.smsSegments?.toString() ?? "-",
|
||||
log.callDuration?.toString() ?? "-",
|
||||
log.externalRef ?? "-",
|
||||
]);
|
||||
|
||||
const csvData = [headers, ...rows].map((row) => row.join(",")).join("\n");
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZBuyInputSchema } from "./buy.schema";
|
||||
import { ZCancelInputSchema } from "./cancel.schema";
|
||||
import { ZDeleteInputSchema } from "./delete.schema";
|
||||
import { ZImportInputSchema } from "./import.schema";
|
||||
import { ZListInputSchema } from "./list.schema";
|
||||
import { ZUpdateInputSchema } from "./update.schema";
|
||||
|
||||
export const phoneNumberRouter = router({
|
||||
list: authedProcedure.input(ZListInputSchema).query(async ({ ctx, input }) => {
|
||||
const { listHandler } = await import("./list.handler");
|
||||
|
||||
return listHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
buy: authedProcedure.input(ZBuyInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { buyHandler } = await import("./buy.handler");
|
||||
|
||||
return buyHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
import: authedProcedure.input(ZImportInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { importHandler } = await import("./import.handler");
|
||||
|
||||
return importHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
cancel: authedProcedure.input(ZCancelInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { cancelHandler } = await import("./cancel.handler");
|
||||
|
||||
return cancelHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
delete: authedProcedure.input(ZDeleteInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { deleteHandler } = await import("./delete.handler");
|
||||
|
||||
return deleteHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
update: authedProcedure.input(ZUpdateInputSchema).mutation(async ({ ctx, input }) => {
|
||||
const { updateHandler } = await import("./update.handler");
|
||||
|
||||
return updateHandler({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TBuyInputSchema } from "./buy.schema";
|
||||
|
||||
type BuyHandlerOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TBuyInputSchema;
|
||||
};
|
||||
|
||||
export const buyHandler = async ({ ctx, input }: BuyHandlerOptions) => {
|
||||
const userId = ctx.user.id;
|
||||
const aiService = createDefaultAIPhoneServiceProvider();
|
||||
|
||||
const checkoutSession = await aiService.generatePhoneNumberCheckoutSession({
|
||||
userId,
|
||||
teamId: input?.teamId ?? undefined,
|
||||
agentId: input.agentId,
|
||||
workflowId: input.workflowId,
|
||||
});
|
||||
|
||||
if (checkoutSession) {
|
||||
return {
|
||||
checkoutUrl: checkoutSession.url,
|
||||
message: checkoutSession.message,
|
||||
phoneNumber: null,
|
||||
};
|
||||
}
|
||||
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Phone number billing is required but not configured.",
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZBuyInputSchema = z.object({
|
||||
teamId: z.number().optional(),
|
||||
agentId: z.string(),
|
||||
workflowId: z.string(),
|
||||
});
|
||||
|
||||
export type TBuyInputSchema = z.infer<typeof ZBuyInputSchema>;
|
||||
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user