fix: cal ai webhook (#24368)

* fix: cal ai email

* fix: remove

* fix: org

* replace Cal AI with Cal.ai

* fix: use

* fix: feedback

* fix: types

* fix: types

* fix: types

* fix: tests

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

* refactor: feedback

* refactor: imporvement

* fix: type

* refactor: feedback

* fix: tests

* fix: use pbac

---------

Co-authored-by: CarinaWolli <[email protected]>
This commit is contained in:
Udit TakkarandCarinaWolli authored and GitHub committed 2025-11-05 13:31:55 +04:00
1 parent 7f48c7fdad
commit 2df2868b20
23 files changed
+589 -74

No files matched your search

@@ -130,7 +130,7 @@ const Page = async ({ searchParams }: PageProps) => {
throw error;
}
console.error("Failed to create Cal AI workflow:", error);
console.error("Failed to create Cal.ai workflow:", error);
redirect("/workflows?error=failed-to-create-workflow");
}
};
@@ -3,6 +3,7 @@ import { Retell } from "retell-sdk";
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { CalAiPhoneNumber, User, Team, Agent } from "@calcom/prisma/client";
import { CreditUsageType } from "@calcom/prisma/enums";
import { POST } from "../route";
@@ -71,6 +72,8 @@ vi.mock("retell-sdk", () => ({
const mockHasAvailableCredits = vi.fn();
const mockChargeCredits = vi.fn();
const mockSendCreditBalanceLimitReachedEmails = vi.fn();
const mockSendCreditBalanceLowWarningEmails = vi.fn();
vi.mock("@calcom/features/ee/billing/credit-service", () => ({
CreditService: vi.fn().mockImplementation(() => ({
@@ -79,6 +82,12 @@ vi.mock("@calcom/features/ee/billing/credit-service", () => ({
})),
}));
vi.mock("@calcom/emails/email-manager", () => ({
sendCreditBalanceLimitReachedEmails: (...args: unknown[]) =>
mockSendCreditBalanceLimitReachedEmails(...args),
sendCreditBalanceLowWarningEmails: (...args: unknown[]) => mockSendCreditBalanceLowWarningEmails(...args),
}));
const mockFindByPhoneNumber = vi.fn();
const mockFindByProviderAgentId = vi.fn();
@@ -231,6 +240,7 @@ describe("Retell AI Webhook Handler", () => {
credits: 58, // 120 seconds = 2 minutes * $0.29 = $0.58 = 58 credits
callDuration: 120,
externalRef: "retell:test-call-id",
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
})
);
});
@@ -288,6 +298,7 @@ describe("Retell AI Webhook Handler", () => {
credits: 87, // 180 seconds = 3 minutes * $0.29 = $0.87 = 87 credits
callDuration: 180,
externalRef: "retell:test-call-id",
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
})
);
});
@@ -471,6 +482,7 @@ describe("Retell AI Webhook Handler", () => {
credits: expectedCredits,
callDuration: durationSeconds,
externalRef: expect.stringMatching(/^retell:test-call-/),
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
})
);
}
@@ -517,7 +529,12 @@ describe("Retell AI Webhook Handler", () => {
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)
expect.objectContaining({
userId: 42,
credits: 61,
callDuration: 125,
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
}) // 125s = 2.083 minutes * $0.29 = $0.604 = 61 credits (rounded up)
);
});
@@ -574,6 +591,7 @@ describe("Retell AI Webhook Handler", () => {
credits: 29, // 60 seconds = 1 minute * $0.29 = $0.29 = 29 credits
callDuration: 60,
externalRef: "retell:test-idempotency-call",
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
})
);
});
@@ -760,6 +778,7 @@ describe("Retell AI Webhook Handler", () => {
credits: 4, // 7 seconds = 0.117 minutes * $0.29 = $0.034 = 4 credits (rounded up)
callDuration: 7,
externalRef: "retell:call_bcd94f5a50832873a5fd68cb1aa",
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
})
);
});
@@ -794,6 +813,7 @@ describe("Retell AI Webhook Handler", () => {
teamId: 10,
credits: 29, // 60 seconds = 1 minute * $0.29 = 29 credits
callDuration: 60,
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
})
);
});
+5 -3
View File
@@ -63,6 +63,8 @@ const RetellWebhookSchema = z.object({
.passthrough(),
});
type RetellCallData = z.infer<typeof RetellWebhookSchema>["call"];
async function chargeCreditsForCall({
userId,
teamId,
@@ -120,7 +122,7 @@ async function chargeCreditsForCall({
}
}
async function handleCallAnalyzed(callData: any) {
async function handleCallAnalyzed(callData: RetellCallData) {
const { from_number, call_id, call_cost, call_type, agent_id } = callData;
if (
@@ -165,7 +167,7 @@ async function handleCallAnalyzed(callData: any) {
}
userId = agent.userId ?? undefined;
teamId = agent.teamId ?? undefined;
teamId = agent.team?.parentId ?? agent.teamId ?? undefined;
log.info(`Processing web call ${call_id} for agent ${agent_id}, user ${userId}, team ${teamId}`);
} else {
@@ -181,7 +183,7 @@ async function handleCallAnalyzed(callData: any) {
}
userId = phoneNumber.userId ?? undefined;
teamId = phoneNumber.teamId ?? undefined;
teamId = phoneNumber.team?.parentId ?? phoneNumber.teamId ?? undefined;
log.info(`Processing phone call ${call_id} from ${from_number}, user ${userId}, team ${teamId}`);
}
@@ -3490,6 +3490,10 @@
"low_credits_warning_message_user": "Your Cal.com account is running low on credits. To avoid any disruption in service, please purchase additional credits. If your balance runs out, SMS messages will stop sending and will be sent as emails instead.",
"credit_limit_reached_message": "Your Cal.com team {{teamName}} has run out of credits. As a result, SMS messages are now being sent via email instead. To resume sending SMS, please purchase additional credits.",
"credit_limit_reached_message_user": "Your Cal.com account has run out of credits. As a result, SMS messages are now being sent via email instead. To resume sending SMS, please purchase additional credits.",
"cal_ai_low_credits_warning_message": "Your Cal.com team {{teamName}} is running low on credits. To avoid any disruption in Cal.ai phone service, please purchase additional credits. If your balance runs out, Cal.ai phone calls will be disabled.",
"cal_ai_low_credits_warning_message_user": "Your Cal.com account is running low on credits. To avoid any disruption in Cal.ai phone service, please purchase additional credits. If your balance runs out, Cal.ai phone calls will be disabled.",
"cal_ai_credit_limit_reached_message": "Your Cal.com team {{teamName}} has run out of credits. As a result, Cal.ai phone calls are now disabled. To resume using Cal.ai phone calls, please purchase additional credits.",
"cal_ai_credit_limit_reached_message_user": "Your Cal.com account has run out of credits. As a result, Cal.ai phone calls are now disabled. To resume using Cal.ai phone calls, please purchase additional credits.",
"current_credit_balance": "Current balance: {{balance}} credits",
"current_balance": "Current balance:",
"notification_about_your_booking": "Notification about your booking",