refactor: Cal.diy (#28903)
* feat: Cal.diy — community-driven MIT-licensed fork of Cal.com This squashed commit contains all Cal.diy changes applied on top of calcom/cal.com main: - Rebrand Cal.com to Cal.diy across the entire codebase - Remove Enterprise Edition (EE) features, license checks, and AGPL restrictions - Switch license from AGPL-3.0 to MIT - Remove docs/ directory (migrated to Nextra at cal.diy) - Remove dead code: org tests, EE tips, platform nav, premium username, SAML/SSO, etc. - Clean up .env.example for self-hosted Cal.diy - Update Docker image references to calcom/cal.diy - Update README, CONTRIBUTING.md, and issue templates for Cal.diy community fork - Add PR welcome bot for Cal.diy contributors - Fix API v2 breaking changes oasdiff ignore entries - Replace Blacksmith CI runners with default GitHub Actions 3893 files changed, 20789 insertions(+), 411020 deletions(-) Co-Authored-By: [email protected] <[email protected]> * refactor: remove org-specific /organizations/:orgId endpoints from API v2 atoms controllers (#1701) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: revert Cal.diy Inc to Cal.com, Inc. in license files, copyright notices, and package metadata (#1702) Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * rip out org related comments in api v2 --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
a17f28e9ab
commit
ab21c7f805
4080 files changed
+14403
-404922
No files matched your search
@@ -1,41 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import jackson from "@calcom/features/ee/sso/lib/jackson";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
|
||||
// This is the callback endpoint for the OIDC provider
|
||||
// A team must set this endpoint in the OIDC provider's configuration
|
||||
async function handler(req: NextRequest) {
|
||||
const log = logger.getSubLogger({ prefix: ["[OIDC auth]"] });
|
||||
const { searchParams } = req.nextUrl;
|
||||
const params = Object.fromEntries(searchParams.entries());
|
||||
|
||||
if (!params.code || !params.state) {
|
||||
return NextResponse.json({ message: "Code and state are required" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { oauthController } = await jackson();
|
||||
|
||||
try {
|
||||
const { redirect_url } = await oauthController.oidcAuthzResponse(params);
|
||||
|
||||
if (!redirect_url) {
|
||||
throw new HttpError({
|
||||
message: "No redirect URL found",
|
||||
statusCode: 500,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.redirect(redirect_url, 302);
|
||||
} catch (err) {
|
||||
log.error(`Error authorizing tenant ${params.tenant}: ${err}`);
|
||||
const { message, statusCode = 500 } = err as HttpError;
|
||||
|
||||
return NextResponse.json({ message }, { status: statusCode });
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(handler);
|
||||
@@ -1,30 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import type { OAuthReq } from "@calcom/features/ee/sso/lib/jackson";
|
||||
import jackson from "@calcom/features/ee/sso/lib/jackson";
|
||||
import type { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
|
||||
async function handler(req: NextRequest) {
|
||||
const log = logger.getSubLogger({ prefix: ["[SAML authorize]"] });
|
||||
const { oauthController } = await jackson();
|
||||
|
||||
const oAuthReq = Object.fromEntries(req.nextUrl.searchParams) as unknown as OAuthReq;
|
||||
|
||||
try {
|
||||
const { redirect_url } = await oauthController.authorize(oAuthReq);
|
||||
|
||||
return NextResponse.redirect(redirect_url as string, 302);
|
||||
} catch (err) {
|
||||
log.error(`Error initaiting SAML login for tenant ${oAuthReq?.tenant}: ${err}`);
|
||||
const { message, statusCode = 500 } = err as HttpError;
|
||||
|
||||
return NextResponse.json({ message }, { status: statusCode });
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(handler);
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -1,38 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { parseRequestData } from "app/api/parseRequestData";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { uuid } from "short-uuid";
|
||||
|
||||
import jackson from "@calcom/features/ee/sso/lib/jackson";
|
||||
import type { SAMLResponsePayload } from "@calcom/features/ee/sso/lib/jackson";
|
||||
import logger from "@calcom/lib/logger";
|
||||
|
||||
async function handler(req: NextRequest) {
|
||||
const uid = uuid();
|
||||
const log = logger.getSubLogger({ prefix: ["[SAML callback]", `trace: ${uid}`] });
|
||||
const { oauthController } = await jackson();
|
||||
|
||||
const requestData = (await parseRequestData(req)) as SAMLResponsePayload;
|
||||
|
||||
try {
|
||||
const { redirect_url, error } = await oauthController.samlResponse(requestData);
|
||||
|
||||
if (redirect_url) {
|
||||
return NextResponse.redirect(redirect_url, 302);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
const uid = uuid();
|
||||
log.error(`Error authenticating user with error ${error} for relayState ${requestData?.RelayState}`);
|
||||
return NextResponse.json({ message: `Error authorizing user. trace: ${uid}` }, { status: 400 });
|
||||
}
|
||||
} catch (error) {
|
||||
log.error(`Error processing SAML response`, error);
|
||||
return NextResponse.json({ message: `Error processing SAML response. trace: ${uid}` }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "No redirect URL provided" }, { status: 400 });
|
||||
}
|
||||
|
||||
export const POST = defaultResponderForAppDir(handler);
|
||||
@@ -1,33 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { parseRequestData } from "app/api/parseRequestData";
|
||||
import * as jose from "jose";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import * as dummy from "openid-client";
|
||||
import { uuid } from "short-uuid";
|
||||
|
||||
import jackson from "@calcom/features/ee/sso/lib/jackson";
|
||||
import type { OAuthTokenReq } from "@calcom/features/ee/sso/lib/jackson";
|
||||
import logger from "@calcom/lib/logger";
|
||||
|
||||
async function handler(req: NextRequest) {
|
||||
// Need these imports to fix import errors with jackson
|
||||
// https://github.com/ory/polis/blob/main/pages/api/import-hack.ts
|
||||
const unused = dummy; // eslint-disable-line @typescript-eslint/no-unused-vars
|
||||
const unused2 = jose; // eslint-disable-line @typescript-eslint/no-unused-vars
|
||||
const { oauthController } = await jackson();
|
||||
const log = logger.getSubLogger({ prefix: ["[SAML token]"] });
|
||||
|
||||
const oauthTokenReq = (await parseRequestData(req)) as OAuthTokenReq;
|
||||
|
||||
try {
|
||||
const tokenResponse = await oauthController.token(oauthTokenReq);
|
||||
return NextResponse.json(tokenResponse);
|
||||
} catch (error) {
|
||||
const uid = uuid();
|
||||
log.error(`Error getting auth token for client id ${oauthTokenReq?.client_id}: ${error} trace: ${uid}`);
|
||||
throw new Error(`Error getting auth token with error ${error} trace: ${uid}`);
|
||||
}
|
||||
}
|
||||
|
||||
export const POST = defaultResponderForAppDir(handler);
|
||||
@@ -1,54 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { uuid } from "short-uuid";
|
||||
import { z } from "zod";
|
||||
|
||||
import jackson from "@calcom/features/ee/sso/lib/jackson";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
|
||||
const extractAuthToken = (req: NextRequest) => {
|
||||
const log = logger.getSubLogger({ prefix: ["SAML extractAuthToken"] });
|
||||
const uid = uuid();
|
||||
const authHeader = req.headers.get("authorization");
|
||||
const parts = (authHeader || "").split(" ");
|
||||
if (parts.length > 1) return parts[1];
|
||||
|
||||
// check for query param
|
||||
let arr: string[] = [];
|
||||
const tokenParse = requestQuery.safeParse(Object.fromEntries(req.nextUrl.searchParams));
|
||||
let access_token;
|
||||
if (!tokenParse.success) {
|
||||
log.error(`Error parsing request query: ${tokenParse.error} trace ${uid}`);
|
||||
throw new HttpError({ statusCode: 401, message: `Unauthorized trace: ${uid}` });
|
||||
}
|
||||
access_token = tokenParse.data.access_token;
|
||||
arr = arr.concat(access_token);
|
||||
if (arr[0].length > 0) return arr[0];
|
||||
|
||||
throw new HttpError({ statusCode: 401, message: `Unauthorized trace: ${uid}` });
|
||||
};
|
||||
|
||||
const requestQuery = z.object({
|
||||
access_token: z.string(),
|
||||
});
|
||||
|
||||
async function handler(req: NextRequest) {
|
||||
const log = logger.getSubLogger({ prefix: ["SAML userinfo"] });
|
||||
const { oauthController } = await jackson();
|
||||
const token = extractAuthToken(req);
|
||||
|
||||
try {
|
||||
const userInfo = await oauthController.userInfo(token);
|
||||
return NextResponse.json(userInfo);
|
||||
} catch (error) {
|
||||
const uid = uuid();
|
||||
log.error(`trace: ${uid} Error getting user info from token: ${error}`);
|
||||
throw new Error(`Error getting user info from token. trace: ${uid}`);
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(handler);
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -66,11 +66,6 @@ vi.mock("@calcom/features/auth/signup/utils/prefillAvatar", () => ({ prefillAvat
|
||||
vi.mock("@calcom/features/auth/signup/utils/validateUsername", () => ({
|
||||
validateAndGetCorrectedUsernameAndEmail: vi.fn().mockResolvedValue({ isValid: true, username: "testuser" }),
|
||||
}));
|
||||
vi.mock("@calcom/features/ee/billing/di/containers/Billing", () => ({
|
||||
getBillingProviderService: vi.fn().mockReturnValue({
|
||||
createCustomer: vi.fn().mockResolvedValue({ stripeCustomerId: "cus_123" }),
|
||||
}),
|
||||
}));
|
||||
vi.mock("@calcom/features/watchlist/lib/telemetry", () => ({ sentrySpan: {} }));
|
||||
vi.mock("@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller", () => ({
|
||||
checkIfEmailIsBlockedInWatchlistController: vi.fn().mockResolvedValue(false),
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
} from "@calcom/features/auth/signup/utils/token";
|
||||
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/features/auth/signup/utils/validateUsername";
|
||||
import { getFeatureRepository } from "@calcom/features/di/containers/FeatureRepository";
|
||||
import { getBillingProviderService } from "@calcom/features/ee/billing/di/containers/Billing";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { GlobalWatchlistRepository } from "@calcom/features/watchlist/lib/repository/GlobalWatchlistRepository";
|
||||
import { sentrySpan } from "@calcom/features/watchlist/lib/telemetry";
|
||||
@@ -42,6 +41,17 @@ import { NextResponse } from "next/server";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["signupCalcomHandler"] });
|
||||
|
||||
const billingService = {
|
||||
async createCustomer(_args: Record<string, unknown>): Promise<{ stripeCustomerId: string }> {
|
||||
return { stripeCustomerId: "" };
|
||||
},
|
||||
async createSubscriptionCheckout(
|
||||
_args: Record<string, unknown>
|
||||
): Promise<{ sessionId: string }> {
|
||||
return { sessionId: "" };
|
||||
},
|
||||
};
|
||||
|
||||
const handler: CustomNextApiHandler = async (body, usernameStatus, query) => {
|
||||
const {
|
||||
email: _email,
|
||||
@@ -55,8 +65,6 @@ const handler: CustomNextApiHandler = async (body, usernameStatus, query) => {
|
||||
})
|
||||
.parse(body);
|
||||
|
||||
const billingService = getBillingProviderService();
|
||||
|
||||
const shouldLockByDefault = await checkIfEmailIsBlockedInWatchlistController({
|
||||
email: _email,
|
||||
organizationId: null,
|
||||
@@ -169,7 +177,7 @@ const handler: CustomNextApiHandler = async (body, usernameStatus, query) => {
|
||||
// Hash the password
|
||||
const hashedPassword = await hashPassword(password);
|
||||
|
||||
if (foundToken && foundToken?.teamId) {
|
||||
if (foundToken?.teamId) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: foundToken.teamId,
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { checkPremiumUsername } from "@calcom/ee/common/lib/checkPremiumUsername";
|
||||
import process from "node:process";
|
||||
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import { SIGNUP_ERROR_CODES } from "@calcom/features/auth/signup/constants";
|
||||
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
|
||||
import { joinAnyChildTeamOnOrgInvite } from "@calcom/features/auth/signup/utils/organization";
|
||||
import { prefillAvatar } from "@calcom/features/auth/signup/utils/prefillAvatar";
|
||||
import {
|
||||
findTokenByToken,
|
||||
throwIfTokenExpired,
|
||||
validateAndGetCorrectedUsernameForTeam,
|
||||
} from "@calcom/features/auth/signup/utils/token";
|
||||
import { validateAndGetCorrectedUsernameAndEmail } from "@calcom/features/auth/signup/utils/validateUsername";
|
||||
import { hashPassword } from "@calcom/lib/auth/hashPassword";
|
||||
import { IS_PREMIUM_USERNAME_ENABLED } from "@calcom/lib/constants";
|
||||
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { isPrismaError } from "@calcom/lib/server/getServerErrorFromUnknown";
|
||||
import { isUsernameReservedDueToMigration } from "@calcom/lib/server/username";
|
||||
@@ -13,15 +19,7 @@ import slugify from "@calcom/lib/slugify";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
import { signupSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { joinAnyChildTeamOnOrgInvite } from "@calcom/features/auth/signup/utils/organization";
|
||||
import { prefillAvatar } from "@calcom/features/auth/signup/utils/prefillAvatar";
|
||||
import { SIGNUP_ERROR_CODES } from "@calcom/features/auth/signup/constants";
|
||||
import {
|
||||
findTokenByToken,
|
||||
throwIfTokenExpired,
|
||||
validateAndGetCorrectedUsernameForTeam,
|
||||
} from "@calcom/features/auth/signup/utils/token";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export default async function handler(body: Record<string, string>) {
|
||||
const { email, password, language, token } = signupSchema.parse(body);
|
||||
@@ -72,7 +70,7 @@ export default async function handler(body: Record<string, string>) {
|
||||
|
||||
const hashedPassword = await hashPassword(password);
|
||||
|
||||
if (foundToken && foundToken?.teamId) {
|
||||
if (foundToken?.teamId) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: foundToken.teamId,
|
||||
@@ -175,16 +173,6 @@ export default async function handler(body: Record<string, string>) {
|
||||
if (!isUsernameAvailable) {
|
||||
return NextResponse.json({ message: "A user exists with that username" }, { status: 409 });
|
||||
}
|
||||
if (IS_PREMIUM_USERNAME_ENABLED) {
|
||||
const checkUsername = await checkPremiumUsername(correctedUsername);
|
||||
if (checkUsername.premium) {
|
||||
return NextResponse.json(
|
||||
{ message: "Sign up from https://cal.com/signup to claim your premium username" },
|
||||
{ status: 422 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
|
||||
@@ -44,7 +44,7 @@ async function authMiddleware() {
|
||||
return userWithCredentials;
|
||||
}
|
||||
|
||||
// TODO: It doesn't seem to be used from within the app. It is possible that someone outside Cal.com is using this GET endpoint
|
||||
// TODO: It doesn't seem to be used from within the app. It is possible that someone outside Cal.diy is using this GET endpoint
|
||||
async function getHandler() {
|
||||
const user = await authMiddleware();
|
||||
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
|
||||
import handler from "@calcom/features/calAIPhone/phoneNumberSubscriptionWebhook";
|
||||
|
||||
export const GET = defaultResponderForAppDir(handler);
|
||||
@@ -52,9 +52,6 @@ async function handler(req: NextRequest) {
|
||||
const result = await handleCancelBooking({
|
||||
bookingData: safeBookingData,
|
||||
userId: session?.user?.id || -1,
|
||||
userUuid: session?.user?.uuid,
|
||||
actionSource: "WEBAPP",
|
||||
impersonatedByUserUuid: session?.user?.impersonatedBy?.uuid ?? null,
|
||||
});
|
||||
|
||||
// const bookingCancelService = getBookingCancelService();
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
import B2 from "backblaze-b2";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
import { COMPLIANCE_DOCUMENTS } from "~/settings/security/compliance/compliance-documents";
|
||||
|
||||
const b2 = new B2({
|
||||
applicationKeyId: process.env.B2_APPLICATION_KEY_ID || "",
|
||||
applicationKey: process.env.B2_APPLICATION_KEY || "",
|
||||
});
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const documentId = searchParams.get("id");
|
||||
|
||||
if (!documentId) {
|
||||
return NextResponse.json({ error: "Missing document ID" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Find the document in our config
|
||||
const document = COMPLIANCE_DOCUMENTS.find((doc) => doc.id === documentId);
|
||||
if (!document) {
|
||||
return NextResponse.json({ error: "Document not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Only handle B2 documents through this route
|
||||
if (document.source.type !== "b2") {
|
||||
return NextResponse.json({ error: "Invalid document type" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check authentication
|
||||
const legacyReq = buildLegacyRequest(await headers(), await cookies());
|
||||
const session = await getServerSession({ req: legacyReq });
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Check if document is restricted and user has access
|
||||
if (document.restricted) {
|
||||
const hasOrgAccess = !!session.user?.org?.id;
|
||||
if (!hasOrgAccess) {
|
||||
return NextResponse.json({ error: "Upgrade required to access this document" }, { status: 403 });
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Authorize with B2 - this returns the downloadUrl
|
||||
const { data: authResponse } = await b2.authorize();
|
||||
|
||||
const bucketName = process.env.B2_BUCKET_NAME || "";
|
||||
const fileName = document.source.fileName;
|
||||
|
||||
// Get download authorization token for this specific file
|
||||
const { data: downloadAuth } = await b2.getDownloadAuthorization({
|
||||
bucketId: process.env.B2_BUCKET_ID || "",
|
||||
fileNamePrefix: fileName,
|
||||
validDurationInSeconds: 3600, // 1 hour
|
||||
});
|
||||
|
||||
// Construct the download URL using downloadUrl from authorize() and token from getDownloadAuthorization()
|
||||
const downloadUrl = `${authResponse.downloadUrl}/file/${bucketName}/${fileName}?Authorization=${downloadAuth.authorizationToken}`;
|
||||
|
||||
// Redirect to the authorized download URL
|
||||
return NextResponse.redirect(downloadUrl, { status: 302 });
|
||||
} catch (error) {
|
||||
console.error("Failed to get B2 download URL:", error instanceof Error ? error.message : "Unknown error");
|
||||
return NextResponse.json({ error: "Failed to generate download link" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import * as twilio from "@calcom/features/ee/workflows/lib/reminders/providers/twilioProvider";
|
||||
import { IS_SMS_CREDITS_ENABLED } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { CreditType } from "@calcom/prisma/enums";
|
||||
|
||||
async function postHandler(req: NextRequest) {
|
||||
const apiKey = req.headers.get("authorization") || req.nextUrl.searchParams.get("apiKey");
|
||||
|
||||
if (process.env.CRON_API_KEY !== apiKey) {
|
||||
return NextResponse.json({ message: "Not authenticated" }, { status: 401 });
|
||||
}
|
||||
|
||||
if (!IS_SMS_CREDITS_ENABLED) {
|
||||
return NextResponse.json({ ok: true, message: "SMS credits not enabled" });
|
||||
}
|
||||
|
||||
const smsLogsWithoutPrice = await prisma.creditExpenseLog.findMany({
|
||||
where: {
|
||||
credits: null,
|
||||
smsSid: {
|
||||
not: null,
|
||||
},
|
||||
date: {
|
||||
gte: dayjs().subtract(1, "hour").toDate(),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
smsSid: true,
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
let pricesUpdated = 0;
|
||||
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
|
||||
|
||||
const creditService = new CreditService();
|
||||
|
||||
await Promise.allSettled(
|
||||
smsLogsWithoutPrice.map(async (log) => {
|
||||
if (!log.smsSid) return;
|
||||
|
||||
try {
|
||||
const { price, numSegments } = await twilio.getMessageInfo(log.smsSid);
|
||||
const credits = price ? creditService.calculateCreditsFromPrice(price) : null;
|
||||
if (!credits) return;
|
||||
|
||||
const updatedLog = await prisma.creditExpenseLog.update({
|
||||
where: { id: log.id },
|
||||
data: { credits, smsSegments: numSegments },
|
||||
select: {
|
||||
creditBalance: {
|
||||
select: {
|
||||
id: true,
|
||||
additionalCredits: true,
|
||||
teamId: true,
|
||||
userId: true,
|
||||
},
|
||||
},
|
||||
creditType: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (updatedLog.creditType === CreditType.ADDITIONAL) {
|
||||
const decrementValue =
|
||||
credits <= updatedLog.creditBalance.additionalCredits
|
||||
? credits
|
||||
: updatedLog.creditBalance.additionalCredits;
|
||||
|
||||
await prisma.creditBalance.update({
|
||||
where: { id: updatedLog.creditBalance.id },
|
||||
data: {
|
||||
additionalCredits: {
|
||||
decrement: decrementValue,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!updatedLog.creditBalance.teamId && !updatedLog.creditBalance.userId) {
|
||||
logger.error(`teamId or userId missing for expense log ${log.id}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const availableCredits = await creditService.getAllCredits({
|
||||
teamId: updatedLog.creditBalance.teamId,
|
||||
userId: updatedLog.creditBalance.userId,
|
||||
});
|
||||
|
||||
const remainingMonthlyCredits = Math.max(0, availableCredits.totalRemainingMonthlyCredits);
|
||||
|
||||
await creditService.handleLowCreditBalance({
|
||||
userId: updatedLog.creditBalance.userId,
|
||||
teamId: updatedLog.creditBalance.teamId,
|
||||
remainingCredits: remainingMonthlyCredits + availableCredits.additionalCredits,
|
||||
});
|
||||
|
||||
pricesUpdated++;
|
||||
} catch (err) {
|
||||
logger.error(`Failed to process SMS log ${log.smsSid}`, err);
|
||||
await prisma.creditExpenseLog.update({
|
||||
where: { id: log.id },
|
||||
data: { credits: 0 },
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
return NextResponse.json({ ok: true, pricesUpdated });
|
||||
}
|
||||
|
||||
export const POST = defaultResponderForAppDir(postHandler);
|
||||
@@ -1,201 +0,0 @@
|
||||
import prismock from "@calcom/testing/lib/__mocks__/prisma";
|
||||
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
|
||||
import type { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import { handleCreateCredentials } from "../route";
|
||||
|
||||
type OrgParams = { id: number };
|
||||
const createOrg = async ({ id }: OrgParams) =>
|
||||
await prismock.team.create({ data: { id, name: `Org${id}`, isOrganization: true } });
|
||||
|
||||
type UserParams = { id: number; email: string };
|
||||
const createUser = async ({ id, email }: UserParams) => await prismock.user.create({ data: { id, email } });
|
||||
|
||||
type WorkspacePlatformParams = { id: number; name?: string; slug?: string; description?: string };
|
||||
const createWorkspacePlatform = async ({ id, name, slug, description }: WorkspacePlatformParams) =>
|
||||
await prismock.workspacePlatform.create({
|
||||
data: {
|
||||
id,
|
||||
name: name ?? "Google",
|
||||
slug: slug ?? "google",
|
||||
description: description ?? "Test platform",
|
||||
defaultServiceAccountKey: {},
|
||||
},
|
||||
});
|
||||
|
||||
type DelegationCredentialParams = {
|
||||
id: string;
|
||||
orgId: number;
|
||||
domain: string;
|
||||
workspacePlatformId: number;
|
||||
};
|
||||
|
||||
const createDelegationCredential = async ({
|
||||
id,
|
||||
orgId,
|
||||
domain,
|
||||
workspacePlatformId,
|
||||
}: DelegationCredentialParams) =>
|
||||
await prismock.delegationCredential.create({
|
||||
data: {
|
||||
id,
|
||||
enabled: true,
|
||||
domain,
|
||||
organizationId: orgId,
|
||||
workspacePlatformId,
|
||||
serviceAccountKey: {
|
||||
client_email: "[email protected]",
|
||||
private_key: "pk",
|
||||
client_id: "cid",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
type CredentialParams = { id?: number; userId?: number; delegationCredentialId?: string; key?: object };
|
||||
const createCredential = async ({
|
||||
id = 1,
|
||||
userId = 1,
|
||||
delegationCredentialId = "delegation-credential-1",
|
||||
key = {},
|
||||
}: CredentialParams = {}) =>
|
||||
await prismock.credential.create({
|
||||
data: {
|
||||
id,
|
||||
type: "google_calendar",
|
||||
key,
|
||||
userId,
|
||||
appId: "google_calendar",
|
||||
delegationCredentialId,
|
||||
},
|
||||
});
|
||||
|
||||
type MembershipParams = { teamId: number; userId: number; role?: MembershipRole };
|
||||
const createMembership = async ({ teamId, userId, role = "MEMBER" }: MembershipParams) =>
|
||||
await prismock.membership.create({ data: { teamId, userId, accepted: true, role } });
|
||||
|
||||
// Helper to assert credentials in DB match expected (partial, order-insensitive)
|
||||
type PartialCredential = Partial<Awaited<ReturnType<typeof prismock.credential.create>>>;
|
||||
async function expectCredentials(expected: PartialCredential[]) {
|
||||
const actual = await prismock.credential.findMany({});
|
||||
expect(actual.length).toBe(expected.length);
|
||||
expect(actual).toEqual(expect.arrayContaining(expected.map((exp) => expect.objectContaining(exp))));
|
||||
}
|
||||
|
||||
describe("Delegation Credentials: Organization-wide Google Calendar Access", () => {
|
||||
beforeEach(() => {
|
||||
prismock.delegationCredential.deleteMany();
|
||||
prismock.credential.deleteMany();
|
||||
prismock.user.deleteMany();
|
||||
prismock.team.deleteMany();
|
||||
prismock.workspacePlatform.deleteMany();
|
||||
prismock.membership.deleteMany();
|
||||
});
|
||||
|
||||
it("shows a helpful message when no Delegation Credentials are enabled", async () => {
|
||||
const result = await handleCreateCredentials();
|
||||
expect(result).toEqual({
|
||||
message: "No enabled delegation credentials found",
|
||||
success: 0,
|
||||
failures: 0,
|
||||
});
|
||||
await expectCredentials([]);
|
||||
});
|
||||
|
||||
it("creates credentials for all eligible organization members when Delegation Credential is enabled", async () => {
|
||||
const org = await createOrg({ id: 1 });
|
||||
const workspacePlatform = await createWorkspacePlatform({ id: 1 });
|
||||
const user1 = await createUser({ id: 1, email: "[email protected]" });
|
||||
const user2 = await createUser({ id: 2, email: "[email protected]" });
|
||||
await createMembership({ teamId: org.id, userId: user1.id });
|
||||
await createMembership({ teamId: org.id, userId: user2.id });
|
||||
await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: org.id,
|
||||
domain: "example.com",
|
||||
workspacePlatformId: workspacePlatform.id,
|
||||
});
|
||||
|
||||
const result = await handleCreateCredentials();
|
||||
expect(result.success).toBe(2);
|
||||
expect(result.failures).toBe(0);
|
||||
await expectCredentials([
|
||||
{ userId: user1.id, delegationCredentialId: "delegation-credential-1", type: "google_calendar" },
|
||||
{ userId: user2.id, delegationCredentialId: "delegation-credential-1", type: "google_calendar" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips credential creation for unsupported workspace platforms", async () => {
|
||||
const org = await createOrg({ id: 1 });
|
||||
// Create a non-google workspace platform
|
||||
const outlookPlatform = await createWorkspacePlatform({
|
||||
id: 2,
|
||||
name: "Outlook",
|
||||
slug: "outlook",
|
||||
description: "Test",
|
||||
});
|
||||
const user = await createUser({ id: 1, email: "[email protected]" });
|
||||
await createMembership({ teamId: org.id, userId: user.id });
|
||||
await createDelegationCredential({
|
||||
id: "delegation-credential-2",
|
||||
orgId: org.id,
|
||||
domain: "outlook.com",
|
||||
workspacePlatformId: outlookPlatform.id,
|
||||
});
|
||||
const result = await handleCreateCredentials();
|
||||
expect(result.success).toBe(0);
|
||||
await expectCredentials([]);
|
||||
});
|
||||
|
||||
it("does not create duplicate credentials for users who already have one", async () => {
|
||||
const org = await createOrg({ id: 1 });
|
||||
const workspacePlatform = await createWorkspacePlatform({ id: 1 });
|
||||
const user = await createUser({ id: 1, email: "[email protected]" });
|
||||
await createMembership({ teamId: org.id, userId: user.id });
|
||||
await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: org.id,
|
||||
domain: "example.com",
|
||||
workspacePlatformId: workspacePlatform.id,
|
||||
});
|
||||
await createCredential({ id: 1, userId: user.id, delegationCredentialId: "delegation-credential-1" });
|
||||
const result = await handleCreateCredentials();
|
||||
expect(result.success).toBe(0);
|
||||
await expectCredentials([
|
||||
{ userId: user.id, delegationCredentialId: "delegation-credential-1", type: "google_calendar" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("processes only a batch of members at a time if there are more than the batch size", async () => {
|
||||
const org = await createOrg({ id: 1 });
|
||||
const workspacePlatform = await createWorkspacePlatform({
|
||||
id: 1,
|
||||
name: "Google",
|
||||
slug: "google",
|
||||
description: "Test platform",
|
||||
});
|
||||
// Simulate more than 100 delegated members
|
||||
const users = [];
|
||||
for (let i = 1; i <= 120; i++) {
|
||||
const user = await createUser({ id: i, email: `user${i}@example.com` });
|
||||
users.push(user);
|
||||
await createMembership({ teamId: org.id, userId: user.id });
|
||||
}
|
||||
await createDelegationCredential({
|
||||
id: "delegation-credential-1",
|
||||
orgId: org.id,
|
||||
domain: "example.com",
|
||||
workspacePlatformId: workspacePlatform.id,
|
||||
});
|
||||
const result = await handleCreateCredentials();
|
||||
expect(result.success).toBe(100); // Only batch size processed
|
||||
await expectCredentials(
|
||||
users.slice(0, 100).map((u) => ({
|
||||
userId: u.id,
|
||||
delegationCredentialId: "delegation-credential-1",
|
||||
type: "google_calendar",
|
||||
}))
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,172 +0,0 @@
|
||||
/**
|
||||
* @description This route is used to create and delete Credential records for all members of an organization that has delegation credentials enabled.
|
||||
*
|
||||
* It also deletes Credential records for all members of an organization that has delegation credentials disabled.
|
||||
*/
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
|
||||
import { buildCredentialCreateData } from "@calcom/features/credentials/services/CredentialDataService";
|
||||
import { DelegationCredentialRepository } from "@calcom/features/delegation-credentials/repositories/DelegationCredentialRepository";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
|
||||
import { defaultResponderForAppDir } from "../../defaultResponderForAppDir";
|
||||
|
||||
const moduleLogger = logger.getSubLogger({ prefix: ["[api]", "[delegation]", "[credentials/cron]"] });
|
||||
const batchSizeToCreateCredentials = 100;
|
||||
const validateRequest = (req: NextRequest) => {
|
||||
const url = new URL(req.url);
|
||||
const apiKey = req.headers.get("authorization") || url.searchParams.get("apiKey");
|
||||
if (![process.env.CRON_API_KEY, `Bearer ${process.env.CRON_SECRET}`].includes(`${apiKey}`)) {
|
||||
throw new HttpError({ statusCode: 401, message: "Unauthorized" });
|
||||
}
|
||||
};
|
||||
|
||||
export async function handleCreateCredentials() {
|
||||
const log = moduleLogger.getSubLogger({ prefix: ["CreateCredentials"] });
|
||||
const delegationCredentials = await DelegationCredentialRepository.findAllEnabledIncludeDelegatedMembers();
|
||||
|
||||
log.info(`Found ${delegationCredentials.length} enabled delegation credentials to create credentials for`);
|
||||
|
||||
if (!delegationCredentials.length) {
|
||||
return {
|
||||
message: "No enabled delegation credentials found",
|
||||
success: 0,
|
||||
failures: 0,
|
||||
};
|
||||
}
|
||||
let totalSuccess = 0;
|
||||
let totalFailures = 0;
|
||||
for (const delegationCredential of delegationCredentials) {
|
||||
const { workspacePlatform, organization } = delegationCredential;
|
||||
|
||||
if (workspacePlatform.slug !== "google") {
|
||||
log.info(
|
||||
`Skipping credential creation for workspace platform ${workspacePlatform.slug} - only google is supported`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// We can't know by looking at a Credential record in DB, if it has access to the `user.email` calendar in Google Calendar.
|
||||
// It could be a credential of a personal calendar of the same user. So, we can't just reuse any existing credential for the user, we have to check if this specific delegationCredential's UserCredential exists or not
|
||||
const existingCredentials =
|
||||
await CredentialRepository.findAllDelegationByUserIdsListAndDelegationCredentialIdAndType({
|
||||
userIds: organization.delegatedMembers.map((member) => member.userId),
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
type: "google_calendar",
|
||||
});
|
||||
|
||||
const existingCredentialUserIds = new Set(existingCredentials.map((cred) => cred.userId));
|
||||
const delegatedMembers = organization.delegatedMembers;
|
||||
const membersNeedingCredentials = delegatedMembers.filter(
|
||||
(member) => !existingCredentialUserIds.has(member.userId)
|
||||
);
|
||||
|
||||
const toProcessMembers = membersNeedingCredentials.slice(0, batchSizeToCreateCredentials);
|
||||
|
||||
log.info(
|
||||
`Creating credentials for ${toProcessMembers.length} members out of ${delegatedMembers.length} delegated members in organization ${organization.id}`
|
||||
);
|
||||
|
||||
const credentialCreationPromises = toProcessMembers.map(async (member) => {
|
||||
try {
|
||||
const credentialData = buildCredentialCreateData({
|
||||
type: "google_calendar",
|
||||
key: {
|
||||
// The in-memory credential that we create for Delegation Credential has access_token as "NOOP_UNUSED_DELEGATION_TOKEN. This is to mark it is in DB, in case we need to identify that.
|
||||
access_token: "NOOP_UNUSED_DELEGATION_TOKEN_DB",
|
||||
},
|
||||
userId: member.userId,
|
||||
appId: "google-calendar",
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
});
|
||||
await CredentialRepository.create(credentialData);
|
||||
log.info(`Created credential for member ${member.userId}`);
|
||||
} catch (error) {
|
||||
log.error(`Error creating credential for member ${member.userId}:`, safeStringify(error));
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
const results = await Promise.allSettled(credentialCreationPromises);
|
||||
const successCount = results.filter((r) => r.status === "fulfilled").length;
|
||||
const failureCount = results.filter((r) => r.status === "rejected").length;
|
||||
log.info(
|
||||
`Created ${successCount} credentials for delegationCredentialId: ${delegationCredential.id} and ${failureCount} failures`
|
||||
);
|
||||
totalSuccess += successCount;
|
||||
totalFailures += failureCount;
|
||||
}
|
||||
|
||||
log.info(
|
||||
`Completed creating credentials for all delegation credentials. Total Success: ${totalSuccess}, Total Failures: ${totalFailures}`
|
||||
);
|
||||
|
||||
return {
|
||||
executedAt: new Date().toISOString(),
|
||||
success: totalSuccess,
|
||||
failures: totalFailures,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleDeleteCredentials() {
|
||||
const log = moduleLogger.getSubLogger({ prefix: ["DeleteCredentials"] });
|
||||
const delegationCredentials =
|
||||
await DelegationCredentialRepository.findAllDisabledAndIncludeNextBatchOfMembersToProcess();
|
||||
|
||||
log.info(`Found ${delegationCredentials.length} delegation credentials to delete credentials for`);
|
||||
|
||||
if (!delegationCredentials.length) {
|
||||
return {
|
||||
message: "No disabled delegation credentials found",
|
||||
success: 0,
|
||||
failures: 0,
|
||||
};
|
||||
}
|
||||
let totalSuccess = 0;
|
||||
for (const delegationCredential of delegationCredentials) {
|
||||
const { workspacePlatform } = delegationCredential;
|
||||
|
||||
if (workspacePlatform.slug !== "google") {
|
||||
log.info(
|
||||
`Skipping credential deletion for workspace platform ${workspacePlatform.slug} - only google is supported`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// DB?: can deleting all credentials at once be problematic?
|
||||
const { count } = await CredentialRepository.deleteAllByDelegationCredentialId({
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
});
|
||||
totalSuccess += count;
|
||||
}
|
||||
log.info(`Deleted ${totalSuccess} credentials for disabled delegation credentials`);
|
||||
|
||||
return {
|
||||
executedAt: new Date().toISOString(),
|
||||
success: totalSuccess,
|
||||
failures: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const handler = async (request: NextRequest) => {
|
||||
validateRequest(request);
|
||||
const result = await Promise.allSettled([handleCreateCredentials(), handleDeleteCredentials()]);
|
||||
const response = result.map((r, index) => {
|
||||
if (r.status === "fulfilled") {
|
||||
return {
|
||||
...r.value,
|
||||
message: `Successfully executed ${index === 0 ? "create" : "delete"} credentials`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...r.reason,
|
||||
message: `Failed to execute ${index === 0 ? "create" : "delete"} credentials`,
|
||||
};
|
||||
});
|
||||
return NextResponse.json(response);
|
||||
};
|
||||
|
||||
export const GET = defaultResponderForAppDir(handler);
|
||||
@@ -1,56 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getTeamBillingServiceFactory } from "@calcom/features/ee/billing/di/containers/Billing";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
const querySchema = z.object({
|
||||
page: z.coerce.number().min(0).optional().default(0),
|
||||
});
|
||||
|
||||
async function postHandler(request: NextRequest) {
|
||||
const apiKey = request.headers.get("authorization") || request.nextUrl.searchParams.get("apiKey");
|
||||
|
||||
if (process.env.CRON_API_KEY !== apiKey) {
|
||||
return NextResponse.json({ message: "Not authenticated" }, { status: 401 });
|
||||
}
|
||||
|
||||
const pageSize = 90; // Adjust this value based on the total number of teams and the available processing time
|
||||
|
||||
let { page: pageNumber } = querySchema.parse(Object.fromEntries(request.nextUrl.searchParams));
|
||||
|
||||
while (true) {
|
||||
const teams = await prisma.team.findMany({
|
||||
where: {
|
||||
slug: {
|
||||
not: null,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
metadata: true,
|
||||
isOrganization: true,
|
||||
parentId: true,
|
||||
},
|
||||
skip: pageNumber * pageSize,
|
||||
take: pageSize,
|
||||
});
|
||||
|
||||
if (teams.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
const teamBillingFactory = getTeamBillingServiceFactory();
|
||||
const teamsBilling = teamBillingFactory.initMany(teams);
|
||||
const teamBillingPromises = teamsBilling.map((teamBilling) => teamBilling.updateQuantity("sync"));
|
||||
await Promise.allSettled(teamBillingPromises);
|
||||
|
||||
pageNumber++;
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export const POST = defaultResponderForAppDir(postHandler);
|
||||
@@ -1,318 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { sendMonthlyDigestEmail } from "@calcom/emails/workflow-email-service";
|
||||
import { EventsInsights } from "@calcom/features/insights/server/events";
|
||||
import { getTranslation } from "@calcom/i18n/server";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
const querySchema = z.object({
|
||||
page: z.coerce.number().min(0).optional().default(0),
|
||||
});
|
||||
|
||||
async function postHandler(request: NextRequest) {
|
||||
const apiKey = request.headers.get("authorization") || request.nextUrl.searchParams.get("apiKey");
|
||||
|
||||
if (process.env.CRON_API_KEY !== apiKey) {
|
||||
return NextResponse.json({ message: "Not authenticated" }, { status: 401 });
|
||||
}
|
||||
|
||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const pageSize = 90; // Adjust this value based on the total number of teams and the available processing time
|
||||
|
||||
let { page: pageNumber } = querySchema.parse(Object.fromEntries(request.nextUrl.searchParams));
|
||||
|
||||
const firstDateOfMonth = new Date();
|
||||
firstDateOfMonth.setDate(1);
|
||||
|
||||
while (true) {
|
||||
const teams = await prisma.team.findMany({
|
||||
where: {
|
||||
slug: {
|
||||
not: null,
|
||||
},
|
||||
createdAt: {
|
||||
// created before or on the first day of this month
|
||||
lte: firstDateOfMonth,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
members: true,
|
||||
name: true,
|
||||
},
|
||||
skip: pageNumber * pageSize,
|
||||
take: pageSize,
|
||||
});
|
||||
|
||||
if (teams.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
for (const team of teams) {
|
||||
const EventData: {
|
||||
Created: number;
|
||||
Completed: number;
|
||||
Rescheduled: number;
|
||||
Cancelled: number;
|
||||
mostBookedEvents: {
|
||||
eventTypeId?: number | null;
|
||||
eventTypeName?: string | null;
|
||||
count?: number | null;
|
||||
}[];
|
||||
membersWithMostBookings: {
|
||||
userId: number | null;
|
||||
user: {
|
||||
id: number;
|
||||
name: string | null;
|
||||
email: string;
|
||||
avatar: string | null;
|
||||
username: string | null;
|
||||
};
|
||||
count: number;
|
||||
}[];
|
||||
admin: { email: string; name: string };
|
||||
team: {
|
||||
name: string;
|
||||
id: number;
|
||||
};
|
||||
} = {
|
||||
Created: 0,
|
||||
Completed: 0,
|
||||
Rescheduled: 0,
|
||||
Cancelled: 0,
|
||||
mostBookedEvents: [],
|
||||
membersWithMostBookings: [],
|
||||
admin: { email: "", name: "" },
|
||||
team: { name: team.name, id: team.id },
|
||||
};
|
||||
|
||||
const userIdsFromTeams = team.members.map((u) => u.userId);
|
||||
|
||||
// Booking Events
|
||||
const whereConditional: Prisma.BookingTimeStatusDenormalizedWhereInput = {
|
||||
OR: [
|
||||
{
|
||||
teamId: team.id,
|
||||
isTeamBooking: true,
|
||||
},
|
||||
{
|
||||
userId: {
|
||||
in: userIdsFromTeams,
|
||||
},
|
||||
isTeamBooking: false,
|
||||
},
|
||||
],
|
||||
createdAt: {
|
||||
gte: dayjs(firstDateOfMonth).toISOString(),
|
||||
lte: dayjs(new Date()).toISOString(),
|
||||
},
|
||||
};
|
||||
|
||||
const countGroupedByStatus = await EventsInsights.countGroupedByStatus(whereConditional);
|
||||
|
||||
EventData["Created"] = countGroupedByStatus["_all"];
|
||||
EventData["Completed"] = countGroupedByStatus["completed"];
|
||||
EventData["Rescheduled"] = countGroupedByStatus["rescheduled"];
|
||||
EventData["Cancelled"] = countGroupedByStatus["cancelled"];
|
||||
|
||||
// Most Booked Event Type
|
||||
const bookingWhere: Prisma.BookingTimeStatusDenormalizedWhereInput = {
|
||||
createdAt: {
|
||||
gte: dayjs(firstDateOfMonth).startOf("day").toDate(),
|
||||
lte: dayjs(new Date()).endOf("day").toDate(),
|
||||
},
|
||||
OR: [
|
||||
{
|
||||
teamId: team.id,
|
||||
isTeamBooking: true,
|
||||
},
|
||||
{
|
||||
userId: {
|
||||
in: userIdsFromTeams,
|
||||
},
|
||||
isTeamBooking: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const bookingsFromSelected = await prisma.bookingTimeStatusDenormalized.groupBy({
|
||||
by: ["eventTypeId"],
|
||||
where: bookingWhere,
|
||||
_count: {
|
||||
id: true,
|
||||
},
|
||||
orderBy: {
|
||||
_count: {
|
||||
id: "desc",
|
||||
},
|
||||
},
|
||||
take: 10,
|
||||
});
|
||||
|
||||
const eventTypeIds = bookingsFromSelected.reduce((acc: number[], booking) => {
|
||||
if (typeof booking.eventTypeId !== "number") return acc;
|
||||
return [...acc, booking.eventTypeId];
|
||||
}, []);
|
||||
|
||||
const eventTypeWhereConditional: Prisma.EventTypeWhereInput = {
|
||||
id: {
|
||||
in: eventTypeIds,
|
||||
},
|
||||
};
|
||||
|
||||
const eventTypesFrom = await prisma.eventType.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
teamId: true,
|
||||
userId: true,
|
||||
slug: true,
|
||||
users: {
|
||||
select: {
|
||||
username: true,
|
||||
},
|
||||
},
|
||||
team: {
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
where: eventTypeWhereConditional,
|
||||
});
|
||||
|
||||
const eventTypeHashMap: Map<
|
||||
number,
|
||||
Prisma.EventTypeGetPayload<{
|
||||
select: {
|
||||
id: true;
|
||||
title: true;
|
||||
teamId: true;
|
||||
userId: true;
|
||||
slug: true;
|
||||
users: {
|
||||
select: {
|
||||
username: true;
|
||||
};
|
||||
};
|
||||
team: {
|
||||
select: {
|
||||
slug: true;
|
||||
};
|
||||
};
|
||||
};
|
||||
}>
|
||||
> = new Map();
|
||||
eventTypesFrom.forEach((eventType) => {
|
||||
eventTypeHashMap.set(eventType.id, eventType);
|
||||
});
|
||||
|
||||
EventData["mostBookedEvents"] = bookingsFromSelected.map((booking) => {
|
||||
const eventTypeSelected = eventTypeHashMap.get(booking.eventTypeId ?? 0);
|
||||
if (!eventTypeSelected) {
|
||||
return {};
|
||||
}
|
||||
|
||||
let eventSlug = "";
|
||||
if (eventTypeSelected.userId) {
|
||||
eventSlug = `${eventTypeSelected?.users[0]?.username}/${eventTypeSelected?.slug}`;
|
||||
}
|
||||
if (eventTypeSelected?.team && eventTypeSelected?.team?.slug) {
|
||||
eventSlug = `${eventTypeSelected.team.slug}/${eventTypeSelected.slug}`;
|
||||
}
|
||||
return {
|
||||
eventTypeId: booking.eventTypeId,
|
||||
eventTypeName: eventSlug,
|
||||
count: booking._count.id,
|
||||
};
|
||||
});
|
||||
|
||||
// Most booked members
|
||||
const bookingsFromTeam = await prisma.bookingTimeStatusDenormalized.groupBy({
|
||||
by: ["userId"],
|
||||
where: bookingWhere,
|
||||
_count: {
|
||||
id: true,
|
||||
},
|
||||
orderBy: {
|
||||
_count: {
|
||||
id: "desc",
|
||||
},
|
||||
},
|
||||
take: 10,
|
||||
});
|
||||
|
||||
const userIds = bookingsFromTeam
|
||||
.filter((booking) => typeof booking.userId === "number")
|
||||
.map((booking) => booking.userId);
|
||||
|
||||
if (userIds.length === 0) {
|
||||
EventData["membersWithMostBookings"] = [];
|
||||
} else {
|
||||
const teamUsers = await prisma.user.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: userIds as number[],
|
||||
},
|
||||
},
|
||||
select: { id: true, name: true, email: true, avatarUrl: true, username: true },
|
||||
});
|
||||
|
||||
const userHashMap = new Map();
|
||||
teamUsers.forEach((user) => {
|
||||
userHashMap.set(user.id, user);
|
||||
});
|
||||
|
||||
EventData["membersWithMostBookings"] = bookingsFromTeam.map((booking) => {
|
||||
return {
|
||||
userId: booking.userId,
|
||||
user: userHashMap.get(booking.userId),
|
||||
count: booking._count.id,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// Send mail to all Owners and Admins
|
||||
const mailReceivers = team?.members?.filter(
|
||||
(member) => member.role === "OWNER" || member.role === "ADMIN"
|
||||
);
|
||||
|
||||
const mailsToSend = mailReceivers.map(async (receiver) => {
|
||||
const owner = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: receiver?.userId,
|
||||
},
|
||||
});
|
||||
|
||||
if (owner) {
|
||||
const t = await getTranslation(owner?.locale ?? "en", "common");
|
||||
|
||||
// Only send email if user has allowed to receive monthly digest emails
|
||||
if (owner.receiveMonthlyDigestEmail) {
|
||||
await sendMonthlyDigestEmail({
|
||||
...EventData,
|
||||
admin: { email: owner?.email ?? "", name: owner?.name ?? "" },
|
||||
language: t,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(mailsToSend);
|
||||
|
||||
await delay(100); // Adjust the delay as needed to avoid rate limiting
|
||||
}
|
||||
|
||||
pageNumber++;
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export const POST = defaultResponderForAppDir(postHandler);
|
||||
@@ -1,5 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
|
||||
import { handleQueuedFormResponseCleanup } from "@calcom/app-store/routing-forms/cron/queuedFormResponseCleanup";
|
||||
|
||||
export const GET = defaultResponderForAppDir(handleQueuedFormResponseCleanup);
|
||||
@@ -7,6 +7,30 @@ import { CalendarAppDelegationCredentialInvalidGrantError } from "@calcom/lib/Ca
|
||||
|
||||
import { handleCreateSelectedCalendars, isSameEmail } from "../route";
|
||||
|
||||
// Mock findUniqueDelegationCalendarCredential to actually query prismock
|
||||
// The stub in delegationCredential.ts always returns null, breaking the cron flow.
|
||||
// We mock it to return a credential-like object so getCalendarService() proceeds.
|
||||
vi.mock("@calcom/app-store/delegationCredential", async () => {
|
||||
const actual = await vi.importActual<typeof import("@calcom/app-store/delegationCredential")>(
|
||||
"@calcom/app-store/delegationCredential"
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
findUniqueDelegationCalendarCredential: vi
|
||||
.fn()
|
||||
.mockImplementation(
|
||||
async ({ userId, delegationCredentialId }: { userId: number; delegationCredentialId: string }) => {
|
||||
// Return a minimal credential object that satisfies CredentialForCalendarServiceWithEmail
|
||||
const credential = await prismock.credential.findFirst({
|
||||
where: { userId, delegationCredentialId },
|
||||
include: { user: { select: { email: true } } },
|
||||
});
|
||||
return credential;
|
||||
}
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
// Mock GoogleCalendarService factory function
|
||||
const getPrimaryCalendarMock = vi.fn();
|
||||
vi.mock("@calcom/app-store/googlecalendar/lib/CalendarService", () => {
|
||||
|
||||
@@ -122,23 +122,7 @@ async function getCalendarService(delegationUserCredential: DelegationUserCreden
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
!credentialForCalendarService.delegatedTo ||
|
||||
!credentialForCalendarService.delegatedTo.serviceAccountKey ||
|
||||
!credentialForCalendarService.delegatedTo.serviceAccountKey.client_email
|
||||
) {
|
||||
log.error(
|
||||
`Invalid delegatedTo for delegationCredentialId: ${delegationUserCredential.delegationCredentialId}`,
|
||||
safeStringify({
|
||||
delegatedToSet: !!credentialForCalendarService.delegatedTo,
|
||||
serviceAccountKeySet: !!credentialForCalendarService.delegatedTo?.serviceAccountKey,
|
||||
clientEmailSet: !!credentialForCalendarService.delegatedTo?.serviceAccountKey?.client_email,
|
||||
})
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const googleCalendarService = createGoogleCalendarServiceWithGoogleType(
|
||||
const googleCalendarService= createGoogleCalendarServiceWithGoogleType(
|
||||
credentialForCalendarService as CredentialForCalendarServiceWithEmail
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
|
||||
import { handler } from "@calcom/features/ee/workflows/api/scheduleEmailReminders";
|
||||
|
||||
export const POST = defaultResponderForAppDir(handler);
|
||||
@@ -1,5 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
|
||||
import { handler } from "@calcom/features/ee/workflows/api/scheduleSMSReminders";
|
||||
|
||||
export const POST = defaultResponderForAppDir(handler);
|
||||
@@ -1,5 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
|
||||
import { handler } from "@calcom/features/ee/workflows/api/scheduleWhatsappReminders";
|
||||
|
||||
export const POST = defaultResponderForAppDir(handler);
|
||||
@@ -227,7 +227,6 @@ describe("link route", () => {
|
||||
bookingId: 1,
|
||||
confirmed: true,
|
||||
emailsEnabled: true,
|
||||
actionSource: "MAGIC_LINK",
|
||||
}),
|
||||
})
|
||||
);
|
||||
@@ -245,7 +244,6 @@ describe("link route", () => {
|
||||
bookingId: 1,
|
||||
confirmed: false,
|
||||
emailsEnabled: true,
|
||||
actionSource: "MAGIC_LINK",
|
||||
}),
|
||||
})
|
||||
);
|
||||
@@ -265,7 +263,6 @@ describe("link route", () => {
|
||||
confirmed: false,
|
||||
reason: "test-reason",
|
||||
emailsEnabled: true,
|
||||
actionSource: "MAGIC_LINK",
|
||||
}),
|
||||
})
|
||||
);
|
||||
@@ -316,16 +313,18 @@ describe("link route", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("should pass actor from makeUserActor to confirmHandler", async () => {
|
||||
it("should pass user context to confirmHandler input", async () => {
|
||||
const baseUrl = "https://app.example.com/api/link?action=accept&token=encrypted-token";
|
||||
const req = createMockRequest(baseUrl);
|
||||
|
||||
await GET(req, { params: Promise.resolve({}) });
|
||||
|
||||
// After EE removal, actor/actionSource are no longer passed to confirmHandler
|
||||
expect(mockConfirmHandler).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
input: expect.objectContaining({
|
||||
actor: { type: "user", id: "test-uuid" },
|
||||
bookingId: 1,
|
||||
confirmed: true,
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import process from "node:process";
|
||||
import { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { symmetricDecrypt } from "@calcom/lib/crypto";
|
||||
import { distributedTracing } from "@calcom/lib/tracing/factory";
|
||||
@@ -92,9 +91,6 @@ async function handler(request: NextRequest) {
|
||||
platformBookingUrl,
|
||||
}
|
||||
: undefined,
|
||||
actionSource: "MAGIC_LINK",
|
||||
actor: makeUserActor(user.uuid),
|
||||
impersonatedByUserUuid: null,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import {
|
||||
ANDROID_CHROME_ICON_192,
|
||||
ANDROID_CHROME_ICON_256,
|
||||
@@ -19,8 +12,12 @@ import {
|
||||
} from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { isTrustedInternalUrl, logBlockedSSRFAttempt, validateUrlForSSRF } from "@calcom/lib/ssrfProtection";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["[api/logo]"] });
|
||||
|
||||
@@ -170,7 +167,8 @@ async function getHandler(request: NextRequest) {
|
||||
|
||||
// Create a legacy request object for compatibility
|
||||
const legacyReq = buildLegacyRequest(await headers(), await cookies());
|
||||
const { isValidOrgDomain } = orgDomainConfig(legacyReq);
|
||||
const currentOrgDomain = null;
|
||||
const isValidOrgDomain = false;
|
||||
|
||||
const hostname = request.headers.get("host");
|
||||
if (!hostname) {
|
||||
@@ -185,7 +183,7 @@ async function getHandler(request: NextRequest) {
|
||||
const [subdomain] = domains;
|
||||
const teamLogos = await getTeamLogos(subdomain, isValidOrgDomain);
|
||||
|
||||
// Resolve all icon types to team logos, falling back to Cal.com defaults.
|
||||
// Resolve all icon types to team logos, falling back to Cal.diy defaults.
|
||||
const type: LogoType = parsedQuery?.type && isValidLogoType(parsedQuery.type) ? parsedQuery.type : "logo";
|
||||
const logoDefinition = logoDefinitions[type];
|
||||
const filteredLogo = teamLogos[logoDefinition.source] ?? logoDefinition.fallback;
|
||||
@@ -237,7 +235,7 @@ async function getHandler(request: NextRequest) {
|
||||
imageResponse.headers.set("Cache-Control", "s-maxage=86400, stale-while-revalidate=60");
|
||||
|
||||
return imageResponse;
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
return NextResponse.json({ error: "Failed fetching logo" }, { status: 404 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import { OrganizationOnboardingRepository } from "@calcom/features/organizations/repositories/OrganizationOnboardingRepository";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { orgOnboardingTeamsSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
const querySchema = z.object({
|
||||
session_id: z.string().min(1),
|
||||
paymentStatus: z.enum(["success", "failed"]),
|
||||
});
|
||||
|
||||
async function getHandler(req: NextRequest) {
|
||||
try {
|
||||
const searchParams = req.nextUrl.searchParams;
|
||||
const { session_id, paymentStatus } = querySchema.parse({
|
||||
session_id: searchParams.get("session_id"),
|
||||
paymentStatus: searchParams.get("paymentStatus"),
|
||||
});
|
||||
|
||||
// Retrieve checkout session from Stripe to get metadata
|
||||
const checkoutSession = await stripe.checkout.sessions.retrieve(session_id);
|
||||
if (!checkoutSession) {
|
||||
throw new HttpError({ statusCode: 404, message: "Checkout session not found" });
|
||||
}
|
||||
|
||||
// Extract organizationOnboardingId from metadata
|
||||
const organizationOnboardingId = checkoutSession.metadata?.organizationOnboardingId;
|
||||
|
||||
// Check if onboarding-v3 feature flag is enabled
|
||||
const featuresRepository = new FeaturesRepository(prisma);
|
||||
const isOnboardingV3Enabled = await featuresRepository.checkIfFeatureIsEnabledGlobally("onboarding-v3");
|
||||
|
||||
// Build query params to preserve
|
||||
const params = new URLSearchParams({
|
||||
session_id,
|
||||
paymentStatus,
|
||||
});
|
||||
|
||||
// If onboarding-v3 is enabled AND organizationOnboardingId exists, redirect to onboarding flow
|
||||
if (isOnboardingV3Enabled && organizationOnboardingId) {
|
||||
// Check if this is a migration flow (user has already completed onboarding)
|
||||
const onboarding = await OrganizationOnboardingRepository.findById(organizationOnboardingId);
|
||||
const hasMigratedTeams =
|
||||
onboarding?.teams &&
|
||||
orgOnboardingTeamsSchema.parse(onboarding.teams).some((team) => team.isBeingMigrated);
|
||||
|
||||
if (hasMigratedTeams) {
|
||||
// Migration flow - user already completed onboarding, redirect to event-types
|
||||
const redirectUrl = new URL("/event-types?newOrganizationModal=true", WEBAPP_URL).toString();
|
||||
return NextResponse.redirect(redirectUrl);
|
||||
}
|
||||
|
||||
// Regular flow - redirect to personal onboarding
|
||||
params.append("fromTeamOnboarding", "true");
|
||||
const redirectUrl = new URL(
|
||||
`/onboarding/personal/settings?${params.toString()}`,
|
||||
WEBAPP_URL
|
||||
).toString();
|
||||
return NextResponse.redirect(redirectUrl);
|
||||
}
|
||||
|
||||
// Otherwise, redirect to the current flow
|
||||
// Preserve any additional query params that were passed
|
||||
searchParams.forEach((value, key) => {
|
||||
if (key !== "session_id" && key !== "paymentStatus") {
|
||||
params.append(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
const redirectUrl = new URL(
|
||||
`/settings/organizations/new/status?${params.toString()}`,
|
||||
WEBAPP_URL
|
||||
).toString();
|
||||
return NextResponse.redirect(redirectUrl);
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
throw error;
|
||||
}
|
||||
// If there's an error, fall back to the default status page
|
||||
const searchParams = req.nextUrl.searchParams;
|
||||
const fallbackParams = new URLSearchParams({
|
||||
session_id: searchParams.get("session_id") || "",
|
||||
paymentStatus: searchParams.get("paymentStatus") || "failed",
|
||||
});
|
||||
const fallbackUrl = new URL(
|
||||
`/settings/organizations/new/status?${fallbackParams.toString()}`,
|
||||
WEBAPP_URL
|
||||
).toString();
|
||||
return NextResponse.redirect(fallbackUrl);
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(getHandler);
|
||||
@@ -1,213 +0,0 @@
|
||||
import "@calcom/testing/lib/__mocks__/prisma";
|
||||
import { onSubmissionOfFormResponse } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
|
||||
import { getResponseToStore } from "@calcom/app-store/routing-forms/lib/getResponseToStore";
|
||||
import { getSerializableForm } from "@calcom/app-store/routing-forms/lib/getSerializableForm";
|
||||
import { RoutingFormResponseRepository } from "@calcom/features/routing-forms/repositories/RoutingFormResponseRepository";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { queuedResponseHandler } from "../route";
|
||||
|
||||
vi.mock("@calcom/features/routing-forms/repositories/RoutingFormResponseRepository");
|
||||
|
||||
const mockRoutingFormResponseRepository = {
|
||||
getQueuedFormResponseFromId: vi.fn(),
|
||||
recordFormResponse: vi.fn(),
|
||||
};
|
||||
vi.mock("@calcom/app-store/routing-forms/lib/getSerializableForm");
|
||||
vi.mock("@calcom/app-store/routing-forms/lib/getResponseToStore");
|
||||
vi.mock("@calcom/app-store/routing-forms/lib/formSubmissionUtils");
|
||||
const mockQueuedFormResponse = {
|
||||
id: "1",
|
||||
formId: "mock-form-id",
|
||||
form: {
|
||||
id: "mock-form-id",
|
||||
name: "Test Form",
|
||||
description: "Test Form Description",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
fields: [],
|
||||
routes: [],
|
||||
userId: 1,
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
},
|
||||
team: null,
|
||||
teamId: null,
|
||||
position: 1,
|
||||
updatedById: null,
|
||||
settings: {},
|
||||
disabled: false,
|
||||
},
|
||||
chosenRouteId: "mock-chosen-route-id",
|
||||
fallbackAction: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
response: {},
|
||||
actualResponseId: 1,
|
||||
};
|
||||
|
||||
describe("queuedResponseHandler", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(RoutingFormResponseRepository).mockImplementation(function () {
|
||||
return mockRoutingFormResponseRepository as any;
|
||||
});
|
||||
});
|
||||
|
||||
it("should process a queued form response", async () => {
|
||||
vi.mocked(mockRoutingFormResponseRepository.getQueuedFormResponseFromId).mockResolvedValue(
|
||||
mockQueuedFormResponse
|
||||
);
|
||||
|
||||
vi.mocked(getSerializableForm).mockResolvedValue({
|
||||
id: "mock-form-id",
|
||||
name: "Test Form",
|
||||
description: "Test Form Description",
|
||||
fields: [],
|
||||
routes: [],
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
position: 1,
|
||||
updatedById: null,
|
||||
disabled: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
settings: {},
|
||||
} as unknown as Awaited<ReturnType<typeof getSerializableForm>>);
|
||||
|
||||
vi.mocked(getResponseToStore).mockResolvedValue({
|
||||
id: "mock-form-id",
|
||||
name: "Test Form",
|
||||
description: "Test Form Description",
|
||||
fields: [],
|
||||
routes: [],
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
},
|
||||
team: null,
|
||||
} as unknown as Awaited<ReturnType<typeof getResponseToStore>>);
|
||||
|
||||
vi.mocked(onSubmissionOfFormResponse).mockResolvedValue({
|
||||
id: "mock-form-id",
|
||||
name: "Test Form",
|
||||
description: "Test Form Description",
|
||||
fields: [],
|
||||
routes: [],
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
},
|
||||
team: null,
|
||||
} as unknown as Awaited<ReturnType<typeof onSubmissionOfFormResponse>>);
|
||||
|
||||
vi.mocked(mockRoutingFormResponseRepository.recordFormResponse).mockResolvedValue({
|
||||
id: "mock-form-id",
|
||||
name: "Test Form",
|
||||
description: "Test Form Description",
|
||||
fields: [],
|
||||
routes: [],
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
},
|
||||
team: null,
|
||||
chosenRouteId: "mock-chosen-route-id",
|
||||
} as unknown as Awaited<ReturnType<typeof mockRoutingFormResponseRepository.recordFormResponse>>);
|
||||
|
||||
const response = await queuedResponseHandler({
|
||||
queuedFormResponseId: "1",
|
||||
params: {},
|
||||
});
|
||||
expect(response).toEqual({
|
||||
formResponseId: "mock-form-id",
|
||||
message: "Processed",
|
||||
});
|
||||
});
|
||||
|
||||
it("should pass fallbackAction to onSubmissionOfFormResponse when present", async () => {
|
||||
const fallbackAction = {
|
||||
type: "eventTypeRedirectUrl" as const,
|
||||
value: "team/fallback-event",
|
||||
eventTypeId: 42,
|
||||
};
|
||||
|
||||
vi.mocked(mockRoutingFormResponseRepository.getQueuedFormResponseFromId).mockResolvedValue({
|
||||
...mockQueuedFormResponse,
|
||||
fallbackAction,
|
||||
});
|
||||
|
||||
vi.mocked(getSerializableForm).mockResolvedValue({
|
||||
id: "mock-form-id",
|
||||
name: "Test Form",
|
||||
description: "Test Form Description",
|
||||
fields: [],
|
||||
routes: [],
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
position: 1,
|
||||
updatedById: null,
|
||||
disabled: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
settings: {},
|
||||
} as unknown as Awaited<ReturnType<typeof getSerializableForm>>);
|
||||
|
||||
vi.mocked(getResponseToStore).mockReturnValue({} as ReturnType<typeof getResponseToStore>);
|
||||
|
||||
vi.mocked(onSubmissionOfFormResponse).mockResolvedValue(
|
||||
undefined as unknown as Awaited<ReturnType<typeof onSubmissionOfFormResponse>>
|
||||
);
|
||||
|
||||
vi.mocked(mockRoutingFormResponseRepository.recordFormResponse).mockResolvedValue({
|
||||
id: 1,
|
||||
response: {},
|
||||
} as Awaited<ReturnType<typeof mockRoutingFormResponseRepository.recordFormResponse>>);
|
||||
|
||||
await queuedResponseHandler({
|
||||
queuedFormResponseId: "1",
|
||||
params: {},
|
||||
});
|
||||
|
||||
expect(onSubmissionOfFormResponse).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
fallbackAction,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("if no queued form response is found, should return early", async () => {
|
||||
vi.mocked(mockRoutingFormResponseRepository.getQueuedFormResponseFromId).mockResolvedValue(null);
|
||||
const response = await queuedResponseHandler({
|
||||
queuedFormResponseId: "1",
|
||||
params: {},
|
||||
});
|
||||
expect(response).toEqual({
|
||||
formResponseId: null,
|
||||
message: "Already processed",
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw if form has no fields", async () => {
|
||||
vi.mocked(mockRoutingFormResponseRepository.getQueuedFormResponseFromId).mockResolvedValue(
|
||||
mockQueuedFormResponse
|
||||
);
|
||||
vi.mocked(getSerializableForm).mockResolvedValue({
|
||||
id: "mock-form-id",
|
||||
name: "Test Form",
|
||||
description: "Test Form Description",
|
||||
fields: undefined,
|
||||
routes: [],
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
},
|
||||
team: null,
|
||||
} as unknown as Awaited<ReturnType<typeof getSerializableForm>>);
|
||||
await expect(
|
||||
queuedResponseHandler({
|
||||
queuedFormResponseId: "1",
|
||||
params: {},
|
||||
})
|
||||
).rejects.toThrow("Form has no fields");
|
||||
});
|
||||
});
|
||||
@@ -1,131 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { z, ZodError } from "zod";
|
||||
|
||||
import { onSubmissionOfFormResponse } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
|
||||
import { getResponseToStore } from "@calcom/app-store/routing-forms/lib/getResponseToStore";
|
||||
import { getSerializableForm } from "@calcom/app-store/routing-forms/lib/getSerializableForm";
|
||||
import { PrismaPendingRoutingTraceRepository } from "@calcom/features/routing-trace/repositories/PrismaPendingRoutingTraceRepository";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { RoutingFormResponseRepository } from "@calcom/features/routing-forms/repositories/RoutingFormResponseRepository";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import { defaultResponderForAppDir } from "../../defaultResponderForAppDir";
|
||||
|
||||
const queuedResponseSchema = z.object({
|
||||
queuedFormResponseId: z.string(),
|
||||
params: z.record(z.string(), z.string().or(z.array(z.string()))),
|
||||
});
|
||||
|
||||
export const queuedResponseHandler = async ({
|
||||
queuedFormResponseId,
|
||||
params,
|
||||
}: {
|
||||
queuedFormResponseId: string;
|
||||
params: Record<string, string | string[]>;
|
||||
}) => {
|
||||
const formResponseRepo = new RoutingFormResponseRepository(prisma);
|
||||
|
||||
// Get the queued response
|
||||
const queuedFormResponse = await formResponseRepo.getQueuedFormResponseFromId(queuedFormResponseId);
|
||||
|
||||
if (!queuedFormResponse) {
|
||||
return {
|
||||
formResponseId: null,
|
||||
message: "Already processed",
|
||||
};
|
||||
}
|
||||
|
||||
const serializableForm = await getSerializableForm({
|
||||
form: queuedFormResponse.form,
|
||||
});
|
||||
|
||||
if (!serializableForm.fields) {
|
||||
throw new Error("Form has no fields");
|
||||
}
|
||||
|
||||
const response = getResponseToStore({
|
||||
formFields: serializableForm.fields,
|
||||
fieldsResponses: params,
|
||||
});
|
||||
|
||||
const formResponse = await formResponseRepo.recordFormResponse({
|
||||
formId: queuedFormResponse.formId,
|
||||
queuedFormResponseId: queuedFormResponse.id,
|
||||
// We record new response here as that might be different from the queued response depending on if the user changed something in b/w before clicking CTA and that something wasn't prerendered
|
||||
response,
|
||||
// We use the queuedFormResponse's chosenRouteId because that is what decided routed team members
|
||||
chosenRouteId: queuedFormResponse.chosenRouteId,
|
||||
});
|
||||
|
||||
// Link the pending routing trace to the new formResponseId so it can be found when booking is created
|
||||
try {
|
||||
const pendingTraceRepo = new PrismaPendingRoutingTraceRepository(prisma);
|
||||
await pendingTraceRepo.linkToFormResponse({
|
||||
queuedFormResponseId: queuedFormResponse.id,
|
||||
formResponseId: formResponse.id,
|
||||
});
|
||||
} catch (error) {
|
||||
// Log but don't fail - trace linking is not critical
|
||||
logger.warn("Failed to link pending routing trace to form response", safeStringify(error));
|
||||
}
|
||||
|
||||
const chosenRoute = serializableForm.routes?.find((r) => r.id === queuedFormResponse.chosenRouteId);
|
||||
const fallbackAction = queuedFormResponse.fallbackAction as {
|
||||
type: "customPageMessage" | "externalRedirectUrl" | "eventTypeRedirectUrl";
|
||||
value: string;
|
||||
eventTypeId?: number;
|
||||
} | null;
|
||||
|
||||
await onSubmissionOfFormResponse({
|
||||
form: {
|
||||
...queuedFormResponse.form,
|
||||
...serializableForm,
|
||||
},
|
||||
formResponseInDb: formResponse,
|
||||
chosenRouteAction: chosenRoute ? ("action" in chosenRoute ? chosenRoute.action : null) : null,
|
||||
fallbackAction,
|
||||
});
|
||||
|
||||
return {
|
||||
formResponseId: formResponse.id,
|
||||
message: "Processed",
|
||||
};
|
||||
};
|
||||
|
||||
export const handler = async (req: NextRequest) => {
|
||||
try {
|
||||
const body = await req.json();
|
||||
const { params, queuedFormResponseId } = queuedResponseSchema.parse(body);
|
||||
const result = await queuedResponseHandler({
|
||||
queuedFormResponseId,
|
||||
params,
|
||||
});
|
||||
|
||||
return NextResponse.json({ status: "success", data: result });
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
logger.error("Invalid input", safeStringify(error));
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: "error",
|
||||
message: "Invalid input",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
logger.error("Error in queuedResponseHandler", safeStringify(error));
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: "error",
|
||||
message: "Internal server error",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = defaultResponderForAppDir(handler);
|
||||
@@ -1,154 +0,0 @@
|
||||
import type { DirectorySyncEvent, DirectorySyncRequest } from "@boxyhq/saml-jackson";
|
||||
import type { Params } from "app/_types";
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import handleGroupEvents from "@calcom/features/ee/dsync/lib/handleGroupEvents";
|
||||
import handleUserEvents from "@calcom/features/ee/dsync/lib/handleUserEvents";
|
||||
import jackson from "@calcom/features/ee/sso/lib/jackson";
|
||||
import { DIRECTORY_IDS_TO_LOG } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["[scim]"] });
|
||||
|
||||
// Extract the auth token from the request headers
|
||||
const extractAuthToken = (req: NextRequest): string | null => {
|
||||
const authHeader = req.headers.get("authorization") || null;
|
||||
return authHeader ? authHeader.split(" ")[1] : null;
|
||||
};
|
||||
|
||||
// Handle the SCIM events
|
||||
const handleEvents = async (event: DirectorySyncEvent) => {
|
||||
log.debug("handleEvents", safeStringify(event));
|
||||
const dSyncData = await prisma.dSyncData.findFirst({
|
||||
where: {
|
||||
directoryId: event.directory_id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
organizationId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!dSyncData) {
|
||||
throw new Error("Directory sync data not found");
|
||||
}
|
||||
|
||||
const { organizationId } = dSyncData;
|
||||
|
||||
if (!organizationId) {
|
||||
throw new Error(`Org ID not found for dsync ${dSyncData.id}`);
|
||||
}
|
||||
|
||||
if (event.event.includes("group")) {
|
||||
handleGroupEvents(event, organizationId);
|
||||
}
|
||||
|
||||
if (event.event === "user.created" || event.event === "user.updated") {
|
||||
await handleUserEvents(event, organizationId);
|
||||
}
|
||||
};
|
||||
|
||||
const querySchema = z.object({
|
||||
directory: z.string().array(),
|
||||
});
|
||||
|
||||
// This is the handler for the SCIM API requests
|
||||
async function getHandler(request: NextRequest, { params }: { params: Promise<Params> }) {
|
||||
return handleScimRequest(request, "GET", params);
|
||||
}
|
||||
|
||||
async function postHandler(request: NextRequest, { params }: { params: Promise<Params> }) {
|
||||
return handleScimRequest(request, "POST", params);
|
||||
}
|
||||
|
||||
async function putHandler(request: NextRequest, { params }: { params: Promise<Params> }) {
|
||||
return handleScimRequest(request, "PUT", params);
|
||||
}
|
||||
|
||||
async function patchHandler(request: NextRequest, { params }: { params: Promise<Params> }) {
|
||||
return handleScimRequest(request, "PATCH", params);
|
||||
}
|
||||
|
||||
async function deleteHandler(request: NextRequest, { params }: { params: Promise<Params> }) {
|
||||
return handleScimRequest(request, "DELETE", params);
|
||||
}
|
||||
|
||||
async function handleScimRequest(request: NextRequest, method: string, params: Promise<Params>) {
|
||||
const parsed = querySchema.safeParse(await params);
|
||||
if (!parsed.success || parsed.data.directory.length === 0) {
|
||||
return NextResponse.json({ error: "Missing directory parameters" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { dsyncController } = await jackson();
|
||||
|
||||
const [directoryId, path, resourceId] = parsed.data.directory;
|
||||
const shouldLog = DIRECTORY_IDS_TO_LOG.includes(directoryId);
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
|
||||
if (shouldLog) {
|
||||
console.log(
|
||||
"SCIM API request",
|
||||
safeStringify({
|
||||
method,
|
||||
url: request.url,
|
||||
params: parsed.data.directory,
|
||||
searchParams: Object.fromEntries(searchParams.entries()),
|
||||
body: request.body
|
||||
? await request
|
||||
.clone()
|
||||
.json()
|
||||
.catch(() => ({}))
|
||||
: undefined,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
let body: object | undefined = undefined;
|
||||
try {
|
||||
body = await request.json().catch(() => undefined);
|
||||
} catch (e) {
|
||||
log.error(`Error parsing SCIM event for directoryId ${directoryId} with error: ${e}`);
|
||||
}
|
||||
|
||||
// Handle the SCIM API requests
|
||||
const scimRequest: DirectorySyncRequest = {
|
||||
method,
|
||||
directoryId,
|
||||
resourceId,
|
||||
apiSecret: extractAuthToken(request),
|
||||
resourceType: path === "Users" ? "users" : "groups",
|
||||
body,
|
||||
query: {
|
||||
count: searchParams.get("count") ? parseInt(searchParams.get("count") as string) : undefined,
|
||||
startIndex: searchParams.get("startIndex")
|
||||
? parseInt(searchParams.get("startIndex") as string)
|
||||
: undefined,
|
||||
filter: searchParams.get("filter") as string,
|
||||
},
|
||||
};
|
||||
|
||||
const { status, data } = await dsyncController.requests.handle(scimRequest, handleEvents);
|
||||
|
||||
if (shouldLog) {
|
||||
console.log(
|
||||
"Response to SCIM",
|
||||
safeStringify({
|
||||
status,
|
||||
data,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(data, { status });
|
||||
}
|
||||
export const GET = defaultResponderForAppDir(getHandler);
|
||||
export const POST = defaultResponderForAppDir(postHandler);
|
||||
export const PATCH = defaultResponderForAppDir(patchHandler);
|
||||
export const DELETE = defaultResponderForAppDir(deleteHandler);
|
||||
export const PUT = defaultResponderForAppDir(putHandler);
|
||||
@@ -1,130 +0,0 @@
|
||||
import { cookies, headers } from "next/headers";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { BillingPlanService } from "@calcom/features/ee/billing/domain/billing-plans";
|
||||
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { WEBAPP_URL, WEBSITE_URL } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Contact } from "@calcom/web/modules/ee/support/lib/intercom/intercom";
|
||||
import { intercom } from "@calcom/web/modules/ee/support/lib/intercom/intercom";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: [`/api/support/conversation`] });
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const headersList = await headers();
|
||||
const cookiesList = await cookies();
|
||||
const legacyReq = buildLegacyRequest(headersList, cookiesList);
|
||||
|
||||
const session = await getServerSession({ req: legacyReq });
|
||||
if (!session?.user?.email) {
|
||||
return NextResponse.json({ error: "Unauthorized - No session found" }, { status: 401 });
|
||||
}
|
||||
|
||||
const intercomApiKey = process.env.INTERCOM_API_TOKEN;
|
||||
if (!intercomApiKey) {
|
||||
return NextResponse.json({ error: "Intercom API key not configured" }, { status: 500 });
|
||||
}
|
||||
|
||||
let contact: Contact;
|
||||
|
||||
const existingContact = await intercom.getContactByEmail(session.user.email);
|
||||
|
||||
if (existingContact.error) {
|
||||
return NextResponse.json(
|
||||
{ error: existingContact?.error ?? "Error fetching intercom contact for user" },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
|
||||
const { user } = session;
|
||||
|
||||
const membershipRepository = new MembershipRepository(prisma);
|
||||
const memberships = await membershipRepository.findAllMembershipsByUserIdForBilling({ userId: user.id });
|
||||
const billingPlanService = new BillingPlanService();
|
||||
const plan = await billingPlanService.getUserPlanByMemberships(memberships);
|
||||
|
||||
if (!existingContact.data) {
|
||||
const additionalUserInfo = await new UserRepository(prisma).getUserStats({ userId: session.user.id });
|
||||
const sumOfTeamEventTypes = additionalUserInfo?.teams.reduce(
|
||||
(sum, team) => sum + team.team.eventTypes.length,
|
||||
0
|
||||
);
|
||||
|
||||
const newContact = await intercom.createContact({
|
||||
email: session.user.email,
|
||||
external_id: session.user.id.toString(),
|
||||
name: session.user.name ?? session.user.email,
|
||||
type: "contact",
|
||||
custom_attributes: {
|
||||
user_name: user?.username,
|
||||
link: `${WEBSITE_URL}/${encodeURIComponent(user?.username ?? "")}`,
|
||||
admin_link: `${WEBAPP_URL}/settings/admin/users/${user?.id}/edit`,
|
||||
impersonate_user: `${WEBAPP_URL}/settings/admin/impersonation?username=${encodeURIComponent(
|
||||
user?.email ?? user?.username ?? ""
|
||||
)}`,
|
||||
locale: user?.locale,
|
||||
completed_onboarding: user?.completedOnboarding,
|
||||
is_logged_in: !!user,
|
||||
has_orgs_plan: !!user?.org,
|
||||
organization: user?.org?.slug,
|
||||
sum_of_bookings: additionalUserInfo?._count?.bookings,
|
||||
sum_of_calendars: additionalUserInfo?._count?.userLevelSelectedCalendars,
|
||||
sum_of_teams: additionalUserInfo?._count?.teams,
|
||||
sum_of_event_types: additionalUserInfo?._count?.eventTypes,
|
||||
sum_of_team_event_types: sumOfTeamEventTypes,
|
||||
Plan: plan,
|
||||
},
|
||||
});
|
||||
|
||||
if (newContact.error || !newContact.data) {
|
||||
return NextResponse.json(
|
||||
{ error: newContact.error ?? "Error creating contact from email" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
contact = newContact.data;
|
||||
} else {
|
||||
contact = existingContact.data;
|
||||
}
|
||||
|
||||
if (!contact) {
|
||||
return NextResponse.json({ error: "No contactId found" }, { status: 404 });
|
||||
}
|
||||
|
||||
try {
|
||||
const { message } = await req.json();
|
||||
|
||||
if (!message.trim()) {
|
||||
return NextResponse.json({ error: "Cannot start a conversation without message" }, { status: 400 });
|
||||
}
|
||||
|
||||
const conversation = await intercom.createConversation({
|
||||
body: message,
|
||||
from: {
|
||||
id: contact.id,
|
||||
type: "user",
|
||||
},
|
||||
});
|
||||
|
||||
if (conversation.error) {
|
||||
return NextResponse.json(
|
||||
{ error: conversation.error ?? "Error creating conversation" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Created conversation in Intercom" }, { status: 200 });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
log.error(`Error creating Intercom conversation:`, safeStringify(err));
|
||||
return NextResponse.json({ error: "Unexpected error occurred" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import crypto from "node:crypto";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
async function getHandler() {
|
||||
const headersList = await headers();
|
||||
const cookiesList = await cookies();
|
||||
const legacyReq = buildLegacyRequest(headersList, cookiesList);
|
||||
|
||||
const session = await getServerSession({ req: legacyReq });
|
||||
const secret = process.env.INTERCOM_SECRET;
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({ message: "user not authenticated" }, { status: 401 });
|
||||
}
|
||||
|
||||
if (!secret) {
|
||||
return NextResponse.json({ message: "Intercom Identity Verification secret not set" }, { status: 400 });
|
||||
}
|
||||
|
||||
const hmac = crypto.createHmac("sha256", secret);
|
||||
hmac.update(String(session.user.id));
|
||||
const hash = hmac.digest("hex");
|
||||
|
||||
return NextResponse.json({ hash });
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(getHandler);
|
||||
@@ -1,141 +0,0 @@
|
||||
import type { Params } from "app/_types";
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import type Stripe from "stripe";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getRequestedSlugError } from "@calcom/app-store/stripepayment/lib/team-billing";
|
||||
import { getBillingProviderService } from "@calcom/ee/billing/di/containers/Billing";
|
||||
import { getTeamBillingServiceFactory } from "@calcom/ee/billing/di/containers/Billing";
|
||||
import { extractBillingDataFromStripeSubscription } from "@calcom/features/ee/billing/lib/stripe-subscription-utils";
|
||||
import { Plan, SubscriptionStatus } from "@calcom/features/ee/billing/repository/billing/IBillingRepository";
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { teamMetadataStrictSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
const querySchema = z.object({
|
||||
team: z.string().transform((val) => parseInt(val)),
|
||||
session_id: z.string().min(1),
|
||||
});
|
||||
|
||||
async function getHandler(req: NextRequest, { params }: { params: Promise<Params> }) {
|
||||
try {
|
||||
const searchParams = req.nextUrl.searchParams;
|
||||
const { team: id, session_id } = querySchema.parse({
|
||||
team: (await params).team,
|
||||
session_id: searchParams.get("session_id"),
|
||||
});
|
||||
|
||||
const checkoutSession = await stripe.checkout.sessions.retrieve(session_id, {
|
||||
expand: ["subscription"],
|
||||
});
|
||||
if (!checkoutSession) {
|
||||
throw new HttpError({ statusCode: 404, message: "Checkout session not found" });
|
||||
}
|
||||
|
||||
const subscription = checkoutSession.subscription as Stripe.Subscription;
|
||||
if (checkoutSession.payment_status !== "paid") {
|
||||
throw new HttpError({ statusCode: 402, message: "Payment required" });
|
||||
}
|
||||
|
||||
let team = await prisma.team.findFirst({
|
||||
where: { metadata: { path: ["paymentId"], equals: checkoutSession.id } },
|
||||
});
|
||||
|
||||
let metadata;
|
||||
|
||||
if (!team) {
|
||||
const prevTeam = await prisma.team.findFirstOrThrow({ where: { id } });
|
||||
|
||||
metadata = teamMetadataStrictSchema.safeParse(prevTeam.metadata);
|
||||
if (!metadata.success) {
|
||||
throw new HttpError({ statusCode: 400, message: "Invalid team metadata" });
|
||||
}
|
||||
|
||||
const { requestedSlug, ...newMetadata } = metadata.data || {};
|
||||
team = await prisma.team.update({
|
||||
where: { id },
|
||||
data: {
|
||||
metadata: {
|
||||
...newMetadata,
|
||||
paymentId: checkoutSession.id,
|
||||
subscriptionId: subscription.id || null,
|
||||
subscriptionItemId: subscription.items.data[0].id || null,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const slug = prevTeam.slug || requestedSlug;
|
||||
if (slug) {
|
||||
try {
|
||||
team = await prisma.team.update({ where: { id }, data: { slug } });
|
||||
} catch (error) {
|
||||
const { message, statusCode } = getRequestedSlugError(error, slug);
|
||||
return NextResponse.json({ message }, { status: statusCode });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!metadata) {
|
||||
metadata = teamMetadataStrictSchema.safeParse(team.metadata);
|
||||
if (!metadata.success) {
|
||||
throw new HttpError({ statusCode: 400, message: "Invalid team metadata" });
|
||||
}
|
||||
}
|
||||
|
||||
if (subscription) {
|
||||
const billingProviderService = getBillingProviderService();
|
||||
const { subscriptionStart, subscriptionEnd, subscriptionTrialEnd } =
|
||||
billingProviderService.extractSubscriptionDates(subscription);
|
||||
|
||||
const { billingPeriod, pricePerSeat, paidSeats } =
|
||||
extractBillingDataFromStripeSubscription(subscription);
|
||||
|
||||
const teamBillingServiceFactory = getTeamBillingServiceFactory();
|
||||
const teamBillingService = teamBillingServiceFactory.init(team);
|
||||
await teamBillingService.saveTeamBilling({
|
||||
teamId: team.id,
|
||||
subscriptionId: subscription.id,
|
||||
subscriptionItemId: subscription.items.data[0].id,
|
||||
customerId:
|
||||
typeof checkoutSession.customer === "string"
|
||||
? checkoutSession.customer
|
||||
: checkoutSession.customer?.id || "",
|
||||
status: SubscriptionStatus.ACTIVE,
|
||||
planName: team.isOrganization ? Plan.ORGANIZATION : Plan.TEAM,
|
||||
subscriptionStart: subscriptionStart ?? undefined,
|
||||
subscriptionEnd: subscriptionEnd ?? undefined,
|
||||
subscriptionTrialEnd: subscriptionTrialEnd ?? undefined,
|
||||
billingPeriod,
|
||||
pricePerSeat,
|
||||
paidSeats,
|
||||
});
|
||||
}
|
||||
|
||||
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({ message: "Team upgraded successfully" });
|
||||
}
|
||||
|
||||
const redirectUrl = team?.isOrganization
|
||||
? `${WEBAPP_URL}/settings/organizations/profile?upgraded=true`
|
||||
: `${WEBAPP_URL}/settings/teams/${team.id}/profile?upgraded=true`;
|
||||
|
||||
return NextResponse.redirect(redirectUrl);
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
throw error;
|
||||
}
|
||||
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(getHandler);
|
||||
@@ -1,149 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import type Stripe from "stripe";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getBillingProviderService } from "@calcom/ee/billing/di/containers/Billing";
|
||||
import { getTeamBillingServiceFactory } from "@calcom/ee/billing/di/containers/Billing";
|
||||
import { extractBillingDataFromStripeSubscription } from "@calcom/features/ee/billing/lib/stripe-subscription-utils";
|
||||
import { Plan, SubscriptionStatus } from "@calcom/features/ee/billing/repository/billing/IBillingRepository";
|
||||
import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { MembershipSchema } from "@calcom/prisma/zod/modelSchema/MembershipSchema";
|
||||
import { TeamSchema } from "@calcom/prisma/zod/modelSchema/TeamSchema";
|
||||
|
||||
const querySchema = z.object({
|
||||
session_id: z.string().min(1),
|
||||
});
|
||||
|
||||
const checkoutSessionMetadataSchema = z.object({
|
||||
pendingPaymentTeamId: z.string().transform(Number),
|
||||
ownerId: z.string().transform(Number),
|
||||
});
|
||||
|
||||
type CheckoutSessionMetadata = z.infer<typeof checkoutSessionMetadataSchema>;
|
||||
|
||||
export const schemaTeamReadPublic = TeamSchema.omit({});
|
||||
export const schemaMembershipPublic = MembershipSchema.merge(z.object({ team: TeamSchema }).partial());
|
||||
|
||||
async function handler(request: NextRequest) {
|
||||
try {
|
||||
const { session_id } = querySchema.parse(Object.fromEntries(request.nextUrl.searchParams));
|
||||
|
||||
const checkoutSession = await getCheckoutSession(session_id);
|
||||
validateCheckoutSession(checkoutSession);
|
||||
const checkoutSessionSubscription = getCheckoutSessionSubscription(checkoutSession);
|
||||
const checkoutSessionMetadata = getCheckoutSessionMetadata(checkoutSession);
|
||||
|
||||
const finalizedTeam = await prisma.team.update({
|
||||
where: { id: checkoutSessionMetadata.pendingPaymentTeamId },
|
||||
data: {
|
||||
pendingPayment: false,
|
||||
members: {
|
||||
create: {
|
||||
userId: checkoutSessionMetadata.ownerId as number,
|
||||
role: MembershipRole.OWNER,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
metadata: {
|
||||
paymentId: checkoutSession.id,
|
||||
subscriptionId: checkoutSessionSubscription.id || null,
|
||||
subscriptionItemId: checkoutSessionSubscription.items.data[0].id || null,
|
||||
},
|
||||
},
|
||||
include: { members: true },
|
||||
});
|
||||
|
||||
if (checkoutSessionSubscription) {
|
||||
const billingService = getBillingProviderService();
|
||||
const { subscriptionStart, subscriptionEnd, subscriptionTrialEnd } =
|
||||
billingService.extractSubscriptionDates(checkoutSessionSubscription);
|
||||
|
||||
const { billingPeriod, pricePerSeat, paidSeats } =
|
||||
extractBillingDataFromStripeSubscription(checkoutSessionSubscription);
|
||||
|
||||
const teamBillingServiceFactory = getTeamBillingServiceFactory();
|
||||
const teamBillingService = teamBillingServiceFactory.init(finalizedTeam);
|
||||
await teamBillingService.saveTeamBilling({
|
||||
teamId: finalizedTeam.id,
|
||||
subscriptionId: checkoutSessionSubscription.id,
|
||||
subscriptionItemId: checkoutSessionSubscription.items.data[0].id,
|
||||
customerId: checkoutSessionSubscription.customer as string,
|
||||
// TODO: Implement true subscription status when webhook events are implemented
|
||||
status: SubscriptionStatus.ACTIVE,
|
||||
planName: Plan.TEAM,
|
||||
subscriptionStart: subscriptionStart ?? undefined,
|
||||
subscriptionEnd: subscriptionEnd ?? undefined,
|
||||
subscriptionTrialEnd: subscriptionTrialEnd ?? undefined,
|
||||
billingPeriod,
|
||||
pricePerSeat,
|
||||
paidSeats,
|
||||
});
|
||||
}
|
||||
|
||||
const response = {
|
||||
message: `Team created successfully. We also made user with ID=${checkoutSessionMetadata.ownerId} the owner of this team.`,
|
||||
team: schemaTeamReadPublic.parse(finalizedTeam),
|
||||
owner: schemaMembershipPublic.parse(finalizedTeam.members[0]),
|
||||
};
|
||||
|
||||
return NextResponse.json(response);
|
||||
} catch (error) {
|
||||
console.error("Error creating team:", error);
|
||||
|
||||
if (error instanceof HttpError) {
|
||||
return NextResponse.json({ message: error.message }, { status: error.statusCode });
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ message: error instanceof Error ? error.message : "An unexpected error occurred" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function getCheckoutSession(sessionId: string) {
|
||||
const checkoutSession = await stripe.checkout.sessions.retrieve(sessionId, {
|
||||
expand: ["subscription"],
|
||||
});
|
||||
if (!checkoutSession) throw new HttpError({ statusCode: 404, message: "Checkout session not found" });
|
||||
|
||||
return checkoutSession;
|
||||
}
|
||||
|
||||
function validateCheckoutSession(checkoutSession: Stripe.Response<Stripe.Checkout.Session>) {
|
||||
if (checkoutSession.payment_status !== "paid")
|
||||
throw new HttpError({ statusCode: 402, message: "Payment required" });
|
||||
}
|
||||
|
||||
function getCheckoutSessionSubscription(checkoutSession: Stripe.Response<Stripe.Checkout.Session>) {
|
||||
if (!checkoutSession.subscription) {
|
||||
throw new HttpError({
|
||||
statusCode: 400,
|
||||
message: "Can't publish team/org without subscription",
|
||||
});
|
||||
}
|
||||
|
||||
return checkoutSession.subscription as Stripe.Subscription;
|
||||
}
|
||||
|
||||
function getCheckoutSessionMetadata(
|
||||
checkoutSession: Stripe.Response<Stripe.Checkout.Session>
|
||||
): CheckoutSessionMetadata {
|
||||
const parseCheckoutSessionMetadata = checkoutSessionMetadataSchema.safeParse(checkoutSession.metadata);
|
||||
|
||||
if (!parseCheckoutSessionMetadata.success) {
|
||||
throw new HttpError({
|
||||
statusCode: 400,
|
||||
message: `Incorrect metadata in checkout session. Error: ${parseCheckoutSessionMetadata.error}`,
|
||||
});
|
||||
}
|
||||
|
||||
return parseCheckoutSessionMetadata.data;
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(handler);
|
||||
@@ -1,141 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import type Stripe from "stripe";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
getBillingProviderService,
|
||||
getTeamBillingServiceFactory,
|
||||
} from "@calcom/features/ee/billing/di/containers/Billing";
|
||||
import { extractBillingDataFromStripeSubscription } from "@calcom/features/ee/billing/lib/stripe-subscription-utils";
|
||||
import { Plan, SubscriptionStatus } from "@calcom/features/ee/billing/repository/billing/IBillingRepository";
|
||||
import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
const querySchema = z.object({
|
||||
session_id: z.string().min(1),
|
||||
});
|
||||
|
||||
const checkoutSessionMetadataSchema = z.object({
|
||||
teamName: z.string(),
|
||||
teamSlug: z.string(),
|
||||
userId: z.string().transform(Number),
|
||||
isOnboarding: z.string().optional(),
|
||||
});
|
||||
|
||||
const generateRandomString = () => {
|
||||
return Math.random().toString(36).substring(2, 10);
|
||||
};
|
||||
|
||||
async function getHandler(req: NextRequest) {
|
||||
const searchParams = req.nextUrl.searchParams;
|
||||
const { session_id } = querySchema.parse({
|
||||
session_id: searchParams.get("session_id"),
|
||||
});
|
||||
|
||||
const checkoutSession = await stripe.checkout.sessions.retrieve(session_id, {
|
||||
expand: ["subscription"],
|
||||
});
|
||||
if (!checkoutSession) throw new HttpError({ statusCode: 404, message: "Checkout session not found" });
|
||||
|
||||
const subscription = checkoutSession.subscription as Stripe.Subscription;
|
||||
|
||||
if (checkoutSession.payment_status !== "paid")
|
||||
throw new HttpError({ statusCode: 402, message: "Payment required" });
|
||||
|
||||
// Let's query to ensure that the team metadata carried over from the checkout session.
|
||||
const parseCheckoutSessionMetadata = checkoutSessionMetadataSchema.safeParse(checkoutSession.metadata);
|
||||
|
||||
if (!parseCheckoutSessionMetadata.success) {
|
||||
console.error(
|
||||
"Team metadata not found in checkout session",
|
||||
parseCheckoutSessionMetadata.error,
|
||||
checkoutSession.id
|
||||
);
|
||||
}
|
||||
|
||||
if (!checkoutSession.metadata?.userId) {
|
||||
throw new HttpError({
|
||||
statusCode: 400,
|
||||
message: "Can't publish team/org without userId",
|
||||
});
|
||||
}
|
||||
|
||||
const checkoutSessionMetadata = parseCheckoutSessionMetadata.success
|
||||
? parseCheckoutSessionMetadata.data
|
||||
: {
|
||||
teamName: checkoutSession?.metadata?.teamName ?? generateRandomString(),
|
||||
teamSlug: checkoutSession?.metadata?.teamSlug ?? generateRandomString(),
|
||||
userId: checkoutSession.metadata.userId,
|
||||
isOnboarding: checkoutSession.metadata.isOnboarding,
|
||||
};
|
||||
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: checkoutSessionMetadata.teamName,
|
||||
slug: checkoutSessionMetadata.teamSlug,
|
||||
members: {
|
||||
create: {
|
||||
userId: checkoutSessionMetadata.userId as number,
|
||||
role: MembershipRole.OWNER,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
metadata: {
|
||||
paymentId: checkoutSession.id,
|
||||
subscriptionId: subscription.id || null,
|
||||
subscriptionItemId: subscription.items.data[0].id || null,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (checkoutSession && subscription) {
|
||||
const billingProviderService = getBillingProviderService();
|
||||
const { subscriptionStart, subscriptionEnd, subscriptionTrialEnd } =
|
||||
billingProviderService.extractSubscriptionDates(subscription);
|
||||
|
||||
const { billingPeriod, pricePerSeat, paidSeats } = extractBillingDataFromStripeSubscription(subscription);
|
||||
|
||||
const teamBillingServiceFactory = getTeamBillingServiceFactory();
|
||||
const teamBillingService = teamBillingServiceFactory.init(team);
|
||||
await teamBillingService.saveTeamBilling({
|
||||
teamId: team.id,
|
||||
subscriptionId: subscription.id,
|
||||
subscriptionItemId: subscription.items.data[0].id,
|
||||
customerId: subscription.customer as string,
|
||||
// TODO: Implement true subscription status when webhook events are implemented
|
||||
status: SubscriptionStatus.ACTIVE,
|
||||
planName: Plan.TEAM,
|
||||
subscriptionStart: subscriptionStart ?? undefined,
|
||||
subscriptionEnd: subscriptionEnd ?? undefined,
|
||||
subscriptionTrialEnd: subscriptionTrialEnd ?? undefined,
|
||||
billingPeriod,
|
||||
pricePerSeat,
|
||||
paidSeats,
|
||||
});
|
||||
}
|
||||
|
||||
// Check if this is from onboarding flow and redirect accordingly
|
||||
const isOnboarding = checkoutSessionMetadata.isOnboarding === "true";
|
||||
|
||||
if (isOnboarding) {
|
||||
// Redirect to invite flow after payment for onboarding with teamId as query param
|
||||
const inviteUrl = new URL("/onboarding/teams/invite", WEBAPP_URL);
|
||||
inviteUrl.searchParams.set("teamId", team.id.toString());
|
||||
return NextResponse.redirect(inviteUrl, {
|
||||
status: 302,
|
||||
});
|
||||
}
|
||||
|
||||
// redirect to team screen
|
||||
return NextResponse.redirect(
|
||||
new URL(`/settings/teams/${team.id}/onboard-members?event=team_created`, WEBAPP_URL),
|
||||
{ status: 302 }
|
||||
);
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(getHandler);
|
||||
@@ -1,49 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { OAuth2Client } from "googleapis-common";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import getAppKeysFromSlug from "@calcom/app-store/_utils/getAppKeysFromSlug";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
|
||||
const scopes = [
|
||||
"https://www.googleapis.com/auth/admin.directory.user.readonly",
|
||||
"https://www.googleapis.com/auth/admin.directory.customer.readonly",
|
||||
];
|
||||
|
||||
async function getHandler(request: NextRequest) {
|
||||
try {
|
||||
// Get appKeys from google-calendar
|
||||
const { client_id, client_secret } = await getAppKeysFromSlug("google-calendar");
|
||||
|
||||
if (!client_id || typeof client_id !== "string")
|
||||
return NextResponse.json({ message: "Google client_id missing." }, { status: 400 });
|
||||
|
||||
if (!client_secret || typeof client_secret !== "string")
|
||||
return NextResponse.json({ message: "Google client_secret missing." }, { status: 400 });
|
||||
|
||||
// Get teamId from query params
|
||||
const teamId = request.nextUrl.searchParams.get("teamId");
|
||||
|
||||
// use different callback to normal calendar connection
|
||||
const redirect_uri = `${WEBAPP_URL}/api/teams/googleworkspace/callback`;
|
||||
const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uri);
|
||||
|
||||
const authUrl = oAuth2Client.generateAuthUrl({
|
||||
access_type: "offline",
|
||||
scope: scopes,
|
||||
prompt: "consent",
|
||||
state: JSON.stringify({ teamId }),
|
||||
});
|
||||
|
||||
return NextResponse.json({ url: authUrl });
|
||||
} catch (error) {
|
||||
console.error("Error generating Google Workspace auth URL:", error);
|
||||
return NextResponse.json(
|
||||
{ message: error instanceof Error ? error.message : "An unexpected error occurred" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(getHandler);
|
||||
@@ -1,89 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { OAuth2Client } from "googleapis-common";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import getAppKeysFromSlug from "@calcom/app-store/_utils/getAppKeysFromSlug";
|
||||
import { throwIfNotHaveAdminAccessToTeam } from "@calcom/app-store/_utils/throwIfNotHaveAdminAccessToTeam";
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
const stateSchema = z.object({
|
||||
teamId: z.string(),
|
||||
});
|
||||
|
||||
async function getHandler(request: NextRequest) {
|
||||
try {
|
||||
const headersList = await headers();
|
||||
const cookiesList = await cookies();
|
||||
const legacyReq = buildLegacyRequest(headersList, cookiesList);
|
||||
|
||||
const session = await getServerSession({ req: legacyReq });
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ message: "You must be logged in to do this" }, { status: 401 });
|
||||
}
|
||||
|
||||
const code = request.nextUrl.searchParams.get("code");
|
||||
const state = request.nextUrl.searchParams.get("state");
|
||||
|
||||
if (!state) {
|
||||
return NextResponse.json({ message: "No state provided" }, { status: 400 });
|
||||
}
|
||||
|
||||
const parsedState = stateSchema.parse(JSON.parse(state));
|
||||
const { teamId } = parsedState;
|
||||
|
||||
await throwIfNotHaveAdminAccessToTeam({
|
||||
teamId: Number(teamId) ?? null,
|
||||
userId: session.user.id,
|
||||
});
|
||||
|
||||
if (!code || typeof code !== "string") {
|
||||
return NextResponse.json({ message: "`code` must be a string" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { client_id, client_secret } = await getAppKeysFromSlug("google-calendar");
|
||||
|
||||
if (!client_id || typeof client_id !== "string")
|
||||
return NextResponse.json({ message: "Google client_id missing." }, { status: 400 });
|
||||
|
||||
if (!client_secret || typeof client_secret !== "string")
|
||||
return NextResponse.json({ message: "Google client_secret missing." }, { status: 400 });
|
||||
|
||||
const redirect_uri = `${WEBAPP_URL}/api/teams/googleworkspace/callback`;
|
||||
const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uri);
|
||||
|
||||
const credentials = await oAuth2Client.getToken(code);
|
||||
|
||||
await prisma.credential.create({
|
||||
data: {
|
||||
type: "google_workspace_directory",
|
||||
key: credentials.res?.data,
|
||||
userId: session.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
let redirectUrl = `${WEBAPP_URL}/settings`;
|
||||
|
||||
if (teamId) {
|
||||
redirectUrl = `${WEBAPP_URL}/settings/teams/${teamId}/members?inviteModal=true&bulk=true`;
|
||||
}
|
||||
|
||||
const safeRedirectUrl = getSafeRedirectUrl(redirectUrl) ?? `${WEBAPP_URL}/teams`;
|
||||
return NextResponse.redirect(safeRedirectUrl);
|
||||
} catch (error) {
|
||||
console.error("Error in Google Workspace callback:", error);
|
||||
|
||||
// Redirect to teams page on error
|
||||
return NextResponse.redirect(`${WEBAPP_URL}/teams`);
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = defaultResponderForAppDir(getHandler);
|
||||
@@ -1,14 +1,11 @@
|
||||
import { checkUsername } from "@calcom/features/profile/lib/checkUsername";
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import { checkUsername } from "@calcom/features/profile/lib/checkUsername";
|
||||
|
||||
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
||||
|
||||
const bodySchema = z.object({
|
||||
username: z.string(),
|
||||
orgSlug: z.string().optional(),
|
||||
@@ -22,7 +19,8 @@ async function postHandler(request: NextRequest) {
|
||||
const legacyReq = buildLegacyRequest(await headers(), await cookies());
|
||||
|
||||
// Get current org domain from request headers
|
||||
const { currentOrgDomain } = orgDomainConfig(legacyReq);
|
||||
const currentOrgDomain = null;
|
||||
const isValidOrgDomain = false;
|
||||
|
||||
const result = await checkUsername(username, currentOrgDomain || orgSlug);
|
||||
|
||||
|
||||
@@ -185,7 +185,7 @@ describe("verify-booking-token route", () => {
|
||||
});
|
||||
|
||||
describe("GET handler", () => {
|
||||
it("should process rejection via GET (for email clients that don't support POST)", async () => {
|
||||
it("should redirect rejection via GET with error requiring POST method", async () => {
|
||||
createMockBooking({
|
||||
id: 1,
|
||||
uid: "abc123",
|
||||
@@ -212,16 +212,9 @@ describe("verify-booking-token route", () => {
|
||||
|
||||
expect(redirectUrl.origin).toBe(EXPECTED_REDIRECT_ORIGIN);
|
||||
expect(redirectUrl.pathname).toBe("/booking/abc123");
|
||||
expect(redirectUrl.searchParams.get("error")).toBeNull();
|
||||
expect(mockConfirmHandler).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
input: expect.objectContaining({
|
||||
bookingId: 1,
|
||||
confirmed: false,
|
||||
actionSource: "MAGIC_LINK",
|
||||
}),
|
||||
})
|
||||
);
|
||||
// GET handler does not process rejections — requires POST
|
||||
expect(redirectUrl.searchParams.get("error")).toBe("Rejection requires POST method");
|
||||
expect(mockConfirmHandler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should redirect with error when query params are invalid (missing action)", async () => {
|
||||
@@ -376,7 +369,6 @@ describe("verify-booking-token route", () => {
|
||||
bookingId: 1,
|
||||
confirmed: true,
|
||||
emailsEnabled: true,
|
||||
actionSource: "MAGIC_LINK",
|
||||
}),
|
||||
})
|
||||
);
|
||||
@@ -452,8 +444,6 @@ describe("verify-booking-token route", () => {
|
||||
confirmed: false,
|
||||
reason: "test",
|
||||
emailsEnabled: true,
|
||||
actionSource: "MAGIC_LINK",
|
||||
actor: { type: "user", id: "test-uuid" },
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { distributedTracing } from "@calcom/lib/tracing/factory";
|
||||
import prisma from "@calcom/prisma";
|
||||
@@ -28,6 +27,16 @@ async function getHandler(request: NextRequest) {
|
||||
try {
|
||||
const { action, token, bookingUid, userId } = querySchema.parse(queryParams);
|
||||
|
||||
if (action === DirectAction.REJECT) {
|
||||
// Rejections should use POST method
|
||||
return NextResponse.redirect(
|
||||
new URL(
|
||||
`/booking/${bookingUid}?error=${encodeURIComponent("Rejection requires POST method")}`,
|
||||
WEBAPP_URL
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return await handleBookingAction(action, token, bookingUid, userId, request, undefined);
|
||||
} catch {
|
||||
const bookingUid = queryParams.bookingUid || "";
|
||||
@@ -106,9 +115,6 @@ async function handleBookingAction(
|
||||
/** Ignored reason input unless we're rejecting */
|
||||
reason: action === DirectAction.REJECT ? reason : undefined,
|
||||
emailsEnabled: true,
|
||||
actionSource: "MAGIC_LINK",
|
||||
actor: makeUserActor(user.uuid),
|
||||
impersonatedByUserUuid: null,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,905 +0,0 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
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";
|
||||
|
||||
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_type?: string;
|
||||
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();
|
||||
const mockSendCreditBalanceLimitReachedEmails = vi.fn();
|
||||
const mockSendCreditBalanceLowWarningEmails = vi.fn();
|
||||
|
||||
vi.mock("@calcom/features/ee/billing/credit-service", () => ({
|
||||
CreditService: vi.fn().mockImplementation(function () {
|
||||
return {
|
||||
hasAvailableCredits: mockHasAvailableCredits,
|
||||
chargeCredits: mockChargeCredits,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/emails/email-manager", () => ({
|
||||
sendCreditBalanceLimitReachedEmails: (...args: unknown[]) =>
|
||||
mockSendCreditBalanceLimitReachedEmails(...args),
|
||||
sendCreditBalanceLowWarningEmails: (...args: unknown[]) => mockSendCreditBalanceLowWarningEmails(...args),
|
||||
}));
|
||||
|
||||
const mockFindByPhoneNumber = vi.fn();
|
||||
const mockFindByProviderAgentId = vi.fn();
|
||||
|
||||
vi.mock("@calcom/features/calAIPhone/repositories/PrismaPhoneNumberRepository", () => ({
|
||||
PrismaPhoneNumberRepository: vi.fn().mockImplementation(function () {
|
||||
return {
|
||||
findByPhoneNumber: mockFindByPhoneNumber,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calAIPhone/repositories/PrismaAgentRepository", () => ({
|
||||
PrismaAgentRepository: vi.fn().mockImplementation(function () {
|
||||
return {
|
||||
findByProviderAgentId: mockFindByProviderAgentId,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
mockFindByPhoneNumber.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",
|
||||
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
mockFindByPhoneNumber.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",
|
||||
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
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(mockFindByPhoneNumber).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle phone number not found", async () => {
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
mockFindByPhoneNumber.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,
|
||||
};
|
||||
|
||||
mockFindByPhoneNumber.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,
|
||||
};
|
||||
|
||||
mockFindByPhoneNumber.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-/),
|
||||
creditFor: CreditUsageType.CAL_AI_PHONE_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,
|
||||
};
|
||||
mockFindByPhoneNumber.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,
|
||||
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
|
||||
}) // 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,
|
||||
};
|
||||
mockFindByPhoneNumber.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",
|
||||
creditFor: CreditUsageType.CAL_AI_PHONE_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,
|
||||
};
|
||||
mockFindByPhoneNumber.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,
|
||||
};
|
||||
mockFindByPhoneNumber.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");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Web Call Tests", () => {
|
||||
const mockAgent: Pick<
|
||||
Agent,
|
||||
| "id"
|
||||
| "name"
|
||||
| "providerAgentId"
|
||||
| "enabled"
|
||||
| "userId"
|
||||
| "teamId"
|
||||
| "createdAt"
|
||||
| "updatedAt"
|
||||
| "inboundEventTypeId"
|
||||
> = {
|
||||
id: "agent-123",
|
||||
name: "Test Agent",
|
||||
providerAgentId: "agent_5e3e0d29d692172c2c24d8f9a7",
|
||||
enabled: true,
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
inboundEventTypeId: null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(Retell.verify).mockReturnValue(true);
|
||||
});
|
||||
|
||||
it("should process web call with valid agent and charge credits", async () => {
|
||||
mockFindByProviderAgentId.mockResolvedValue(mockAgent);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "call_bcd94f5a50832873a5fd68cb1aa",
|
||||
call_type: "web_call",
|
||||
agent_id: "agent_5e3e0d29d692172c2c24d8f9a7",
|
||||
call_status: "ended",
|
||||
start_timestamp: 1757673314024,
|
||||
end_timestamp: 1757673321010,
|
||||
call_cost: {
|
||||
total_duration_seconds: 7,
|
||||
combined_cost: 1.3416667,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
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(mockFindByProviderAgentId).toHaveBeenCalledWith({
|
||||
providerAgentId: "agent_5e3e0d29d692172c2c24d8f9a7",
|
||||
});
|
||||
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 1,
|
||||
teamId: undefined,
|
||||
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,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle web call with team agent", async () => {
|
||||
const teamAgent = { ...mockAgent, userId: 2, teamId: 10, inboundEventTypeId: null };
|
||||
mockFindByProviderAgentId.mockResolvedValue(teamAgent);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "web-call-team",
|
||||
call_type: "web_call",
|
||||
agent_id: "agent_team_123",
|
||||
call_status: "ended",
|
||||
start_timestamp: 1757673314024,
|
||||
call_cost: {
|
||||
total_duration_seconds: 60,
|
||||
combined_cost: 2.0,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockChargeCredits).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: 2,
|
||||
teamId: 10,
|
||||
credits: 29, // 60 seconds = 1 minute * $0.29 = 29 credits
|
||||
callDuration: 60,
|
||||
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle web call without from_number", async () => {
|
||||
mockFindByProviderAgentId.mockResolvedValue(mockAgent);
|
||||
mockChargeCredits.mockResolvedValue(undefined);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "web-call-no-phone",
|
||||
agent_id: "agent_5e3e0d29d692172c2c24d8f9a7",
|
||||
call_status: "ended",
|
||||
start_timestamp: 1757673314024,
|
||||
call_cost: {
|
||||
total_duration_seconds: 30,
|
||||
combined_cost: 1.0,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockFindByProviderAgentId).toHaveBeenCalled();
|
||||
expect(mockFindByPhoneNumber).not.toHaveBeenCalled();
|
||||
expect(mockChargeCredits).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle web call with missing agent_id", async () => {
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "web-call-no-agent",
|
||||
call_type: "web_call",
|
||||
call_status: "ended",
|
||||
call_cost: {
|
||||
total_duration_seconds: 30,
|
||||
combined_cost: 1.0,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockFindByProviderAgentId).not.toHaveBeenCalled();
|
||||
expect(mockChargeCredits).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle web call with agent not found", async () => {
|
||||
mockFindByProviderAgentId.mockResolvedValue(null);
|
||||
|
||||
const body: RetellWebhookBody = {
|
||||
event: "call_analyzed",
|
||||
call: {
|
||||
call_id: "web-call-no-agent-found",
|
||||
call_type: "web_call",
|
||||
agent_id: "non-existent-agent",
|
||||
call_status: "ended",
|
||||
start_timestamp: 1757673314024,
|
||||
call_cost: {
|
||||
total_duration_seconds: 30,
|
||||
combined_cost: 1.0,
|
||||
},
|
||||
// Web calls don't have from_number, to_number, direction
|
||||
},
|
||||
};
|
||||
|
||||
const request = createMockRequest(body, "valid-signature");
|
||||
const response = await callPOST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mockFindByProviderAgentId).toHaveBeenCalledWith({
|
||||
providerAgentId: "non-existent-agent",
|
||||
});
|
||||
expect(mockChargeCredits).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,303 +0,0 @@
|
||||
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 { PrismaAgentRepository } from "@calcom/features/calAIPhone/repositories/PrismaAgentRepository";
|
||||
import { PrismaPhoneNumberRepository } from "@calcom/features/calAIPhone/repositories/PrismaPhoneNumberRepository";
|
||||
import { CreditService } from "@calcom/features/ee/billing/credit-service";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
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(),
|
||||
// Make phone fields optional for web calls
|
||||
from_number: z.string().optional(),
|
||||
to_number: z.string().optional(),
|
||||
direction: z.enum(["inbound", "outbound"]).optional(),
|
||||
call_type: z.string().optional(),
|
||||
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(),
|
||||
});
|
||||
|
||||
type RetellCallData = z.infer<typeof RetellWebhookSchema>["call"];
|
||||
|
||||
async function chargeCreditsForCall({
|
||||
userId,
|
||||
teamId,
|
||||
callCost,
|
||||
callId,
|
||||
callDuration,
|
||||
}: {
|
||||
userId?: number;
|
||||
teamId?: number;
|
||||
callCost: number;
|
||||
callId: string;
|
||||
callDuration: number;
|
||||
}) {
|
||||
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 = callDuration / 60;
|
||||
const calculatedCallCost = durationInMinutes * safeRatePerMinute;
|
||||
// Convert to cents and round up to ensure we don't undercharge
|
||||
const creditsToDeduct = Math.ceil(calculatedCallCost * 100);
|
||||
|
||||
const creditService = new CreditService();
|
||||
|
||||
try {
|
||||
await creditService.chargeCredits({
|
||||
userId: userId ?? undefined,
|
||||
teamId: teamId ?? undefined,
|
||||
credits: creditsToDeduct,
|
||||
callDuration: callDuration,
|
||||
creditFor: CreditUsageType.CAL_AI_PHONE_CALL,
|
||||
externalRef: `retell:${callId}`,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Successfully charged ${creditsToDeduct} credits (${callDuration}s at $${safeRatePerMinute}/min) for ${
|
||||
teamId ? `team:${teamId}` : ""
|
||||
} ${userId ? `user:${userId}` : ""}, call ${callId}`,
|
||||
};
|
||||
} catch (e) {
|
||||
log.error("Error charging credits for Retell AI call", {
|
||||
error: e,
|
||||
call_id: callId,
|
||||
call_cost: callCost,
|
||||
userId,
|
||||
teamId,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
message: `Error charging credits for Retell AI call: ${
|
||||
e instanceof Error ? e.message : "Unknown error"
|
||||
}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCallAnalyzed(callData: RetellCallData) {
|
||||
const { from_number, call_id, call_cost, call_type, agent_id } = 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.info(
|
||||
`Invalid or missing call_cost.total_duration_seconds for call ${call_id}: ${safeStringify(call_cost)}`
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
message: `Invalid or missing call_cost.total_duration_seconds for call ${call_id}`,
|
||||
};
|
||||
}
|
||||
|
||||
let userId: number | undefined;
|
||||
let teamId: number | undefined;
|
||||
|
||||
// Handle web calls vs phone calls
|
||||
if (call_type === "web_call" || !from_number) {
|
||||
if (!agent_id) {
|
||||
log.error(`Web call ${call_id} missing agent_id, cannot charge credits`);
|
||||
return {
|
||||
success: false,
|
||||
message: `Web call ${call_id} missing agent_id, cannot charge credits`,
|
||||
};
|
||||
}
|
||||
|
||||
const agentRepo = new PrismaAgentRepository(prisma);
|
||||
const agent = await agentRepo.findByProviderAgentId({
|
||||
providerAgentId: agent_id,
|
||||
});
|
||||
|
||||
if (!agent) {
|
||||
log.error(`No agent found for providerAgentId ${agent_id}, call ${call_id}`);
|
||||
return {
|
||||
success: false,
|
||||
message: `No agent found for providerAgentId ${agent_id}, call ${call_id}`,
|
||||
};
|
||||
}
|
||||
|
||||
userId = agent.userId ?? undefined;
|
||||
teamId = agent.team?.parentId ?? agent.teamId ?? undefined;
|
||||
|
||||
log.info(`Processing web call ${call_id} for agent ${agent_id}, user ${userId}, team ${teamId}`);
|
||||
} else {
|
||||
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
|
||||
const phoneNumber = await phoneNumberRepo.findByPhoneNumber({
|
||||
phoneNumber: from_number,
|
||||
});
|
||||
|
||||
if (!phoneNumber) {
|
||||
const msg = `No phone number found for ${from_number}, call ${call_id}`;
|
||||
log.error(msg);
|
||||
return { success: false, message: msg };
|
||||
}
|
||||
|
||||
userId = phoneNumber.userId ?? undefined;
|
||||
teamId = phoneNumber.team?.parentId ?? phoneNumber.teamId ?? undefined;
|
||||
|
||||
log.info(`Processing phone call ${call_id} from ${from_number}, user ${userId}, team ${teamId}`);
|
||||
}
|
||||
|
||||
if (!userId && !teamId) {
|
||||
log.error(`Call ${call_id} has no associated user or team`);
|
||||
return {
|
||||
success: false,
|
||||
message: `Call ${call_id} has no associated user or team`,
|
||||
};
|
||||
}
|
||||
|
||||
return await chargeCreditsForCall({
|
||||
userId,
|
||||
teamId,
|
||||
callCost: call_cost.combined_cost || 0,
|
||||
callId: call_id,
|
||||
callDuration: call_cost.total_duration_seconds,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
// Skip inbound calls (only for phone calls, web calls don't have direction)
|
||||
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}`, {
|
||||
call_id: 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,5 +0,0 @@
|
||||
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
||||
|
||||
import handleSMSResponse from "@calcom/features/ee/workflows/api/handleSMSResponse";
|
||||
|
||||
export const POST = defaultResponderForAppDir(handleSMSResponse);
|
||||
Reference in new issue
Block a user