refactor: Remove circular deps between @calcom/lib and @calcom/features [1] (#24399)

* add eslint config

* migrate autoLock to features

* migrate teamService to features

* migrate userCreationService

* migrate insights services to features

* migrate ProfileRepository

* update imports

* migrate filter segmen tests

* migrate filter segment repository

* migrate getBusyTimes

* migrate getLocaleFromRequest

* refactor csvUtils

* make filename clearer

* migrate getLuckyUser integration test

* migrate autoLock test to features

* wip

* refactors

* migrate useBookerUrl

* migrate more

* wip

* Migrate eventTypeRepository

* membership repository

* update imports

* update imports

* migrate

* move organization repository

* update imports

* update imports

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix tests

* fix type checks

* fix

* fix

* migrate

* update imports

* fix tests

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix
This commit is contained in:
Benny Joo authored and GitHub committed 2025-10-13 12:01:02 -03:00
1 parent 1dc20e3aec
commit ff38d6c7db
339 files changed
+876 -833

No files matched your search

@@ -5,7 +5,7 @@ import type { UIEvent } from "react";
import { useEffect, useRef, useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { UserAdminTeams } from "@calcom/lib/server/repository/user";
import type { UserAdminTeams } from "@calcom/features/users/repositories/UserRepository";
import type { AppCategories } from "@calcom/prisma/client";
import type { AppFrontendPayload as App } from "@calcom/types/App";
import type { CredentialFrontendPayload as Credential } from "@calcom/types/Credential";
@@ -11,7 +11,7 @@ import { AppOnboardingSteps } from "@calcom/lib/apps/appOnboardingSteps";
import { getAppOnboardingUrl } from "@calcom/lib/apps/getAppOnboardingUrl";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { UserAdminTeams } from "@calcom/lib/server/repository/user";
import type { UserAdminTeams } from "@calcom/features/users/repositories/UserRepository";
import type { AppFrontendPayload as App } from "@calcom/types/App";
import type { CredentialFrontendPayload as Credential } from "@calcom/types/Credential";
import classNames from "@calcom/ui/classNames";
@@ -0,0 +1,23 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import parser from "accept-language-parser";
import type { GetServerSidePropsContext, NextApiRequest } from "next";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
type Maybe<T> = T | null | undefined;
const { i18n } = require("@calcom/config/next-i18next.config");
export async function getLocaleFromRequest(
req: NextApiRequest | GetServerSidePropsContext["req"]
): Promise<string> {
const session = await getServerSession({ req });
if (session?.user?.locale) return session.user.locale;
let preferredLocale: string | null | undefined;
if (req.headers["accept-language"]) {
preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"], {
loose: true,
}) as Maybe<string>;
}
return preferredLocale ?? i18n.defaultLocale;
}
@@ -8,7 +8,7 @@ import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { DeploymentRepository } from "@calcom/lib/server/repository/deployment";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import prisma from "@calcom/prisma";
const log = logger.getSubLogger({ prefix: ["getServerSession"] });
@@ -34,9 +34,9 @@ import { safeStringify } from "@calcom/lib/safeStringify";
import { hashEmail } from "@calcom/lib/server/PiiHasher";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import { DeploymentRepository } from "@calcom/lib/server/repository/deployment";
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
import type { Membership, Team } from "@calcom/prisma/client";
@@ -2,6 +2,7 @@ import { cookies, headers } from "next/headers";
import { NextResponse } from "next/server";
import { getPremiumMonthlyPlanPriceId } from "@calcom/app-store/stripepayment/lib/utils";
import { getLocaleFromRequest } from "@calcom/features/auth/lib/getLocaleFromRequest";
import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
import { prefillAvatar } from "@calcom/features/auth/signup/utils/prefillAvatar";
@@ -9,7 +10,6 @@ import { StripeBillingService } from "@calcom/features/ee/billing/stripe-billlin
import { checkIfEmailIsBlockedInWatchlistController } from "@calcom/features/watchlist/operations/check-if-email-in-watchlist.controller";
import { hashPassword } from "@calcom/lib/auth/hashPassword";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { getLocaleFromRequest } from "@calcom/lib/getLocaleFromRequest";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import type { CustomNextApiHandler } from "@calcom/lib/server/username";
@@ -1,5 +1,5 @@
import { updateNewTeamMemberEventTypes } from "@calcom/features/ee/teams/lib/queries";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
import { prisma } from "@calcom/prisma";
import type { Team, User, OrganizationSettings } from "@calcom/prisma/client";
import { MembershipRole } from "@calcom/prisma/enums";
@@ -1,5 +1,5 @@
import { updateNewTeamMemberEventTypes } from "@calcom/features/ee/teams/lib/queries";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
import { prisma } from "@calcom/prisma";
import type { Team, OrganizationSettings } from "@calcom/prisma/client";
@@ -4,7 +4,13 @@ import { z } from "zod";
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import {
getBusyTimesFromLimits,
getBusyTimesFromTeamLimits,
} from "@calcom/features/busyTimes/lib/getBusyTimesFromLimits";
import { getBusyTimesService } from "@calcom/features/di/containers/BusyTimes";
import { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
import type { IRedisService } from "@calcom/features/redis/IRedisService";
import { getWorkingHours } from "@calcom/lib/availability";
import type { DateOverride, WorkingHours } from "@calcom/lib/date-ranges";
@@ -14,16 +20,10 @@ import { ErrorCode } from "@calcom/lib/errorCodes";
import { HttpError } from "@calcom/lib/http-error";
import { parseBookingLimit } from "@calcom/lib/intervalLimits/isBookingLimits";
import { parseDurationLimit } from "@calcom/lib/intervalLimits/isDurationLimits";
import {
getBusyTimesFromLimits,
getBusyTimesFromTeamLimits,
} from "@calcom/lib/intervalLimits/server/getBusyTimesFromLimits";
import { getPeriodStartDatesBetween as getPeriodStartDatesBetweenUtil } from "@calcom/lib/intervalLimits/utils/getPeriodStartDatesBetween";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { withReporting } from "@calcom/lib/sentryWrapper";
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
import { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
import type { PrismaOOORepository } from "@calcom/lib/server/repository/ooo";
import type {
Booking,
@@ -8,12 +8,11 @@ import getLocationOptionsForSelect from "@calcom/features/bookings/lib/getLocati
import { FormBuilderField } from "@calcom/features/form-builder/FormBuilderField";
import { fieldTypesConfigMap } from "@calcom/features/form-builder/fieldTypes";
import { fieldsThatSupportLabelAsSafeHtml } from "@calcom/features/form-builder/fieldsThatSupportLabelAsSafeHtml";
import { SystemField } from "@calcom/lib/SystemField";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import type { RouterOutputs } from "@calcom/trpc/react";
import { SystemField } from "../../../lib/SystemField";
type Fields = NonNullable<RouterOutputs["viewer"]["public"]["event"]>["bookingFields"];
export const BookingFields = ({
fields,
@@ -15,7 +15,7 @@ import { createBooking, createRecurringBooking, createInstantBooking } from "@ca
import type { GetBookingType } from "@calcom/features/bookings/lib/get-booking";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { getFullName } from "@calcom/features/form-builder/utils";
import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
import { useBookingSuccessRedirect } from "@calcom/features/bookings/lib/bookingSuccessRedirect";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { localStorage } from "@calcom/lib/webstorage";
@@ -2,9 +2,9 @@ import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { getBookerBaseUrlSync } from "@calcom/features/ee/organizations/lib/getBookerBaseUrlSync";
import { getTeamUrlSync } from "@calcom/features/ee/organizations/lib/getTeamUrlSync";
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
import { getBookerBaseUrlSync } from "@calcom/lib/getBookerUrl/client";
import { getTeamUrlSync } from "@calcom/lib/getBookerUrl/client";
import { SchedulingType } from "@calcom/prisma/enums";
import { AvatarGroup } from "@calcom/ui/components/avatar";
@@ -0,0 +1,12 @@
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import { WEBAPP_URL, WEBSITE_URL } from "@calcom/lib/constants";
export const useBookerUrl = () => {
const orgBranding = useOrgBranding();
return orgBranding?.fullDomain ?? WEBSITE_URL ?? WEBAPP_URL;
};
export const useEmbedBookerUrl = () => {
const orgBranding = useOrgBranding();
return orgBranding?.fullDomain ?? WEBAPP_URL;
};
@@ -11,9 +11,9 @@ import getApps from "@calcom/app-store/utils";
import { createEvent, updateEvent, deleteEvent } from "@calcom/features/calendars/lib/CalendarManager";
import { createMeeting, updateMeeting, deleteMeeting } from "@calcom/features/conferencing/lib/videoClient";
import CrmManager from "@calcom/features/crmManager/crmManager";
import CRMScheduler from "@calcom/features/crmManager/crmScheduler";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { getUid } from "@calcom/lib/CalEventParser";
import CRMScheduler from "@calcom/lib/crmManager/tasker/crmScheduler";
import { symmetricDecrypt } from "@calcom/lib/crypto";
import { isDelegationCredential } from "@calcom/lib/delegationCredential";
import logger from "@calcom/lib/logger";
@@ -1,18 +0,0 @@
import { z } from "zod";
export const SystemField = z.enum([
"name",
"email",
"location",
"title",
"notes",
"guests",
"rescheduleReason",
"smsReminderNumber",
"attendeePhoneNumber",
"aiAgentCallPhoneNumber",
]);
export const SMS_REMINDER_NUMBER_FIELD = "smsReminderNumber";
export const CAL_AI_AGENT_PHONE_NUMBER_FIELD = "aiAgentCallPhoneNumber";
export const TITLE_FIELD = "title";
@@ -0,0 +1,528 @@
import { describe, it, expect, vi, beforeEach, test } from "vitest";
import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { navigateInTopWindow } from "@calcom/lib/navigateInTopWindow";
import { useBookingSuccessRedirect, getNewSearchParams } from "./bookingSuccessRedirect";
const mockPush = vi.fn();
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: mockPush,
}),
}));
vi.mock("@calcom/lib/navigateInTopWindow", () => ({
navigateInTopWindow: vi.fn(),
}));
vi.mock("@calcom/lib/hooks/useCompatSearchParams", () => ({
useCompatSearchParams: vi.fn(),
}));
vi.mock("@calcom/embed-core/embed-iframe", () => ({
useIsEmbed: vi.fn(),
}));
// Test data constants
const EMBED_PARAMS = ["embed", "layout", "embedType", "ui.color-scheme"];
const WEBAPP_PARAMS = ["overlayCalendar"];
// Helper function to create a mock booking with sensible defaults
type MockBooking = Pick<
BookingResponse,
| "uid"
| "title"
| "description"
| "startTime"
| "endTime"
| "location"
| "attendees"
| "user"
| "responses"
>;
const createMockBooking = (overrides: Partial<MockBooking> = {}): MockBooking => ({
uid: "test-booking-uid",
title: "Test Meeting",
description: "Test Description",
startTime: new Date("2024-01-01T10:00:00Z"),
endTime: new Date("2024-01-01T11:00:00Z"),
location: "Zoom",
attendees: [
{
id: 1,
name: "John Doe",
email: "[email protected]",
timeZone: "UTC",
locale: "en",
phoneNumber: "+1234567890",
bookingId: 1,
noShow: false,
},
],
user: {
email: null,
name: "Jane Host",
timeZone: "UTC",
username: "jane-host",
},
responses: {
name: "John Doe",
phone: "+1234567890",
},
...overrides,
});
// Helper to assert multiple params are null
const assertParamsNull = (result: URLSearchParams, params: string[]) => {
params.forEach((param) => expect(result.get(param)).toBeNull());
};
// Helper to assert multiple params have specific values
const assertParamsEqual = (result: URLSearchParams, paramValues: Record<string, string>) => {
Object.entries(paramValues).forEach(([key, value]) => {
expect(result.get(key)).toBe(value);
});
};
// Helper to assert URL search params
const assertUrlSearchParams = (url: string, expectedParams: Record<string, string | null>) => {
const urlObject = new URL(url);
Object.entries(expectedParams).forEach(([key, value]) => {
if (value === null) {
expect(urlObject.searchParams.get(key)).toBeNull();
} else {
expect(urlObject.searchParams.get(key)).toBe(value);
}
});
};
describe("getNewSearchParams", () => {
describe("filtering internal params", () => {
describe("when filterInternalParams is true", () => {
test.each([
{
name: "filters embed params from searchParams",
searchParams: {
embed: "true",
layout: "month_view",
embedType: "inline",
"ui.color-scheme": "dark",
foo: "bar",
},
query: { bookingId: "123" },
expectedNull: ["embed", "layout", "embedType", "ui.color-scheme"],
expectedPresent: { foo: "bar", bookingId: "123" },
},
{
name: "filters webapp params from searchParams",
searchParams: { overlayCalendar: "true", foo: "bar" },
query: { bookingId: "123" },
expectedNull: ["overlayCalendar"],
expectedPresent: { foo: "bar", bookingId: "123" },
},
{
name: "filters both embed and webapp params from searchParams",
searchParams: { embed: "true", layout: "month_view", overlayCalendar: "true", foo: "bar" },
query: { bookingId: "123" },
expectedNull: ["embed", "layout", "overlayCalendar"],
expectedPresent: { foo: "bar", bookingId: "123" },
},
])("$name", ({ searchParams, query, expectedNull, expectedPresent }) => {
const result = getNewSearchParams({
query,
searchParams: new URLSearchParams(searchParams),
filterInternalParams: true,
});
assertParamsNull(result, expectedNull);
assertParamsEqual(result, expectedPresent);
});
test.each([
{
name: "filters embed params from query object",
query: {
bookingId: "789",
embed: "namespace",
layout: "month_view",
embedType: "inline",
"ui.color-scheme": "dark",
test: "value",
},
expectedNull: ["embed", "layout", "embedType", "ui.color-scheme"],
expectedPresent: { bookingId: "789", test: "value" },
},
{
name: "filters webapp params from query object",
query: {
bookingId: "789",
overlayCalendar: "true",
test: "value",
},
expectedNull: ["overlayCalendar"],
expectedPresent: { bookingId: "789", test: "value" },
},
])("$name", ({ query, expectedNull, expectedPresent }) => {
const result = getNewSearchParams({ query, filterInternalParams: true });
assertParamsNull(result, expectedNull);
assertParamsEqual(result, expectedPresent);
});
});
describe("when filterInternalParams is false", () => {
test.each([
{
name: "preserves embed params",
searchParams: { embed: "true", layout: "month_view", foo: "bar" },
query: { bookingId: "456" },
expectedPresent: { embed: "true", layout: "month_view", foo: "bar", bookingId: "456" },
},
{
name: "preserves webapp params",
searchParams: { overlayCalendar: "true", foo: "bar" },
query: { bookingId: "456" },
expectedPresent: { overlayCalendar: "true", foo: "bar", bookingId: "456" },
},
])("$name", ({ searchParams, query, expectedPresent }) => {
const result = getNewSearchParams({
query,
searchParams: new URLSearchParams(searchParams),
filterInternalParams: false,
});
assertParamsEqual(result, expectedPresent);
});
});
describe("when filterInternalParams is not provided", () => {
it("defaults to false and preserves all params", () => {
const searchParams = new URLSearchParams({
embed: "true",
overlayCalendar: "true",
foo: "bar",
});
const query = { bookingId: "123" };
const result = getNewSearchParams({ query, searchParams });
assertParamsEqual(result, {
embed: "true",
overlayCalendar: "true",
foo: "bar",
bookingId: "123",
});
});
});
});
describe("edge cases", () => {
it("handles null values in query", () => {
const query = {
bookingId: "123",
nullParam: null,
undefinedParam: undefined,
validParam: "value",
};
const result = getNewSearchParams({ query });
expect(result.get("bookingId")).toBe("123");
expect(result.get("nullParam")).toBeNull();
expect(result.get("undefinedParam")).toBeNull();
expect(result.get("validParam")).toBe("value");
});
it("handles empty strings in query", () => {
const query = {
emptyString: "",
bookingId: "123",
};
const result = getNewSearchParams({ query });
expect(result.get("emptyString")).toBe("");
expect(result.get("bookingId")).toBe("123");
});
it("handles boolean values in query", () => {
const query = {
boolTrue: true,
boolFalse: false,
};
const result = getNewSearchParams({ query });
expect(result.get("boolTrue")).toBe("true");
expect(result.get("boolFalse")).toBe("false");
});
it("handles missing searchParams", () => {
const query = { bookingId: "123", test: "value" };
const result = getNewSearchParams({ query, filterInternalParams: true });
assertParamsEqual(result, { bookingId: "123", test: "value" });
});
it("handles empty query object", () => {
const searchParams = new URLSearchParams({ foo: "bar" });
const result = getNewSearchParams({ query: {}, searchParams });
assertParamsEqual(result, { foo: "bar" });
});
it("query params are appended after searchParams when keys conflict", () => {
const searchParams = new URLSearchParams({ shared: "fromSearchParams", foo: "bar" });
const query = { shared: "fromQuery", baz: "qux" };
const result = getNewSearchParams({ query, searchParams });
// When using append, both values are kept with the first one returned by get()
expect(result.get("shared")).toBe("fromSearchParams");
expect(result.getAll("shared")).toEqual(["fromSearchParams", "fromQuery"]);
expect(result.get("foo")).toBe("bar");
expect(result.get("baz")).toBe("qux");
});
});
});
describe("useBookingSuccessRedirect", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(useCompatSearchParams).mockReturnValue(new URLSearchParams() as any);
vi.mocked(useIsEmbed).mockReturnValue(false);
});
const mockBooking = createMockBooking();
describe("external redirects", () => {
describe("without forwardParamsSuccessRedirect", () => {
it("redirects to external URL without any parameters", () => {
const bookingSuccessRedirect = useBookingSuccessRedirect();
bookingSuccessRedirect({
successRedirectUrl: "https://example.com/success",
forwardParamsSuccessRedirect: false,
query: { test: "value", embed: "namespace" },
booking: mockBooking,
});
expect(navigateInTopWindow).toHaveBeenCalledWith("https://example.com/success");
});
});
describe("with forwardParamsSuccessRedirect", () => {
test.each([
{
name: "filters out embed params from query",
query: {
test: "value",
embed: "namespace",
layout: "month_view",
embedType: "inline",
"ui.color-scheme": "dark",
},
searchParams: "",
expectedPresent: { test: "value", uid: "test-booking-uid" },
expectedNull: ["embed", "layout", "embedType", "ui.color-scheme"],
},
{
name: "filters out webapp params from query",
query: {
test: "value",
overlayCalendar: "true",
},
searchParams: "",
expectedPresent: { test: "value", uid: "test-booking-uid" },
expectedNull: ["overlayCalendar"],
},
{
name: "filters out embed params from searchParams",
query: { additional: "param" },
searchParams: "embed=namespace&layout=month_view&embedType=inline&ui.color-scheme=dark&test=value",
expectedPresent: { test: "value", additional: "param", uid: "test-booking-uid" },
expectedNull: ["embed", "layout", "embedType", "ui.color-scheme"],
},
{
name: "filters out webapp params from searchParams",
query: { additional: "param" },
searchParams: "overlayCalendar=true&test=value",
expectedPresent: { test: "value", additional: "param", uid: "test-booking-uid" },
expectedNull: ["overlayCalendar"],
},
])("$name", ({ query, searchParams, expectedPresent, expectedNull }) => {
if (searchParams) {
vi.mocked(useCompatSearchParams).mockReturnValue(new URLSearchParams(searchParams) as any);
}
const bookingSuccessRedirect = useBookingSuccessRedirect();
bookingSuccessRedirect({
successRedirectUrl: "https://example.com/success",
forwardParamsSuccessRedirect: true,
query,
booking: mockBooking,
});
const calledUrl = vi.mocked(navigateInTopWindow).mock.calls[0][0];
const url = new URL(calledUrl);
// Check expected present params (allow for additional booking params)
Object.entries(expectedPresent).forEach(([key, value]) => {
expect(url.searchParams.get(key)).toBe(value);
});
// Check expected null params
expectedNull.forEach((param) => {
expect(url.searchParams.get(param)).toBeNull();
});
});
it("includes cal.rerouting param from searchParams", () => {
vi.mocked(useCompatSearchParams).mockReturnValue(new URLSearchParams("cal.rerouting=true") as any);
const bookingSuccessRedirect = useBookingSuccessRedirect();
bookingSuccessRedirect({
successRedirectUrl: "https://example.com/success",
forwardParamsSuccessRedirect: true,
query: { test: "value" },
booking: mockBooking,
});
const calledUrl = vi.mocked(navigateInTopWindow).mock.calls[0][0];
assertUrlSearchParams(calledUrl, { "cal.rerouting": "true" });
});
});
});
describe("internal redirects to booking page", () => {
describe("URL structure", () => {
test.each([
{ isEmbed: false, expectedPath: "/booking/test-booking-uid?" },
{ isEmbed: true, expectedPath: "/booking/test-booking-uid/embed?" },
])("redirects to $expectedPath when isEmbed is $isEmbed", ({ isEmbed, expectedPath }) => {
vi.mocked(useIsEmbed).mockReturnValue(isEmbed);
const bookingSuccessRedirect = useBookingSuccessRedirect();
bookingSuccessRedirect({
successRedirectUrl: null,
forwardParamsSuccessRedirect: false,
query: { test: "value" },
booking: mockBooking,
});
expect(mockPush).toHaveBeenCalledWith(expect.stringContaining(expectedPath));
});
});
describe("param preservation for internal navigation", () => {
it("preserves ALL params including embed and webapp params (no filtering)", () => {
vi.mocked(useIsEmbed).mockReturnValue(false);
const bookingSuccessRedirect = useBookingSuccessRedirect();
bookingSuccessRedirect({
successRedirectUrl: null,
forwardParamsSuccessRedirect: false,
query: {
test: "value",
embed: "namespace",
layout: "month_view",
embedType: "inline",
"ui.color-scheme": "dark",
overlayCalendar: "true",
},
booking: mockBooking,
});
const calledUrl = mockPush.mock.calls[0][0];
// ALL params should be preserved for internal navigation
expect(calledUrl).toContain("test=value");
expect(calledUrl).toContain("embed=namespace");
expect(calledUrl).toContain("layout=month_view");
expect(calledUrl).toContain("embedType=inline");
expect(calledUrl).toContain("ui.color-scheme=dark");
expect(calledUrl).toContain("overlayCalendar=true");
});
test.each([
{
name: "includes flag.coep from searchParams",
searchParams: "flag.coep=true",
expectedParam: "flag.coep=true",
},
{
name: "includes cal.rerouting from searchParams",
searchParams: "cal.rerouting=true",
expectedParam: "cal.rerouting=true",
},
])("$name", ({ searchParams, expectedParam }) => {
vi.mocked(useCompatSearchParams).mockReturnValue(new URLSearchParams(searchParams) as any);
const bookingSuccessRedirect = useBookingSuccessRedirect();
bookingSuccessRedirect({
successRedirectUrl: null,
forwardParamsSuccessRedirect: false,
query: { test: "value" },
booking: mockBooking,
});
const calledUrl = mockPush.mock.calls[0][0];
expect(calledUrl).toContain(expectedParam);
});
});
});
describe("edge cases", () => {
it("handles null successRedirectUrl correctly", () => {
const bookingSuccessRedirect = useBookingSuccessRedirect();
bookingSuccessRedirect({
successRedirectUrl: null,
forwardParamsSuccessRedirect: true,
query: { test: "value" },
booking: mockBooking,
});
expect(mockPush).toHaveBeenCalled();
expect(navigateInTopWindow).not.toHaveBeenCalled();
});
it("handles undefined successRedirectUrl correctly", () => {
const bookingSuccessRedirect = useBookingSuccessRedirect();
bookingSuccessRedirect({
successRedirectUrl: undefined as any,
forwardParamsSuccessRedirect: true,
query: { test: "value" },
booking: mockBooking,
});
expect(mockPush).toHaveBeenCalled();
expect(navigateInTopWindow).not.toHaveBeenCalled();
});
it("handles empty query object", () => {
const bookingSuccessRedirect = useBookingSuccessRedirect();
bookingSuccessRedirect({
successRedirectUrl: "https://example.com/success",
forwardParamsSuccessRedirect: false,
query: {},
booking: mockBooking,
});
expect(navigateInTopWindow).toHaveBeenCalledWith("https://example.com/success");
});
});
});
@@ -0,0 +1,252 @@
import { useRouter } from "next/navigation";
import dayjs from "@calcom/dayjs";
import type { PaymentPageProps } from "@calcom/ee/payments/pages/payment";
import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
import type { BookingResponse } from "@calcom/features/bookings/types";
import { getSafe } from "@calcom/lib/getSafe";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { navigateInTopWindow } from "@calcom/lib/navigateInTopWindow";
import type { EventType } from "@calcom/prisma/client";
export function getNewSearchParams(args: {
query: Record<string, string | null | undefined | boolean>;
searchParams?: URLSearchParams;
filterInternalParams?: boolean;
}) {
const { query, searchParams, filterInternalParams = false } = args;
const newSearchParams = new URLSearchParams();
// Embed-specific params
const embedParams = new Set(["embed", "layout", "embedType", "ui.color-scheme"]);
// Webapp-specific params
const webappParams = new Set(["overlayCalendar"]);
// Add non-excluded params from searchParams if provided
if (searchParams) {
searchParams.forEach((value, key) => {
if (shouldExcludeParam(key)) {
return;
}
newSearchParams.append(key, value);
});
}
// Add params from query, filtering excluded params
Object.entries(query).forEach(([key, value]) => {
if (value === null || value === undefined) {
return;
}
if (shouldExcludeParam(key)) {
return;
}
newSearchParams.append(key, String(value));
});
function shouldExcludeParam(key: string) {
if (filterInternalParams) {
return embedParams.has(key) || webappParams.has(key);
}
return false;
}
return newSearchParams;
}
type SuccessRedirectBookingType = Pick<
BookingResponse | PaymentPageProps["booking"],
"uid" | "title" | "description" | "startTime" | "endTime" | "location" | "attendees" | "user" | "responses"
>;
type BookingResponseKey = keyof SuccessRedirectBookingType;
type ResultType = {
[key in BookingResponseKey]?: SuccessRedirectBookingType[key];
} & {
hostName?: string[];
attendeeName?: string | null;
hostStartTime?: string | null;
attendeeStartTime?: string | null;
guestEmails?: string[] | null;
phone?: string | null;
attendeeFirstName?: string | null;
attendeeLastName?: string | null;
};
export const getBookingRedirectExtraParams = (booking: SuccessRedirectBookingType) => {
const redirectQueryParamKeys: BookingResponseKey[] = [
"title",
"description",
"startTime",
"endTime",
"location",
"attendees",
"user",
"responses",
];
// Helper function to extract response details (e.g., phone, attendee's first and last name)
function extractResponseDetails(booking: SuccessRedirectBookingType, obj: ResultType): ResultType {
const result: ResultType = { ...obj };
const phone = getSafe<string>(booking.responses, ["phone"]);
const firstName = getSafe<string>(booking.responses, ["name", "firstName"]);
const lastName = getSafe<string>(booking.responses, ["name", "lastName"]);
const name = getSafe<string>(booking.responses, ["name"]);
if (phone) result.phone = phone;
if (firstName) result.attendeeFirstName = firstName;
if (lastName) result.attendeeLastName = lastName;
else if (name && typeof name === "string") result.attendeeName = name; // Fallback if `name` is a string instead of an object
return result;
}
// Helper function to extract user details (e.g., host name and time zone)
function extractUserDetails(booking: SuccessRedirectBookingType, obj: ResultType): ResultType {
if (booking.user?.name) {
const hostStartTime = dayjs(booking.startTime).tz(booking.user.timeZone).format();
return {
...obj,
hostName: [...(obj.hostName || []), booking.user.name],
hostStartTime,
};
}
return obj;
}
// Helper function to extract attendee and guest details
function extractAttendeesAndGuests(booking: SuccessRedirectBookingType, obj: ResultType): ResultType {
if (!Array.isArray(booking.attendees) || booking.attendees.length === 0) return obj;
const attendeeName = booking.attendees[0]?.name || null;
const attendeeTimeZone = booking.attendees[0]?.timeZone || "UTC";
const attendeeStartTime = dayjs(booking.startTime).tz(attendeeTimeZone).format();
const { hostNames, guestEmails } = booking.attendees.slice(1).reduce(
(acc, attendee) => {
if (attendee.name) {
acc.hostNames.push(attendee.name);
} else if (attendee.email) {
acc.guestEmails.push(attendee.email);
}
return acc;
},
{ hostNames: [], guestEmails: [] } as { hostNames: string[]; guestEmails: string[] }
);
return {
...obj,
attendeeName,
attendeeStartTime,
hostName: [...(obj.hostName || []), ...hostNames],
guestEmails: guestEmails.length > 0 ? guestEmails : undefined,
};
}
const bookingParams = (Object.keys(booking) as BookingResponseKey[])
.filter((key) => redirectQueryParamKeys.includes(key))
.reduce<ResultType>(
(obj, key) => {
if (key === "responses") return extractResponseDetails(booking, obj);
if (key === "user") return extractUserDetails(booking, obj);
if (key === "attendees") return extractAttendeesAndGuests(booking, obj);
return { ...obj, [key]: booking[key] };
},
{ uid: booking.uid }
);
const queryCompatibleParams: Record<string, string | boolean | null | undefined> = {
...Object.fromEntries(
Object.entries(bookingParams).map(([key, value]) => {
if (Array.isArray(value)) {
return [key, value.join(", ")];
}
if (typeof value === "object" && value !== null) {
// Skip complex objects (user, attendees) as we are extracting only needed fields
return [key, undefined];
}
return [key, value];
})
),
hostName: bookingParams.hostName?.join(", "),
attendeeName: bookingParams.attendeeName || undefined,
hostStartTime: bookingParams.hostStartTime || undefined,
attendeeStartTime: bookingParams.attendeeStartTime || undefined,
};
return queryCompatibleParams;
};
export const useBookingSuccessRedirect = () => {
const router = useRouter();
const searchParams = useCompatSearchParams();
const isEmbed = useIsEmbed();
const bookingSuccessRedirect = ({
successRedirectUrl,
query,
booking,
forwardParamsSuccessRedirect,
}: {
successRedirectUrl: EventType["successRedirectUrl"];
forwardParamsSuccessRedirect: EventType["forwardParamsSuccessRedirect"];
query: Record<string, string | null | undefined | boolean>;
booking: SuccessRedirectBookingType;
}) => {
// Ensures that the param is added both to external redirect url and booking success page URL
query = {
...query,
"cal.rerouting": searchParams.get("cal.rerouting"),
};
if (successRedirectUrl) {
const url = new URL(successRedirectUrl);
// Using parent ensures, Embed iframe would redirect outside of the iframe.
if (!forwardParamsSuccessRedirect) {
navigateInTopWindow(url.toString());
return;
}
const bookingExtraParams = getBookingRedirectExtraParams(booking);
// Filter internal Cal.com params when redirecting to external URLs.
// - It prevents leaking internal state.
// - Certain websites might break due to the presence of certain params e.g. Wordpress has different meaning for `embed` param and an embed param passed by Cal.com breaks a wordpress webpage
const newSearchParams = getNewSearchParams({
query: {
...query,
...bookingExtraParams,
isEmbed,
},
searchParams: new URLSearchParams(searchParams.toString()),
filterInternalParams: true,
});
newSearchParams.forEach((value, key) => {
url.searchParams.append(key, value);
});
navigateInTopWindow(url.toString());
return;
}
// TODO: Abstract it out and reuse at other places where we navigate within the embed. Though this is needed only in case of hard navigation happening but we aren't sure where hard navigation happens and where a soft navigation
// This is specially true after App Router it seems
const headersRelatedSearchParams = searchParams
? {
"flag.coep": searchParams.get("flag.coep") ?? "false",
}
: undefined;
// We don't want to forward all search params, as they could possibly break the booking page.
const newSearchParams = getNewSearchParams({
query,
searchParams: new URLSearchParams(headersRelatedSearchParams),
});
return router.push(`/booking/${booking.uid}${isEmbed ? "/embed" : ""}?${newSearchParams.toString()}`);
};
return bookingSuccessRedirect;
};
@@ -0,0 +1,110 @@
import dayjs from "@calcom/dayjs";
import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { HttpError } from "@calcom/lib/http-error";
import { ascendingLimitKeys, intervalLimitKeyToUnit } from "@calcom/lib/intervalLimits/intervalLimit";
import type { IntervalLimit, IntervalLimitKey } from "@calcom/lib/intervalLimits/intervalLimitSchema";
import { parseBookingLimit } from "@calcom/lib/intervalLimits/isBookingLimits";
import { withReporting } from "@calcom/lib/sentryWrapper";
export interface ICheckBookingLimitsService {
bookingRepo: BookingRepository;
}
export class CheckBookingLimitsService {
constructor(private readonly dependencies: ICheckBookingLimitsService) {}
private async _checkBookingLimits(
bookingLimits: IntervalLimit,
eventStartDate: Date,
eventId: number,
rescheduleUid?: string | undefined,
timeZone?: string | null,
includeManagedEvents?: boolean
) {
const parsedBookingLimits = parseBookingLimit(bookingLimits);
if (!parsedBookingLimits) return false;
// not iterating entries to preserve types
const limitCalculations = ascendingLimitKeys.map((key) =>
this.checkBookingLimit({
key,
limitingNumber: parsedBookingLimits[key],
eventStartDate,
eventId,
timeZone,
rescheduleUid,
includeManagedEvents,
})
);
try {
return !!(await Promise.all(limitCalculations));
} catch (error) {
throw new HttpError({ message: getErrorFromUnknown(error).message, statusCode: 401 });
}
}
checkBookingLimits = withReporting(this._checkBookingLimits.bind(this), "checkBookingLimits");
private async _checkBookingLimit({
eventStartDate,
eventId,
key,
limitingNumber,
rescheduleUid,
timeZone,
teamId,
user,
includeManagedEvents = false,
}: {
eventStartDate: Date;
eventId?: number;
key: IntervalLimitKey;
limitingNumber: number | undefined;
rescheduleUid?: string | undefined;
timeZone?: string | null;
teamId?: number;
user?: { id: number; email: string };
includeManagedEvents?: boolean;
}) {
const eventDateInOrganizerTz = timeZone ? dayjs(eventStartDate).tz(timeZone) : dayjs(eventStartDate);
if (!limitingNumber) return;
const unit = intervalLimitKeyToUnit(key);
const startDate = dayjs(eventDateInOrganizerTz).startOf(unit).toDate();
const endDate = dayjs(eventDateInOrganizerTz).endOf(unit).toDate();
let bookingsInPeriod;
if (teamId && user) {
bookingsInPeriod = await this.dependencies.bookingRepo.getAllAcceptedTeamBookingsOfUser({
user: { id: user.id, email: user.email },
teamId,
startDate: startDate,
endDate: endDate,
shouldReturnCount: true,
excludedUid: rescheduleUid,
includeManagedEvents,
});
} else {
bookingsInPeriod = await this.dependencies.bookingRepo.countBookingsByEventTypeAndDateRange({
eventTypeId: eventId!,
startDate,
endDate,
excludedUid: rescheduleUid,
});
}
if (bookingsInPeriod < limitingNumber) return;
throw new HttpError({
message: `booking_limit_reached`,
statusCode: 403,
});
}
checkBookingLimit = withReporting(this._checkBookingLimit.bind(this), "checkBookingLimit");
}
@@ -0,0 +1,73 @@
import dayjs from "@calcom/dayjs";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { HttpError } from "@calcom/lib/http-error";
import { ascendingLimitKeys, intervalLimitKeyToUnit } from "@calcom/lib/intervalLimits/intervalLimit";
import type { IntervalLimit, IntervalLimitKey } from "@calcom/lib/intervalLimits/intervalLimitSchema";
import { parseDurationLimit } from "@calcom/lib/intervalLimits/isDurationLimits";
import prisma from "@calcom/prisma";
export async function checkDurationLimits(
durationLimits: IntervalLimit,
eventStartDate: Date,
eventId: number,
rescheduleUid?: string
) {
const parsedDurationLimits = parseDurationLimit(durationLimits);
if (!parsedDurationLimits) return false;
// not iterating entries to preserve types
const limitCalculations = ascendingLimitKeys.map((key) =>
checkDurationLimit({
key,
limitingNumber: parsedDurationLimits[key],
eventStartDate,
eventId,
rescheduleUid,
})
);
try {
return !!(await Promise.all(limitCalculations));
} catch (error) {
throw new HttpError({ message: getErrorFromUnknown(error).message, statusCode: 401 });
}
}
export async function checkDurationLimit({
eventStartDate,
eventId,
key,
limitingNumber,
rescheduleUid,
}: {
eventStartDate: Date;
eventId: number;
key: IntervalLimitKey;
limitingNumber: number | undefined;
rescheduleUid?: string;
}) {
{
if (!limitingNumber) return;
const unit = intervalLimitKeyToUnit(key);
const startDate = dayjs(eventStartDate).startOf(unit).toDate();
const endDate = dayjs(eventStartDate).endOf(unit).toDate();
const bookingRepo = new BookingRepository(prisma);
const totalBookingDuration = await bookingRepo.getTotalBookingDuration({
eventId,
startDate,
endDate,
rescheduleUid,
});
if (totalBookingDuration < limitingNumber) return;
throw new HttpError({
message: `duration_limit_reached`,
statusCode: 403,
});
}
}
@@ -7,9 +7,9 @@ import {
import { describe, test, expect, vi } from "vitest";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
vi.mock("@calcom/lib/server/repository/user", () => {
vi.mock("@calcom/features/users/repositories/UserRepository", () => {
return {
UserRepository: vi.fn().mockImplementation(() => ({
enrichUserWithItsProfile: vi.fn(),
@@ -2,7 +2,7 @@ import type { z } from "zod";
import { eventTypeAppMetadataOptionalSchema } from "@calcom/app-store/zod-utils";
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "@calcom/app-store/delegationCredential";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import prisma from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
@@ -3,7 +3,7 @@ import type { z } from "zod";
import {
SMS_REMINDER_NUMBER_FIELD,
CAL_AI_AGENT_PHONE_NUMBER_FIELD,
} from "@calcom/features/bookings/lib/SystemField";
} from "@calcom/lib/SystemField";
import type { Workflow } from "@calcom/features/ee/workflows/lib/types";
import { fieldsThatSupportLabelAsSafeHtml } from "@calcom/features/form-builder/fieldsThatSupportLabelAsSafeHtml";
import { getFieldIdentifier } from "@calcom/features/form-builder/utils/getFieldIdentifier";
@@ -1,6 +1,6 @@
import type z from "zod";
import { SystemField } from "@calcom/features/bookings/lib/SystemField";
import { SystemField } from "@calcom/lib/SystemField";
import type { bookingResponsesDbSchema } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
import { contructEmailFromPhoneNumber } from "@calcom/lib/contructEmailFromPhoneNumber";
import { getBookingWithResponses } from "@calcom/lib/getBooking";
@@ -0,0 +1,34 @@
import type z from "zod";
import { TITLE_FIELD, SMS_REMINDER_NUMBER_FIELD } from "@calcom/lib/SystemField";
import type { bookingResponse } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
import type { CalendarEvent } from "@calcom/types/Calendar";
export default function getLabelValueMapFromResponses(
calEvent: Pick<CalendarEvent, "customInputs" | "userFieldsResponses" | "responses" | "eventTypeId">,
isOrganizer = false
) {
const { customInputs, userFieldsResponses, responses, eventTypeId } = calEvent;
const isDynamicEvent = !eventTypeId;
let labelValueMap: Record<string, z.infer<typeof bookingResponse>> = {};
if (userFieldsResponses) {
if (!!responses?.[TITLE_FIELD] && !isDynamicEvent) {
userFieldsResponses[TITLE_FIELD] = responses[TITLE_FIELD];
}
if (!!responses?.[SMS_REMINDER_NUMBER_FIELD] && !isDynamicEvent) {
userFieldsResponses[SMS_REMINDER_NUMBER_FIELD] = responses[SMS_REMINDER_NUMBER_FIELD];
}
for (const [, value] of Object.entries(userFieldsResponses)) {
if (!value.label || (!isOrganizer && value.isHidden)) {
continue;
}
labelValueMap[value.label] = value.value;
}
} else {
labelValueMap = customInputs as Record<string, string | string[]>;
}
return labelValueMap;
}
@@ -0,0 +1,800 @@
import { describe, it, vi, expect, afterEach, beforeEach, beforeAll, afterAll } from "vitest";
import { getLuckyUserService } from "@calcom/features/di/containers/LuckyUser";
import prisma from "@calcom/prisma";
const luckyUserService = getLuckyUserService();
let commonEventTypeId: number;
const userIds: number[] = [];
async function deleteUsers() {
await prisma.user.deleteMany({
where: {
id: {
in: userIds,
},
},
});
userIds.splice(0, userIds.length);
}
beforeAll(async () => {
const event = await prisma.eventType.create({
data: {
title: "Test Event",
slug: "test-event",
length: 15,
},
select: {
id: true,
},
});
commonEventTypeId = event.id;
});
beforeEach(() => {
// tell vitest we use mocked time
vi.useFakeTimers();
});
afterEach(async () => {
await deleteUsers();
vi.useRealTimers();
});
afterAll(async () => {
await prisma.eventType.delete({
where: {
id: commonEventTypeId,
},
});
});
type BookingPropsRelatedToLuckyUserAlgorithm = {
eventTypeId: number;
createdAt: Date;
noShowHost?: boolean | null;
};
type OptionalBookingProps = {
uid?: string;
title?: string;
startTime?: Date;
endTime?: Date;
attendees?: {
create: {
name: string;
email: string;
timeZone: string;
noShow?: boolean | null;
}[];
};
};
type UserProps = {
email: string;
createdDate?: Date;
};
const commonBookingData = {
startTime: new Date(),
endTime: new Date(),
};
const commonAttendeesData = [
{
name: "test-attendee",
email: "[email protected]",
timeZone: "Asia/Calcutta",
},
];
const createUserWithBookings = async ({
user: { email, createdDate },
bookings,
}: {
user: UserProps;
bookings: (BookingPropsRelatedToLuckyUserAlgorithm & OptionalBookingProps)[];
}) => {
const user = await prisma.user.create({
data: {
email,
createdDate,
bookings: {
create: bookings.map(({ eventTypeId, ...booking }, index) => ({
...commonBookingData,
attendees: {
create: commonAttendeesData,
},
uid: `uuid-${email}-booking${index + 1}`,
title: `${email} Booking ${index + 1}`,
eventTypeId,
...booking,
})),
},
},
include: {
bookings: true,
credentials: true,
},
});
userIds.push(user.id);
return user;
};
const createHostWithBookings = async ({
user: userData,
bookings,
priority = 2,
weight = null,
createdAt,
}: {
user: UserProps;
bookings: (BookingPropsRelatedToLuckyUserAlgorithm & OptionalBookingProps)[];
weight?: number | null;
priority?: number;
createdAt?: Date;
}) => {
const user = await createUserWithBookings({
user: {
createdDate: userData.createdDate || new Date(),
email: userData.email,
},
bookings,
});
const host = await prisma.host.create({
data: {
user: { connect: { id: user.id } },
eventType: { connect: { id: commonEventTypeId } },
weight,
priority,
createdAt: createdAt ?? new Date(),
},
include: {
user: {
include: {
bookings: true,
credentials: true,
},
},
},
});
return {
...host,
user: {
...host.user,
priority,
weight,
},
};
};
function expectLuckyUsers(luckyUsers: { email: string }[], expectedLuckyUsers: { email: string }[]) {
expect(luckyUsers.map((user) => user.email)).toEqual(expectedLuckyUsers.map((user) => user.email));
}
describe("getLuckyUser Integration tests", () => {
describe("should not consider no show bookings for round robin: ", () => {
it("When a host is no show, that is chosen when competing with another host that showed up for the booking", async () => {
const createOrganizerThatShowedUp = async (email: string) => {
return createHostWithBookings({
user: { email },
bookings: [{ eventTypeId: commonEventTypeId, createdAt: new Date("2022-01-25T05:30:00.000Z") }],
});
};
const createOrganizerThatDidntShowUp = async (email: string) => {
return createHostWithBookings({
user: { email },
bookings: [
{
eventTypeId: commonEventTypeId,
createdAt: new Date("2022-01-25T06:30:00.000Z"),
noShowHost: true,
},
],
});
};
const organizerHostThatShowedUp = await createOrganizerThatShowedUp("[email protected]");
const organizerHostThatDidntShowUp = await createOrganizerThatDidntShowUp("[email protected]");
const organizerThatShowedUp = organizerHostThatShowedUp.user;
const organizerThatDidntShowUp = organizerHostThatDidntShowUp.user;
const luckyUser = await luckyUserService.getLuckyUser({
availableUsers: [organizerThatShowedUp, organizerThatDidntShowUp],
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled: false,
team: {},
},
allRRHosts: [],
routingFormResponse: null,
});
expect(luckyUser.email).toBe(organizerThatDidntShowUp.email);
});
it("When a attendee is a noShow for organizers booking, that organizer is competing with another host whose attendee showed up for the booking", async () => {
const organizerHostWhoseAttendeeShowedUp = await createHostWithBookings({
user: { email: "[email protected]" },
bookings: [
{
eventTypeId: commonEventTypeId,
createdAt: new Date("2022-01-25T05:30:00.000Z"),
title: "Test User 1 Booking",
attendees: {
create: [
{
name: "test-attendee",
email: "[email protected]",
timeZone: "Asia/Calcutta",
},
],
},
},
],
});
const organizerWhoseAttendeeShowedUp = organizerHostWhoseAttendeeShowedUp.user;
const organizerHostWhoseAttendeeDidntShowUp = await createHostWithBookings({
user: { email: "[email protected]" },
bookings: [
{
eventTypeId: commonEventTypeId,
createdAt: new Date("2022-01-25T06:30:00.000Z"),
attendees: {
create: [
{
noShow: true,
name: "test-attendee",
email: "[email protected]",
timeZone: "Asia/Calcutta",
},
],
},
},
],
});
const organizerWhoseAttendeeDidntShowUp = organizerHostWhoseAttendeeDidntShowUp.user;
expect(
luckyUserService.getLuckyUser({
availableUsers: [organizerWhoseAttendeeShowedUp, organizerWhoseAttendeeDidntShowUp],
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled: false,
team: {},
},
allRRHosts: [],
routingFormResponse: null,
})
).resolves.toStrictEqual(organizerWhoseAttendeeDidntShowUp);
});
it("When a organizer is attendee (event types with fixed hosts) and no show, that organizer is competing other hosts", async () => {
const organizerHostWhoseAttendeeShowedUp = await createHostWithBookings({
user: { email: "[email protected]" },
bookings: [
{
eventTypeId: commonEventTypeId,
createdAt: new Date("2022-01-25T05:30:00.000Z"),
title: "Test User 1 Booking",
attendees: {
create: [
{
name: "test-attendee",
email: "[email protected]",
timeZone: "Asia/Calcutta",
},
],
},
},
],
});
const organizerWhoseAttendeeShowedUp = organizerHostWhoseAttendeeShowedUp.user;
const fixedHostOrganizerHostWhoseAttendeeDidNotShowUp = await createHostWithBookings({
user: { email: "[email protected]" },
bookings: [
{
eventTypeId: commonEventTypeId,
createdAt: new Date("2022-01-25T06:30:00.000Z"),
attendees: {
create: [
{
name: "test-attendee",
email: "[email protected]",
timeZone: "Asia/Calcutta",
},
],
},
},
// User2 is fixed user, User 3 was selected as round robin host but did not show up so this booking should be counted for User 3
{
uid: "uuid-test-user2-booking2",
title: `Test User 2 Booking 2`,
createdAt: new Date("2022-01-25T07:30:00.000Z"),
eventTypeId: commonEventTypeId,
attendees: {
create: [
{
name: "test-attendee",
email: "[email protected]",
timeZone: "Asia/Calcutta",
noShow: true,
},
],
},
},
],
});
const fixedHostOrganizerWhoseAttendeeDidNotShowUp =
fixedHostOrganizerHostWhoseAttendeeDidNotShowUp.user;
const organizerHostWhoWasAttendeeAndDidntShowUp = await createHostWithBookings({
user: { email: `[email protected]` },
bookings: [
{
uid: "uuid-test-user3-booking1",
title: `Test User 3 Booking`,
createdAt: new Date("2022-01-25T04:30:00.000Z"),
attendees: {
create: [
{
name: "test-attendee",
email: "[email protected]",
timeZone: "Asia/Calcutta",
},
],
},
eventTypeId: commonEventTypeId,
},
],
});
const organizerWhoWasAttendeeAndDidntShowUp = organizerHostWhoWasAttendeeAndDidntShowUp.user;
expect(
luckyUserService.getLuckyUser({
availableUsers: [
organizerWhoseAttendeeShowedUp,
fixedHostOrganizerWhoseAttendeeDidNotShowUp,
organizerWhoWasAttendeeAndDidntShowUp,
],
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled: false,
team: {},
},
allRRHosts: [],
routingFormResponse: null,
})
).resolves.toStrictEqual(organizerWhoWasAttendeeAndDidntShowUp);
});
it("should consider booking when noShowHost is null", async () => {
const hostWithBookingThatHappenedLater = await createHostWithBookings({
user: { email: "[email protected]" },
bookings: [
{
uid: "uuid-test-user1-booking1",
createdAt: new Date("2022-01-25T07:30:00.000Z"),
title: "Test user 1 Booking",
noShowHost: null,
eventTypeId: commonEventTypeId,
attendees: {
create: [
{
name: "test-attendee",
email: "[email protected]",
timeZone: "Asia/Calcutta",
},
],
},
},
],
});
const userWithBookingThatHappenedLater = hostWithBookingThatHappenedLater.user;
const hostWithBookingThatHappenedEarlier = await createHostWithBookings({
user: { email: "[email protected]" },
bookings: [
{
uid: "uuid-test-user2-booking1",
title: "Test User 2 Booking",
createdAt: new Date("2022-01-25T06:30:00.000Z"),
noShowHost: null,
eventTypeId: commonEventTypeId,
attendees: {
create: [
{
name: "test-attendee",
email: "[email protected]",
timeZone: "Asia/Calcutta",
},
],
},
},
],
});
const userWithBookingThatHappenedEarlier = hostWithBookingThatHappenedEarlier.user;
expect(
luckyUserService.getLuckyUser({
availableUsers: [userWithBookingThatHappenedLater, userWithBookingThatHappenedEarlier],
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled: false,
team: {},
},
allRRHosts: [],
routingFormResponse: null,
})
).resolves.toStrictEqual(userWithBookingThatHappenedEarlier);
});
});
});
describe("getOrderedListOfLuckyUsers Integration tests", () => {
beforeEach(() => {
vi.setSystemTime("2024-11-14T00:00:13Z");
});
it("should sort as per availableUsers if no other criteria like weight/priority/calibration (TODO: make it independent of availableUsers order)", async () => {
const [host1, host2, host3] = await Promise.all([
createHostWithBookings({
user: { email: "[email protected]" },
bookings: [],
createdAt: new Date(),
}),
createHostWithBookings({
user: { email: "[email protected]" },
bookings: [],
createdAt: new Date(),
}),
createHostWithBookings({
user: { email: "[email protected]" },
bookings: [],
createdAt: new Date(),
}),
]);
const user1 = host1.user;
const user2 = host2.user;
const user3 = host3.user;
const { users: luckyUsers } = await luckyUserService.getOrderedListOfLuckyUsers({
availableUsers: [user2, user1, user3],
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled: false,
team: {},
},
allRRHosts: [],
routingFormResponse: null,
});
expectLuckyUsers(luckyUsers, [user2, user1, user3]);
const { users: luckyUsers2 } = await luckyUserService.getOrderedListOfLuckyUsers({
availableUsers: [user3, user1, user2],
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled: false,
team: {},
},
allRRHosts: [],
routingFormResponse: null,
});
expectLuckyUsers(luckyUsers2, [user3, user1, user2]);
});
describe("should sort as per weights", () => {
const isRRWeightsEnabled = true;
it("even if there are no bookings", async () => {
const [host1WithWeight100, host2WithWeight200, host3WithWeight100] = await Promise.all([
createHostWithBookings({
user: { email: "[email protected]" },
bookings: [],
createdAt: new Date(),
weight: 100,
}),
createHostWithBookings({
user: { email: "[email protected]" },
bookings: [],
createdAt: new Date(),
weight: 200,
}),
createHostWithBookings({
user: { email: "[email protected]" },
bookings: [],
createdAt: new Date(),
weight: 100,
}),
]);
const user1WithWeight100 = host1WithWeight100.user;
const userWithHighestWeight = host2WithWeight200.user;
const user2WithWeight100 = host3WithWeight100.user;
const allRRHosts = [host1WithWeight100, host2WithWeight200, host3WithWeight100];
const { users: luckyUsers } = await luckyUserService.getOrderedListOfLuckyUsers({
availableUsers: [userWithHighestWeight, user1WithWeight100, user2WithWeight100],
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled,
team: {},
},
allRRHosts,
routingFormResponse: null,
});
expectLuckyUsers(luckyUsers, [
// It has the highest weight
userWithHighestWeight,
// It has the same weight as the next one but comes earlier in availableUsers array
user1WithWeight100,
// It is the last choice
user2WithWeight100,
]);
const { users: luckyUsers2 } = await luckyUserService.getOrderedListOfLuckyUsers({
availableUsers: [user2WithWeight100, userWithHighestWeight, user1WithWeight100],
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled,
team: {},
},
allRRHosts,
routingFormResponse: null,
});
expectLuckyUsers(luckyUsers2, [
// It has the highest weight and zero bookings.
userWithHighestWeight,
// It has the same weight as the next one but comes earlier in availableUsers array
user2WithWeight100,
// It is the last choice
user1WithWeight100,
]);
});
it("consider booking count for the current month", async () => {
const [
hostWithOneBookingAndWeight200,
hostWithTwoBookingsAndWeight100,
hostWithThreeBookingsAndWeight100,
] = await Promise.all([
createHostWithBookings({
user: { email: "[email protected]" },
bookings: [{ eventTypeId: commonEventTypeId, createdAt: new Date() }],
createdAt: new Date(),
weight: 200,
}),
createHostWithBookings({
user: { email: "[email protected]" },
bookings: [
{ eventTypeId: commonEventTypeId, createdAt: new Date() },
{ eventTypeId: commonEventTypeId, createdAt: new Date() },
],
createdAt: new Date(),
weight: 100,
}),
createHostWithBookings({
user: { email: "[email protected]" },
bookings: [
{ eventTypeId: commonEventTypeId, createdAt: new Date() },
{ eventTypeId: commonEventTypeId, createdAt: new Date() },
{ eventTypeId: commonEventTypeId, createdAt: new Date() },
],
createdAt: new Date(),
weight: 100,
}),
]);
const userWithOneBookingAndWeight200 = hostWithOneBookingAndWeight200.user;
const userWithTwoBookingsAndWeight100 = hostWithTwoBookingsAndWeight100.user;
const userWithThreeBookingsAndWeight100 = hostWithThreeBookingsAndWeight100.user;
const availableUsers = [
userWithThreeBookingsAndWeight100,
userWithTwoBookingsAndWeight100,
userWithOneBookingAndWeight200,
];
const getLuckUserParams = {
availableUsers,
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled,
team: null,
},
allRRHosts: [
hostWithOneBookingAndWeight200,
hostWithTwoBookingsAndWeight100,
hostWithThreeBookingsAndWeight100,
],
routingFormResponse: null,
};
const { users: luckyUsers, perUserData } = await luckyUserService.getOrderedListOfLuckyUsers({
...getLuckUserParams,
availableUsers: [getLuckUserParams.availableUsers[0], ...getLuckUserParams.availableUsers.slice(1)],
});
expectLuckyUsers(luckyUsers, [
// User with 1 booking is chosen first because it has higher weight and lesser bookings
userWithOneBookingAndWeight200,
// User with 2 bookings is chosen next because it has lesser bookings
userWithTwoBookingsAndWeight100,
// User with 3 bookings is chosen last because it has the most bookings
userWithThreeBookingsAndWeight100,
]);
if (!perUserData?.bookingShortfalls) {
throw new Error("bookingShortfalls is not defined");
}
expect(perUserData.bookingShortfalls[userWithThreeBookingsAndWeight100.id]).toBe(-1.5);
expect(perUserData.bookingShortfalls[userWithTwoBookingsAndWeight100.id]).toBe(-0.5);
expect(perUserData.bookingShortfalls[userWithOneBookingAndWeight200.id]).toBe(2);
});
it("not considering bookings that were created in previous months", async () => {
const [
hostWithOneBookingInPreviousMonthAndWeight200,
hostWithTwoBookingsInPreviousMonthAndWeight100,
hostWithThreeBookingsInPreviousMonthAndWeight100,
] = await Promise.all([
createHostWithBookings({
user: { email: "[email protected]", createdDate: new Date() },
bookings: [{ eventTypeId: commonEventTypeId, createdAt: new Date("2024-10-01T00:00:00.000Z") }],
weight: 200,
createdAt: new Date(),
}),
createHostWithBookings({
user: { email: "[email protected]", createdDate: new Date() },
bookings: [
{ eventTypeId: commonEventTypeId, createdAt: new Date("2024-10-01T00:00:00.000Z") },
{ eventTypeId: commonEventTypeId, createdAt: new Date("2024-10-01T00:00:00.000Z") },
],
weight: 100,
createdAt: new Date(),
}),
createHostWithBookings({
user: { email: "[email protected]", createdDate: new Date() },
bookings: [
{ eventTypeId: commonEventTypeId, createdAt: new Date("2024-10-01T00:00:00.000Z") },
{ eventTypeId: commonEventTypeId, createdAt: new Date("2024-10-01T00:00:00.000Z") },
{ eventTypeId: commonEventTypeId, createdAt: new Date("2024-10-01T00:00:00.000Z") },
],
weight: 100,
createdAt: new Date(),
}),
]);
const userWithOneBookingInPreviousMonthAndWeight200 =
hostWithOneBookingInPreviousMonthAndWeight200.user;
const userWithTwoBookingsInPreviousMonthAndWeight100 =
hostWithTwoBookingsInPreviousMonthAndWeight100.user;
const userWithThreeBookingsInPreviousMonthAndWeight100 =
hostWithThreeBookingsInPreviousMonthAndWeight100.user;
const availableUsers = [
userWithThreeBookingsInPreviousMonthAndWeight100,
userWithTwoBookingsInPreviousMonthAndWeight100,
userWithOneBookingInPreviousMonthAndWeight200,
];
const getLuckUserParams = {
availableUsers,
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled,
team: null,
},
allRRHosts: [
hostWithOneBookingInPreviousMonthAndWeight200,
hostWithTwoBookingsInPreviousMonthAndWeight100,
hostWithThreeBookingsInPreviousMonthAndWeight100,
],
routingFormResponse: null,
};
const { users: luckyUsers, perUserData } = await luckyUserService.getOrderedListOfLuckyUsers({
...getLuckUserParams,
availableUsers: [getLuckUserParams.availableUsers[0], ...getLuckUserParams.availableUsers.slice(1)],
});
expectLuckyUsers(luckyUsers, [
// User with 1 booking is chosen first because it has higher weight and lesser bookings
userWithOneBookingInPreviousMonthAndWeight200,
// User with 3 bookings is chosen next because it comes earlier in availableUsers array
userWithThreeBookingsInPreviousMonthAndWeight100,
// User with 2 bookings is chosen last because it comes later in availableUsers array
userWithTwoBookingsInPreviousMonthAndWeight100,
]);
if (!perUserData?.bookingShortfalls) {
throw new Error("bookingShortfalls is not defined");
}
// Because no one has any bookings in the current month, the booking shortfall should be 0 for all users
expect(perUserData.bookingShortfalls[userWithThreeBookingsInPreviousMonthAndWeight100.id]).toBe(0);
expect(perUserData.bookingShortfalls[userWithTwoBookingsInPreviousMonthAndWeight100.id]).toBe(0);
expect(perUserData.bookingShortfalls[userWithOneBookingInPreviousMonthAndWeight200.id]).toBe(0);
});
});
describe("should sort as per host creation data calibration", () => {
const isRRWeightsEnabled = true;
it("not considering bookings that were created in previous months", async () => {
const today = new Date();
const tenthOfTheMonth = new Date(today.getFullYear(), today.getMonth(), 10);
const secondsInDay = 24 * 60 * 60 * 1000;
const ninthOfTheMonth = new Date(tenthOfTheMonth.getTime() - secondsInDay);
const eighthOfTheMonth = new Date(tenthOfTheMonth.getTime() - 2 * secondsInDay);
const [host1, host2, host3] = await Promise.all([
createHostWithBookings({
user: { email: "[email protected]", createdDate: tenthOfTheMonth },
bookings: [
{ eventTypeId: commonEventTypeId, createdAt: new Date(tenthOfTheMonth.getTime() + 1000) },
],
weight: 200,
createdAt: tenthOfTheMonth,
}),
createHostWithBookings({
user: { email: "[email protected]", createdDate: ninthOfTheMonth },
bookings: [
{ eventTypeId: commonEventTypeId, createdAt: new Date(ninthOfTheMonth.getTime() + 1000) },
{ eventTypeId: commonEventTypeId, createdAt: new Date(ninthOfTheMonth.getTime() + 2000) },
],
weight: 100,
createdAt: ninthOfTheMonth,
}),
createHostWithBookings({
user: { email: "[email protected]", createdDate: eighthOfTheMonth },
bookings: [
{ eventTypeId: commonEventTypeId, createdAt: new Date(eighthOfTheMonth.getTime() + 1000) },
{ eventTypeId: commonEventTypeId, createdAt: new Date(eighthOfTheMonth.getTime() + 2000) },
{ eventTypeId: commonEventTypeId, createdAt: new Date(eighthOfTheMonth.getTime() + 3000) },
],
weight: 100,
createdAt: eighthOfTheMonth,
}),
]);
const availableUsers = [host3.user, host2.user, host1.user];
const getLuckyUserParams = {
availableUsers,
eventType: {
id: commonEventTypeId,
isRRWeightsEnabled,
team: null,
},
allRRHosts: [host1, host2, host3],
routingFormResponse: null,
};
const { users: luckyUsers, perUserData } = await luckyUserService.getOrderedListOfLuckyUsers({
...getLuckyUserParams,
availableUsers: [getLuckyUserParams.availableUsers[0], ...getLuckyUserParams.availableUsers.slice(1)],
});
if (!perUserData?.bookingShortfalls || !perUserData?.calibrations) {
throw new Error("bookingShortfalls or calibrations is not defined");
}
expect(perUserData.calibrations[host1.user.id]).toBe(2.5);
expect(perUserData.calibrations[host2.user.id]).toBe(3);
expect(perUserData.calibrations[host3.user.id]).toBe(0);
expectLuckyUsers(luckyUsers, [host1.user, host3.user, host2.user]);
});
});
});
@@ -8,10 +8,10 @@ import logger from "@calcom/lib/logger";
import { raqbQueryValueSchema } from "@calcom/lib/raqb/zod";
import { safeStringify } from "@calcom/lib/safeStringify";
import type { PrismaAttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import type { HostRepository } from "@calcom/lib/server/repository/host";
import type { PrismaOOORepository } from "@calcom/lib/server/repository/ooo";
import type { UserRepository } from "@calcom/lib/server/repository/user";
import type { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import type { Prisma } from "@calcom/prisma/client";
import type { User, Booking, SelectedCalendar } from "@calcom/prisma/client";
import type { AttributeType } from "@calcom/prisma/enums";
@@ -18,7 +18,7 @@ import {
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import EventManager from "@calcom/features/bookings/lib/EventManager";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
import { HttpError } from "@calcom/lib/http-error";
@@ -27,7 +27,7 @@ import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import prisma from "@calcom/prisma";
import type { Prisma, WorkflowReminder } from "@calcom/prisma/client";
@@ -13,7 +13,7 @@ import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import type { EventManagerUser } from "@calcom/features/bookings/lib/EventManager";
import EventManager, { placeholderCreatedEvent } from "@calcom/features/bookings/lib/EventManager";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
import logger from "@calcom/lib/logger";
@@ -23,6 +23,7 @@ import { scheduleMandatoryReminder } from "@calcom/ee/workflows/lib/reminders/sc
import getICalUID from "@calcom/emails/lib/getICalUID";
import { CalendarEventBuilder } from "@calcom/features/CalendarEventBuilder";
import EventManager, { placeholderCreatedEvent } from "@calcom/features/bookings/lib/EventManager";
import type { CheckBookingLimitsService } from "@calcom/features/bookings/lib/checkBookingLimits";
import type { BookingDataSchemaGetter } from "@calcom/features/bookings/lib/dto/types";
import type {
CreateRegularBookingData,
@@ -33,13 +34,16 @@ import type { CheckBookingAndDurationLimitsService } from "@calcom/features/book
import { handlePayment } from "@calcom/features/bookings/lib/handlePayment";
import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhookTrigger";
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import type { CacheService } from "@calcom/features/calendar-cache/lib/getShouldServeCache";
import AssignmentReasonRecorder from "@calcom/features/ee/round-robin/assignmentReason/AssignmentReasonRecorder";
import { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
import { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
import { getEventName, updateHostInEventName } from "@calcom/features/eventtypes/lib/eventNaming";
import type { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { getFullName } from "@calcom/features/form-builder/utils";
import { handleAnalyticsEvents } from "@calcom/features/tasker/tasks/analytics/handleAnalyticsEvents";
import type { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { UsersRepository } from "@calcom/features/users/users.repository";
import type { GetSubscriberOptions } from "@calcom/features/webhooks/lib/getWebhooks";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
@@ -55,21 +59,17 @@ import { DEFAULT_GROUP_ID } from "@calcom/lib/constants";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { extractBaseEmail } from "@calcom/lib/extract-base-email";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
import { HttpError } from "@calcom/lib/http-error";
import type { CheckBookingLimitsService } from "@calcom/lib/intervalLimits/server/checkBookingLimits";
import logger from "@calcom/lib/logger";
import { getPiiFreeCalendarEvent, getPiiFreeEventType } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import type { PrismaAttributeRepository as AttributeRepository } from "@calcom/lib/server/repository/PrismaAttributeRepository";
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
import type { HostRepository } from "@calcom/lib/server/repository/host";
import type { PrismaOOORepository as OooRepository } from "@calcom/lib/server/repository/ooo";
import type { UserRepository } from "@calcom/lib/server/repository/user";
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { HashedLinkService } from "@calcom/lib/server/service/hashedLinkService";
import { WorkflowService } from "@calcom/lib/server/service/workflows";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
@@ -1,7 +1,7 @@
import dayjs from "@calcom/dayjs";
import type { IntervalLimit } from "@calcom/lib/intervalLimits/intervalLimitSchema";
import type { CheckBookingLimitsService } from "@calcom/lib/intervalLimits/server/checkBookingLimits";
import { checkDurationLimits } from "@calcom/lib/intervalLimits/server/checkDurationLimits";
import type { CheckBookingLimitsService } from "@calcom/features/bookings/lib/checkBookingLimits";
import { checkDurationLimits } from "@calcom/features/bookings/lib/checkDurationLimits";
import { withReporting } from "@calcom/lib/sentryWrapper";
import type { NewBookingEventType } from "./getEventTypesFromDB";
@@ -4,7 +4,7 @@ import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/
import type { DefaultEvent } from "@calcom/features/eventtypes/lib/defaultEvents";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
import { withSelectedCalendars } from "@calcom/lib/server/repository/user";
import { withSelectedCalendars } from "@calcom/features/users/repositories/UserRepository";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -1,5 +1,5 @@
import dayjs from "@calcom/dayjs";
import { checkIfFreeEmailDomain } from "@calcom/lib/freeEmailDomainCheck/checkIfFreeEmailDomain";
import { checkIfFreeEmailDomain } from "@calcom/features/watchlist/lib/checkIfFreeEmailDomain";
import { withReporting } from "@calcom/lib/sentryWrapper";
import type { getEventTypeResponse } from "./getEventTypesFromDB";
@@ -9,7 +9,7 @@ import { HttpError } from "@calcom/lib/http-error";
import { getPiiFreeUser } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { withSelectedCalendars } from "@calcom/lib/server/repository/user";
import { withSelectedCalendars } from "@calcom/features/users/repositories/UserRepository";
import { userSelect } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
@@ -7,7 +7,7 @@ import {
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { withSelectedCalendars, UserRepository } from "@calcom/lib/server/repository/user";
import { withSelectedCalendars, UserRepository } from "@calcom/features/users/repositories/UserRepository";
import prisma, { userSelect } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -1,6 +1,6 @@
import { ErrorCode } from "@calcom/lib/errorCodes";
import { HttpError } from "@calcom/lib/http-error";
import { BookingRepository } from "@calcom/lib/server/repository/booking";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import type { Prisma } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
import prisma from "@calcom/prisma";
@@ -1,16 +1,16 @@
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { getAllDelegationCredentialsForUserIncludeServiceAccountKey } from "@calcom/app-store/delegationCredential";
import { getDelegationCredentialOrFindRegularCredential } from "@calcom/app-store/delegationCredential";
import { sendCancelledSeatEmailsAndSMS } from "@calcom/emails";
import { updateMeeting } from "@calcom/features/conferencing/lib/videoClient";
import { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import { getRichDescription } from "@calcom/lib/CalEventParser";
import { getAllDelegationCredentialsForUserIncludeServiceAccountKey } from "@calcom/app-store/delegationCredential";
import { getDelegationCredentialOrFindRegularCredential } from "@calcom/app-store/delegationCredential";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { updateMeeting } from "@calcom/features/conferencing/lib/videoClient";
import prisma from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { bookingCancelAttendeeSeatSchema } from "@calcom/prisma/zod-utils";
@@ -1,7 +1,7 @@
import type { Mock } from "vitest";
import { describe, expect, it, vi, afterEach } from "vitest";
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { FilterHostsService } from "./filterHostsBySameRoundRobinHost";
@@ -1,5 +1,5 @@
import { isRerouting } from "@calcom/lib/bookings/routing/utils";
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
export interface IFilterHostsService {
bookingRepo: BookingRepository;
@@ -5,7 +5,7 @@ import {
import type { EventType } from "@calcom/features/users/lib/getRoutedUsers";
import { withReporting } from "@calcom/lib/sentryWrapper";
import type { RoutingFormResponse } from "@calcom/features/bookings/lib/getLuckyUser";
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import type { SelectedCalendar } from "@calcom/prisma/client";
import type { SchedulingType } from "@calcom/prisma/enums";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
@@ -1,7 +1,7 @@
import { workflowSelect } from "@calcom/ee/workflows/lib/getAllWorkflows";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import { enrichUserWithDelegationCredentials } from "@calcom/app-store/delegationCredential";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
import { HttpError as HttpCode } from "@calcom/lib/http-error";
import { isPrismaObjOrUndefined } from "@calcom/lib/isPrismaObj";
import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
@@ -1,13 +1,13 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
// eslint-disable-next-line no-restricted-imports
import { PaymentServiceMap } from "@calcom/app-store/payment.services.generated";
import { sendNoShowFeeChargedEmail } from "@calcom/emails";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { ErrorWithCode } from "@calcom/lib/errors";
import { getTranslation } from "@calcom/lib/server/i18n";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { TeamRepository } from "@calcom/lib/server/repository/team";
import { handleNoShowFee } from "./handleNoShowFee";
@@ -37,7 +37,7 @@ vi.mock("@calcom/lib/server/repository/credential", () => ({
},
}));
vi.mock("@calcom/lib/server/repository/membership", () => ({
vi.mock("@calcom/features/membership/repositories/MembershipRepository", () => ({
MembershipRepository: {
findUniqueByUserIdAndTeamId: vi.fn(),
},
@@ -8,7 +8,7 @@ import { ErrorWithCode } from "@calcom/lib/errors";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { TeamRepository } from "@calcom/lib/server/repository/team";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
@@ -1,13 +1,13 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import type { Payment } from "@calcom/prisma/client";
import { handleNoShowFee } from "./handleNoShowFee";
import { processNoShowFeeOnCancellation } from "./processNoShowFeeOnCancellation";
import { shouldChargeNoShowCancellationFee } from "./shouldChargeNoShowCancellationFee";
vi.mock("@calcom/lib/server/repository/membership", () => ({
vi.mock("@calcom/features/membership/repositories/MembershipRepository", () => ({
MembershipRepository: {
findUniqueByUserIdAndTeamId: vi.fn(),
},
@@ -1,6 +1,6 @@
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
import logger from "@calcom/lib/logger";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import type { Payment } from "@calcom/prisma/client";
import { MembershipRole } from "@calcom/prisma/enums";
@@ -0,0 +1,256 @@
import prismaMock from "../../../../tests/libs/__mocks__/prisma";
import { describe, it, expect, beforeEach, vi } from "vitest";
import { BookingStatus, RRTimestampBasis } from "@calcom/prisma/enums";
import { BookingRepository } from "./BookingRepository";
const createAttendeeNoShowTestBookings = async () => {
await Promise.all([
prismaMock.booking.create({
data: {
userId: 1,
uid: "123",
eventTypeId: 1,
status: BookingStatus.ACCEPTED,
attendees: {
create: {
email: "[email protected]",
noShow: false,
name: "Test 1",
timeZone: "America/Toronto",
},
},
startTime: new Date("2025-05-01T00:00:00.000Z"),
endTime: new Date("2025-05-01T01:00:00.000Z"),
title: "Test Event",
},
}),
prismaMock.booking.create({
data: {
userId: 1,
uid: "123",
eventTypeId: 1,
status: BookingStatus.ACCEPTED,
attendees: {
create: {
email: "[email protected]",
noShow: true,
name: "Test 1",
timeZone: "America/Toronto",
},
},
startTime: new Date("2025-05-01T00:00:00.000Z"),
endTime: new Date("2025-05-01T01:00:00.000Z"),
title: "Test Event",
},
}),
]);
};
const createHostNoShowTestBookings = async () => {
await Promise.all([
prismaMock.booking.create({
data: {
userId: 1,
uid: "123",
eventTypeId: 1,
status: BookingStatus.ACCEPTED,
attendees: {
create: {
email: "[email protected]",
noShow: false,
name: "Test 1",
timeZone: "America/Toronto",
},
},
startTime: new Date("2025-05-01T00:00:00.000Z"),
endTime: new Date("2025-05-01T01:00:00.000Z"),
title: "Test Event",
noShowHost: false,
},
}),
prismaMock.booking.create({
data: {
userId: 1,
uid: "123",
eventTypeId: 1,
status: BookingStatus.ACCEPTED,
attendees: {
create: {
email: "[email protected]",
noShow: false,
name: "Test 1",
timeZone: "America/Toronto",
},
},
startTime: new Date("2025-05-01T00:00:00.000Z"),
endTime: new Date("2025-05-01T01:00:00.000Z"),
title: "Test Event",
noShowHost: true,
},
}),
]);
};
describe("BookingRepository", () => {
beforeEach(() => {
vi.setSystemTime(new Date("2025-05-01T00:00:00.000Z"));
vi.resetAllMocks();
});
describe("getAllBookingsForRoundRobin", () => {
describe("includeNoShowInRRCalculation", () => {
it("it should not include bookings where the attendee is a no show", async () => {
await createAttendeeNoShowTestBookings();
const bookingRepo = new BookingRepository(prismaMock);
const bookings = await bookingRepo.getAllBookingsForRoundRobin({
users: [{ id: 1, email: "[email protected]" }],
eventTypeId: 1,
startDate: new Date(),
endDate: new Date(),
includeNoShowInRRCalculation: false,
virtualQueuesData: null,
});
expect(bookings).toHaveLength(1);
});
it("it should include bookings where the attendee is a no show", async () => {
await createAttendeeNoShowTestBookings();
const bookingRepo = new BookingRepository(prismaMock);
const bookings = await bookingRepo.getAllBookingsForRoundRobin({
users: [{ id: 1, email: "[email protected]" }],
eventTypeId: 1,
startDate: new Date(),
endDate: new Date(),
includeNoShowInRRCalculation: true,
virtualQueuesData: null,
});
expect(bookings).toHaveLength(2);
});
it("it should not include bookings where the host is a no show", async () => {
await createHostNoShowTestBookings();
const bookingRepo = new BookingRepository(prismaMock);
const bookings = await bookingRepo.getAllBookingsForRoundRobin({
users: [{ id: 1, email: "[email protected]" }],
eventTypeId: 1,
startDate: new Date(),
endDate: new Date(),
includeNoShowInRRCalculation: false,
virtualQueuesData: null,
});
expect(bookings).toHaveLength(1);
});
it("it should include bookings where the host is a no show", async () => {
await createHostNoShowTestBookings();
const bookingRepo = new BookingRepository(prismaMock);
const bookings = await bookingRepo.getAllBookingsForRoundRobin({
users: [{ id: 1, email: "[email protected]" }],
eventTypeId: 1,
startDate: new Date(),
endDate: new Date(),
includeNoShowInRRCalculation: true,
virtualQueuesData: null,
});
expect(bookings).toHaveLength(2);
});
it("it should not include bookings where the host or an attendee is a no show", async () => {
await createHostNoShowTestBookings();
await createAttendeeNoShowTestBookings();
const bookingRepo = new BookingRepository(prismaMock);
const bookings = await bookingRepo.getAllBookingsForRoundRobin({
users: [{ id: 1, email: "[email protected]" }],
eventTypeId: 1,
startDate: new Date(),
endDate: new Date(),
includeNoShowInRRCalculation: false,
virtualQueuesData: null,
});
expect(bookings).toHaveLength(2);
});
it("it should include bookings where the host or an attendee is a no show", async () => {
await createHostNoShowTestBookings();
await createAttendeeNoShowTestBookings();
const bookingRepo = new BookingRepository(prismaMock);
const bookings = await bookingRepo.getAllBookingsForRoundRobin({
users: [{ id: 1, email: "[email protected]" }],
eventTypeId: 1,
startDate: new Date(),
endDate: new Date(),
includeNoShowInRRCalculation: true,
virtualQueuesData: null,
});
expect(bookings).toHaveLength(4);
});
});
it("should use start time as timestamp basis for the booking count", async () => {
await Promise.all([
prismaMock.booking.create({
data: {
userId: 1,
uid: "booking_may",
eventTypeId: 1,
status: BookingStatus.ACCEPTED,
attendees: {
create: {
email: "[email protected]",
noShow: false,
name: "Test 1",
timeZone: "America/Toronto",
},
},
startTime: new Date("2025-05-26T00:00:00.000Z"),
endTime: new Date("2025-05-26T01:00:00.000Z"),
createdAt: new Date("2025-05-03T00:00:00.000Z"),
title: "Test Event",
},
}),
prismaMock.booking.create({
data: {
userId: 1,
uid: "booking_june",
eventTypeId: 1,
status: BookingStatus.ACCEPTED,
attendees: {
create: {
email: "[email protected]",
noShow: true,
name: "Test 1",
timeZone: "America/Toronto",
},
},
startTime: new Date("2025-06-26T00:00:00.000Z"),
endTime: new Date("2025-06-26T01:00:00.000Z"),
createdAt: new Date("2025-05-03T00:00:00.000Z"),
title: "Test Event",
},
}),
]);
const bookingRepo = new BookingRepository(prismaMock);
const bookings = await bookingRepo.getAllBookingsForRoundRobin({
users: [{ id: 1, email: "[email protected]" }],
eventTypeId: 1,
startDate: new Date("2025-06-01T00:00:00.000Z"),
endDate: new Date("2025-06-30T23:59:00.000Z"),
includeNoShowInRRCalculation: true,
virtualQueuesData: null,
rrTimestampBasis: RRTimestampBasis.START_TIME,
});
expect(bookings).toHaveLength(1);
expect(bookings[0].startTime.toISOString()).toBe(new Date("2025-06-26T00:00:00.000Z").toISOString());
});
});
});
File diff suppressed because it is too large. Load diff
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { HttpError } from "@calcom/lib/http-error";
import type { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
import type { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
import { BotDetectionService } from "./BotDetectionService";
@@ -4,7 +4,7 @@ import type { IncomingHttpHeaders } from "http";
import type { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import type { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
import type { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
interface BotDetectionConfig {
eventTypeId?: number;
@@ -0,0 +1,284 @@
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import type { EventType } from "@calcom/features/availability/lib/getUserAvailability";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { getCheckBookingLimitsService } from "@calcom/features/di/containers/BookingLimits";
import { getBusyTimesService } from "@calcom/features/di/containers/BusyTimes";
import { descendingLimitKeys, intervalLimitKeyToUnit } from "@calcom/lib/intervalLimits/intervalLimit";
import type { IntervalLimit } from "@calcom/lib/intervalLimits/intervalLimitSchema";
import LimitManager from "@calcom/lib/intervalLimits/limitManager";
import { isBookingWithinPeriod } from "@calcom/lib/intervalLimits/utils";
import { getPeriodStartDatesBetween } from "@calcom/lib/intervalLimits/utils/getPeriodStartDatesBetween";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { performance } from "@calcom/lib/server/perfObserver";
import prisma from "@calcom/prisma";
import type { EventBusyDetails } from "@calcom/types/Calendar";
const _getBusyTimesFromLimits = async (
bookingLimits: IntervalLimit | null,
durationLimits: IntervalLimit | null,
dateFrom: Dayjs,
dateTo: Dayjs,
duration: number | undefined,
eventType: NonNullable<EventType>,
bookings: EventBusyDetails[],
timeZone: string,
rescheduleUid?: string
) => {
performance.mark("limitsStart");
// shared amongst limiters to prevent processing known busy periods
const limitManager = new LimitManager();
// run this first, as counting bookings should always run faster..
if (bookingLimits) {
performance.mark("bookingLimitsStart");
await getBusyTimesFromBookingLimits({
bookings,
bookingLimits,
dateFrom,
dateTo,
eventTypeId: eventType.id,
limitManager,
rescheduleUid,
timeZone,
});
performance.mark("bookingLimitsEnd");
performance.measure(`checking booking limits took $1'`, "bookingLimitsStart", "bookingLimitsEnd");
}
// ..than adding up durations (especially for the whole year)
if (durationLimits) {
performance.mark("durationLimitsStart");
await getBusyTimesFromDurationLimits(
bookings,
durationLimits,
dateFrom,
dateTo,
duration,
eventType,
limitManager,
timeZone,
rescheduleUid
);
performance.mark("durationLimitsEnd");
performance.measure(`checking duration limits took $1'`, "durationLimitsStart", "durationLimitsEnd");
}
performance.mark("limitsEnd");
performance.measure(`checking all limits took $1'`, "limitsStart", "limitsEnd");
return limitManager.getBusyTimes();
};
const _getBusyTimesFromBookingLimits = async (params: {
bookings: EventBusyDetails[];
bookingLimits: IntervalLimit;
dateFrom: Dayjs;
dateTo: Dayjs;
limitManager: LimitManager;
rescheduleUid?: string;
eventTypeId?: number;
teamId?: number;
user?: { id: number; email: string };
includeManagedEvents?: boolean;
timeZone?: string | null;
}) => {
const {
bookings,
bookingLimits,
dateFrom,
dateTo,
limitManager,
eventTypeId,
teamId,
user,
rescheduleUid,
includeManagedEvents = false,
timeZone,
} = params;
for (const key of descendingLimitKeys) {
const limit = bookingLimits?.[key];
if (!limit) continue;
const unit = intervalLimitKeyToUnit(key);
const periodStartDates = getPeriodStartDatesBetween(dateFrom, dateTo, unit);
for (const periodStart of periodStartDates) {
if (limitManager.isAlreadyBusy(periodStart, unit)) continue;
// special handling of yearly limits to improve performance
if (unit === "year") {
try {
const checkBookingLimitsService = getCheckBookingLimitsService();
await checkBookingLimitsService.checkBookingLimit({
eventStartDate: periodStart.toDate(),
limitingNumber: limit,
eventId: eventTypeId,
key,
teamId,
user,
rescheduleUid,
includeManagedEvents,
timeZone,
});
} catch (_) {
limitManager.addBusyTime(periodStart, unit);
if (periodStartDates.every((start) => limitManager.isAlreadyBusy(start, unit))) {
return;
}
}
continue;
}
const periodEnd = periodStart.endOf(unit);
let totalBookings = 0;
for (const booking of bookings) {
// consider booking part of period independent of end date
if (!isBookingWithinPeriod(booking, periodStart, periodEnd, timeZone || "UTC")) {
continue;
}
totalBookings++;
if (totalBookings >= limit) {
limitManager.addBusyTime(periodStart, unit);
break;
}
}
}
}
};
const _getBusyTimesFromDurationLimits = async (
bookings: EventBusyDetails[],
durationLimits: IntervalLimit,
dateFrom: Dayjs,
dateTo: Dayjs,
duration: number | undefined,
eventType: NonNullable<EventType>,
limitManager: LimitManager,
timeZone: string,
rescheduleUid?: string
) => {
for (const key of descendingLimitKeys) {
const limit = durationLimits?.[key];
if (!limit) continue;
const unit = intervalLimitKeyToUnit(key);
const periodStartDates = getPeriodStartDatesBetween(dateFrom, dateTo, unit);
for (const periodStart of periodStartDates) {
if (limitManager.isAlreadyBusy(periodStart, unit)) continue;
const selectedDuration = (duration || eventType.length) ?? 0;
if (selectedDuration > limit) {
limitManager.addBusyTime(periodStart, unit);
continue;
}
// special handling of yearly limits to improve performance
if (unit === "year") {
const bookingRepo = new BookingRepository(prisma);
const totalYearlyDuration = await bookingRepo.getTotalBookingDuration({
eventId: eventType.id,
startDate: periodStart.toDate(),
endDate: periodStart.endOf(unit).toDate(),
rescheduleUid,
});
if (totalYearlyDuration + selectedDuration > limit) {
limitManager.addBusyTime(periodStart, unit);
if (periodStartDates.every((start) => limitManager.isAlreadyBusy(start, unit))) {
return;
}
}
continue;
}
const periodEnd = periodStart.endOf(unit);
let totalDuration = selectedDuration;
for (const booking of bookings) {
// consider booking part of period independent of end date
if (!isBookingWithinPeriod(booking, periodStart, periodEnd, timeZone || "UTC")) {
continue;
}
totalDuration += dayjs(booking.end).diff(dayjs(booking.start), "minute");
if (totalDuration > limit) {
limitManager.addBusyTime(periodStart, unit);
break;
}
}
}
}
};
const getBusyTimesFromDurationLimits = withReporting(
_getBusyTimesFromDurationLimits,
"getBusyTimesFromDurationLimits"
);
const _getBusyTimesFromTeamLimits = async (
user: { id: number; email: string },
bookingLimits: IntervalLimit,
dateFrom: Dayjs,
dateTo: Dayjs,
teamId: number,
includeManagedEvents: boolean,
timeZone: string,
rescheduleUid?: string
) => {
const busyTimesService = getBusyTimesService();
const { limitDateFrom, limitDateTo } = busyTimesService.getStartEndDateforLimitCheck(
dateFrom.toISOString(),
dateTo.toISOString(),
bookingLimits
);
const bookingRepo = new BookingRepository(prisma);
const bookings = await bookingRepo.getAllAcceptedTeamBookingsOfUser({
user,
teamId,
startDate: limitDateFrom.toDate(),
endDate: limitDateTo.toDate(),
excludedUid: rescheduleUid,
includeManagedEvents,
});
const busyTimes = bookings.map(({ id, startTime, endTime, eventTypeId, title, userId }) => ({
start: dayjs(startTime).toDate(),
end: dayjs(endTime).toDate(),
title,
source: `eventType-${eventTypeId}-booking-${id}`,
userId,
}));
const limitManager = new LimitManager();
await getBusyTimesFromBookingLimits({
bookings: busyTimes,
bookingLimits,
dateFrom,
dateTo,
limitManager,
rescheduleUid,
teamId,
user,
includeManagedEvents,
timeZone,
});
return limitManager.getBusyTimes();
};
export const getBusyTimesFromLimits = withReporting(_getBusyTimesFromLimits, "getBusyTimesFromLimits");
export const getBusyTimesFromBookingLimits = withReporting(
_getBusyTimesFromBookingLimits,
"getBusyTimesFromBookingLimits"
);
export const getBusyTimesFromTeamLimits = withReporting(
_getBusyTimesFromTeamLimits,
"getBusyTimesFromTeamLimits"
);
@@ -0,0 +1,136 @@
import { prisma } from "@calcom/prisma/__mocks__/prisma";
import { describe, expect, it, vi } from "vitest";
import dayjs from "@calcom/dayjs";
import { getBusyTimesService } from "@calcom/features/di/containers/BusyTimes";
vi.mock("@calcom/prisma", () => ({
prisma,
}));
const startOfTomorrow = dayjs().add(1, "day").startOf("day");
const tomorrowDate = startOfTomorrow.format("YYYY-MM-DD");
const mockBookings = ({
beforeEventBuffer = 0,
afterEventBuffer = 0,
seatsPerTimeSlot,
}: {
beforeEventBuffer?: number;
afterEventBuffer?: number;
seatsPerTimeSlot?: number;
}) => [
{
id: 1,
startTime: startOfTomorrow.set("hour", 10).toDate(),
endTime: startOfTomorrow.set("hour", 11).toDate(),
title: "Booking Between X and Y",
userId: 1,
uid: "xxxx1",
eventType: {
id: 1,
beforeEventBuffer,
afterEventBuffer,
seatsPerTimeSlot: seatsPerTimeSlot ?? null,
},
_count: {
seatsReferences: 1,
},
},
{
id: 2,
startTime: startOfTomorrow.set("hour", 14).toDate(),
endTime: startOfTomorrow.set("hour", 15).toDate(),
title: "Booking Between X and Y",
userId: 1,
uid: "xxxx2",
eventType: {
id: 1,
beforeEventBuffer,
afterEventBuffer,
seatsPerTimeSlot: seatsPerTimeSlot ?? null,
},
...(seatsPerTimeSlot
? {
_count: {
seatsReferences: 1,
},
}
: {}),
},
];
describe("getBusyTimes", () => {
it("blocks a regular time slot", async () => {
const busyTimesService = getBusyTimesService();
const busyTimes = await busyTimesService.getBusyTimes({
credentials: [],
userId: 1,
userEmail: "[email protected]",
username: "exampleuser1",
bypassBusyCalendarTimes: false,
selectedCalendars: [],
startTime: startOfTomorrow.format(),
endTime: startOfTomorrow.endOf("day").format(),
currentBookings: mockBookings({}),
});
expect(busyTimes).toEqual([
expect.objectContaining({
start: dayjs(`${tomorrowDate}`).startOf("day").set("hour", 10).toDate(),
end: dayjs(`${tomorrowDate}`).startOf("day").set("hour", 11).toDate(),
source: "eventType-1-booking-1",
title: "Booking Between X and Y",
}),
expect.objectContaining({
start: dayjs(`${tomorrowDate}`).startOf("day").set("hour", 14).toDate(),
end: dayjs(`${tomorrowDate}`).startOf("day").set("hour", 15).toDate(),
source: "eventType-1-booking-2",
title: "Booking Between X and Y",
}),
]);
});
it("should block before and after buffer times", async () => {
const busyTimesService = getBusyTimesService();
const busyTimes = await busyTimesService.getBusyTimes({
credentials: [],
userId: 1,
userEmail: "[email protected]",
username: "exampleuser1",
bypassBusyCalendarTimes: false,
selectedCalendars: [],
startTime: startOfTomorrow.format(),
endTime: startOfTomorrow.endOf("day").format(),
currentBookings: [mockBookings({ beforeEventBuffer: 10 })[0]],
});
expect(busyTimes).toEqual([
expect.objectContaining({
start: dayjs(`${tomorrowDate}`).startOf("day").set("hour", 9).set("minute", 50).toDate(),
end: dayjs(`${tomorrowDate}`).startOf("day").set("hour", 11).toDate(),
source: "eventType-1-booking-1",
title: "Booking Between X and Y",
}),
]);
});
it("should have busy times only if seated with remaining seats when buffers exist", async () => {
const busyTimesService = getBusyTimesService();
const busyTimes = await busyTimesService.getBusyTimes({
credentials: [],
userId: 1,
eventTypeId: 1,
userEmail: "[email protected]",
username: "exampleuser1",
bypassBusyCalendarTimes: false,
selectedCalendars: [],
startTime: startOfTomorrow.format(),
endTime: startOfTomorrow.endOf("day").format(),
currentBookings: [mockBookings({ beforeEventBuffer: 10, seatsPerTimeSlot: 10 })[0]],
});
expect(busyTimes).toEqual([
expect.objectContaining({
start: dayjs(`${tomorrowDate}`).startOf("day").set("hour", 9).set("minute", 50).toDate(),
end: dayjs(`${tomorrowDate}`).startOf("day").set("hour", 10).toDate(),
}),
]);
});
});
@@ -0,0 +1,400 @@
import dayjs from "@calcom/dayjs";
import { getBusyCalendarTimes } from "@calcom/features/calendars/lib/CalendarManager";
import { getDefinedBufferTimes } from "@calcom/features/eventtypes/lib/getDefinedBufferTimes";
import { subtract } from "@calcom/lib/date-ranges";
import { stringToDayjs } from "@calcom/lib/dayjs";
import { intervalLimitKeyToUnit } from "@calcom/lib/intervalLimits/intervalLimit";
import type { IntervalLimit } from "@calcom/lib/intervalLimits/intervalLimitSchema";
import logger from "@calcom/lib/logger";
import { getPiiFreeBooking } from "@calcom/lib/piiFreeData";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { performance } from "@calcom/lib/server/perfObserver";
import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import prisma from "@calcom/prisma";
import type { Booking, EventType } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
import type { SelectedCalendar } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
import type { EventBusyDetails } from "@calcom/types/Calendar";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
export interface IBusyTimesService {
bookingRepo: BookingRepository;
}
export class BusyTimesService {
constructor(public readonly dependencies: IBusyTimesService) {}
async _getBusyTimes(params: {
credentials: CredentialForCalendarService[];
userId: number;
userEmail: string;
username: string;
eventTypeId?: number;
startTime: string;
beforeEventBuffer?: number;
afterEventBuffer?: number;
endTime: string;
selectedCalendars: SelectedCalendar[];
seatedEvent?: boolean;
rescheduleUid?: string | null;
duration?: number | null;
currentBookings?:
| (Pick<Booking, "id" | "uid" | "userId" | "startTime" | "endTime" | "title"> & {
eventType: Pick<
EventType,
"id" | "beforeEventBuffer" | "afterEventBuffer" | "seatsPerTimeSlot"
> | null;
_count?: {
seatsReferences: number;
};
})[]
| null;
bypassBusyCalendarTimes: boolean;
silentlyHandleCalendarFailures?: boolean;
shouldServeCache?: boolean;
}) {
const {
credentials,
userId,
userEmail,
username,
eventTypeId,
startTime,
endTime,
beforeEventBuffer,
afterEventBuffer,
selectedCalendars,
seatedEvent,
rescheduleUid,
duration,
bypassBusyCalendarTimes = false,
silentlyHandleCalendarFailures = false,
shouldServeCache,
} = params;
logger.silly(
`Checking Busy time from Cal Bookings in range ${startTime} to ${endTime} for input ${JSON.stringify({
userId,
eventTypeId,
status: BookingStatus.ACCEPTED,
})}`
);
/**
* A user is considered busy within a given time period if there
* is a booking they own OR attend.
*
* Performs a query for all bookings where:
* - The given booking is owned by this user, or..
* - The current user has a different booking at this time he/she attends
*
* See further discussion within this GH issue:
* https://github.com/calcom/cal.com/issues/6374
*
* NOTE: Changes here will likely require changes to some mocking
* logic within getSchedule.test.ts:addBookings
*/
performance.mark("prismaBookingGetStart");
const startTimeDate =
rescheduleUid && duration
? dayjs(startTime).subtract(duration, "minute").toDate()
: new Date(startTime);
const endTimeDate =
rescheduleUid && duration ? dayjs(endTime).add(duration, "minute").toDate() : new Date(endTime);
// to also get bookings that are outside of start and end time, but the buffer falls within the start and end time
const definedBufferTimes = getDefinedBufferTimes();
const maxBuffer = definedBufferTimes[definedBufferTimes.length - 1];
const startTimeAdjustedWithMaxBuffer = dayjs(startTimeDate).subtract(maxBuffer, "minute").toDate();
const endTimeAdjustedWithMaxBuffer = dayjs(endTimeDate).add(maxBuffer, "minute").toDate();
// INFO: Refactored to allow this method to take in a list of current bookings for the user.
// Will keep support for retrieving a user's bookings if the caller does not already supply them.
// This function is called from multiple places but we aren't refactoring all of them at this moment
// to avoid potential side effects.
let bookings = params.currentBookings;
if (!bookings) {
const bookingRepo = this.dependencies.bookingRepo;
bookings = await bookingRepo.findAllExistingBookingsForEventTypeBetween({
userIdAndEmailMap: new Map([[userId, userEmail]]),
eventTypeId,
startDate: startTimeAdjustedWithMaxBuffer,
endDate: endTimeAdjustedWithMaxBuffer,
seatedEvent,
});
}
const bookingSeatCountMap: { [x: string]: number } = {};
const busyTimes = bookings.reduce((aggregate: EventBusyDetails[], booking) => {
const { id, startTime, endTime, eventType, title, ...rest } = booking;
const minutesToBlockBeforeEvent = (eventType?.beforeEventBuffer || 0) + (afterEventBuffer || 0);
const minutesToBlockAfterEvent = (eventType?.afterEventBuffer || 0) + (beforeEventBuffer || 0);
if (rest._count?.seatsReferences) {
const bookedAt = `${dayjs(startTime).utc().format()}<>${dayjs(endTime).utc().format()}`;
bookingSeatCountMap[bookedAt] = bookingSeatCountMap[bookedAt] || 0;
bookingSeatCountMap[bookedAt]++;
// Seat references on the current event are non-blocking until the event is fully booked.
if (
// there are still seats available.
bookingSeatCountMap[bookedAt] < (eventType?.seatsPerTimeSlot || 1) &&
// and this is the seated event, other event types should be blocked.
eventTypeId === eventType?.id
) {
// then we ONLY add the before/after buffer times as busy times.
if (minutesToBlockBeforeEvent) {
aggregate.push({
start: dayjs(startTime).subtract(minutesToBlockBeforeEvent, "minute").toDate(),
end: dayjs(startTime).toDate(), // The event starts after the buffer
});
}
if (minutesToBlockAfterEvent) {
aggregate.push({
start: dayjs(endTime).toDate(), // The event ends before the buffer
end: dayjs(endTime).add(minutesToBlockAfterEvent, "minute").toDate(),
});
}
return aggregate;
}
// if it does get blocked at this point; we remove the bookingSeatCountMap entry
// doing this allows using the map later to remove the ranges from calendar busy times.
delete bookingSeatCountMap[bookedAt];
}
// rescheduling the same booking to the same time should be possible. Why?
if (rest.uid === rescheduleUid) {
return aggregate;
}
aggregate.push({
start: dayjs(startTime).subtract(minutesToBlockBeforeEvent, "minute").toDate(),
end: dayjs(endTime).add(minutesToBlockAfterEvent, "minute").toDate(),
title,
source: `eventType-${eventType?.id}-booking-${id}`,
});
return aggregate;
}, []);
logger.debug(
`Busy Time from Cal Bookings ${JSON.stringify({
busyTimes,
bookings: bookings?.map((booking) => getPiiFreeBooking(booking)),
numCredentials: credentials?.length,
})}`
);
performance.mark("prismaBookingGetEnd");
performance.measure(`prisma booking get took $1'`, "prismaBookingGetStart", "prismaBookingGetEnd");
if (credentials?.length > 0 && !bypassBusyCalendarTimes) {
const startConnectedCalendarsGet = performance.now();
const calendarBusyTimesQuery = await getBusyCalendarTimes(
credentials,
startTime,
endTime,
selectedCalendars,
shouldServeCache
);
if (!calendarBusyTimesQuery.success) {
if (silentlyHandleCalendarFailures) {
logger.warn(
`Calendar busy times fetch failed but handling silently due to silentlyHandleCalendarFailures flag for user ${username}`,
{
selectedCalendarIds: selectedCalendars.map((calendar) => calendar.id),
}
);
} else {
throw new Error(
`Failed to fetch busy calendar times for selected calendars ${selectedCalendars.map(
(calendar) => calendar.id
)}`
);
}
} else {
const calendarBusyTimes = calendarBusyTimesQuery.data;
const endConnectedCalendarsGet = performance.now();
logger.debug(
`Connected Calendars get took ${
endConnectedCalendarsGet - startConnectedCalendarsGet
} ms for user ${username}`,
JSON.stringify({
eventTypeId,
startTimeDate,
endTimeDate,
calendarBusyTimes,
})
);
const openSeatsDateRanges = Object.keys(bookingSeatCountMap).map((key) => {
const [start, end] = key.split("<>");
return {
start: dayjs(start),
end: dayjs(end),
};
});
if (rescheduleUid) {
const originalRescheduleBooking = bookings.find((booking) => booking.uid === rescheduleUid);
if (originalRescheduleBooking) {
openSeatsDateRanges.push({
start: dayjs(originalRescheduleBooking.startTime),
end: dayjs(originalRescheduleBooking.endTime),
});
}
}
const result = subtract(
calendarBusyTimes.map((value) => ({
...value,
end: dayjs(value.end),
start: dayjs(value.start),
})),
openSeatsDateRanges
);
busyTimes.push(
...result.map((busyTime) => ({
...busyTime,
start: busyTime.start.subtract(afterEventBuffer || 0, "minute").toDate(),
end: busyTime.end.add(beforeEventBuffer || 0, "minute").toDate(),
}))
);
}
/*
// TODO: Disabled until we can filter Zoom events by date. Also this is adding too much latency.
const videoBusyTimes = (await getBusyVideoTimes(credentials)).filter(notEmpty);
console.log("videoBusyTimes", videoBusyTimes);
busyTimes.push(...videoBusyTimes);
*/
} else {
logger.warn(`No credentials found for user ${userId}`, {
selectedCalendarIds: selectedCalendars.map((calendar) => calendar.id),
});
}
logger.debug(
"getBusyTimes:",
JSON.stringify({
allBusyTimes: busyTimes,
})
);
return busyTimes;
}
getBusyTimes = withReporting(this._getBusyTimes.bind(this), "getBusyTimes");
getStartEndDateforLimitCheck(
startDate: string,
endDate: string,
bookingLimits?: IntervalLimit | null,
durationLimits?: IntervalLimit | null
) {
const startTimeAsDayJs = stringToDayjs(startDate);
const endTimeAsDayJs = stringToDayjs(endDate);
let limitDateFrom = stringToDayjs(startDate);
let limitDateTo = stringToDayjs(endDate);
// expand date ranges by absolute minimum required to apply limits
// (yearly limits are handled separately for performance)
for (const key of ["PER_MONTH", "PER_WEEK", "PER_DAY"] as Exclude<keyof IntervalLimit, "PER_YEAR">[]) {
if (bookingLimits?.[key] || durationLimits?.[key]) {
const unit = intervalLimitKeyToUnit(key);
limitDateFrom = dayjs.min(limitDateFrom, startTimeAsDayJs.startOf(unit));
limitDateTo = dayjs.max(limitDateTo, endTimeAsDayJs.endOf(unit));
}
}
return { limitDateFrom, limitDateTo };
}
async getBusyTimesForLimitChecks(params: {
userIds: number[];
eventTypeId: number;
startDate: string;
endDate: string;
rescheduleUid?: string | null;
bookingLimits?: IntervalLimit | null;
durationLimits?: IntervalLimit | null;
}) {
const { userIds, eventTypeId, startDate, endDate, rescheduleUid, bookingLimits, durationLimits } = params;
performance.mark("getBusyTimesForLimitChecksStart");
let busyTimes: EventBusyDetails[] = [];
if (!bookingLimits && !durationLimits) {
return busyTimes;
}
const { limitDateFrom, limitDateTo } = this.getStartEndDateforLimitCheck(
startDate,
endDate,
bookingLimits,
durationLimits
);
logger.silly(
`Fetch limit checks bookings in range ${limitDateFrom} to ${limitDateTo} for input ${JSON.stringify({
eventTypeId,
status: BookingStatus.ACCEPTED,
})}`
);
const where: Prisma.BookingWhereInput = {
userId: {
in: userIds,
},
eventTypeId,
status: BookingStatus.ACCEPTED,
// FIXME: bookings that overlap on one side will never be counted
startTime: {
gte: limitDateFrom.toDate(),
},
endTime: {
lte: limitDateTo.toDate(),
},
};
if (rescheduleUid) {
where.NOT = {
uid: rescheduleUid,
};
}
const bookings = await prisma.booking.findMany({
where,
select: {
id: true,
startTime: true,
endTime: true,
eventType: {
select: {
id: true,
},
},
title: true,
userId: true,
},
});
busyTimes = bookings.map(({ id, startTime, endTime, eventType, title, userId }) => ({
start: dayjs(startTime).toDate(),
end: dayjs(endTime).toDate(),
title,
source: `eventType-${eventType?.id}-booking-${id}`,
userId,
}));
logger.silly(`Fetch limit checks bookings for eventId: ${eventTypeId} ${JSON.stringify(busyTimes)}`);
performance.mark("getBusyTimesForLimitChecksEnd");
performance.measure(
`prisma booking get for limits took $1'`,
"getBusyTimesForLimitChecksStart",
"getBusyTimesForLimitChecksEnd"
);
return busyTimes;
}
}
@@ -1,6 +1,6 @@
import type { CalendarSubscriptionEventItem } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionPort.interface";
import logger from "@calcom/lib/logger";
import { BookingRepository } from "@calcom/lib/server/repository/booking";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import type { SelectedCalendar } from "@calcom/prisma/client";
const log = logger.getSubLogger({ prefix: ["CalendarSyncService"] });
@@ -6,7 +6,7 @@ import {
import { isDelegationCredential } from "@calcom/lib/delegationCredential";
import logger from "@calcom/lib/logger";
import { DestinationCalendarRepository } from "@calcom/lib/server/repository/destinationCalendar";
import { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
import { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
@@ -8,8 +8,8 @@ import { describe, test, expect, beforeEach } from "vitest";
import { PrismaAppRepository } from "@calcom/features/apps/repository/PrismaAppRepository";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import { DestinationCalendarRepository } from "@calcom/lib/server/repository/destinationCalendar";
import { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import prisma from "@calcom/prisma";
const testUser = {
@@ -0,0 +1,14 @@
import tasker from "@calcom/features/tasker";
import { tasksConfig } from "@calcom/features/tasker/tasks";
class CRMScheduler {
static async createEvent({ bookingUid }: { bookingUid: string }) {
return tasker.create(
"createCRMEvent",
{ bookingUid },
{ maxAttempts: tasksConfig.createCRMEvent?.maxAttempts ?? 5 }
);
}
}
export default CRMScheduler;
@@ -0,0 +1,154 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it } from "vitest";
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { FilterSegmentRepository } from "../../repositories/filterSegment";
import type { TCreateFilterSegmentInputSchema } from "../../repositories/filterSegment.type";
const repository = new FilterSegmentRepository();
describe("FilterSegmentRepository.create()", () => {
const userId = 1;
const mockUser = {
id: userId,
name: "Test User",
} as NonNullable<TrpcSessionUser>;
const baseInput = {
tableIdentifier: "bookings",
activeFilters: [
{
f: "status",
v: {
type: ColumnFilterType.SINGLE_SELECT,
data: "active",
},
},
],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
searchTerm: "test search",
};
it("should create a user-scoped filter segment", async () => {
const input: TCreateFilterSegmentInputSchema = {
...baseInput,
scope: "USER",
name: "My Bookings",
};
const result = await repository.create({
userId,
input,
});
expect(result).toEqual(
expect.objectContaining({
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "My Bookings",
searchTerm: "test search",
})
);
});
it("should create a team-scoped filter segment for admin user", async () => {
// Create team membership first
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: 1,
accepted: true,
role: MembershipRole.ADMIN,
},
});
const input: TCreateFilterSegmentInputSchema = {
...baseInput,
scope: "TEAM",
teamId: 1,
name: "Team Bookings",
};
const result = await repository.create({
userId,
input,
});
expect(result).toEqual(
expect.objectContaining({
teamId: 1,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
searchTerm: "test search",
})
);
});
it("should throw error when creating team segment without admin role", async () => {
// Create team membership with MEMBER role
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: 1,
accepted: true,
role: MembershipRole.MEMBER,
},
});
const input: TCreateFilterSegmentInputSchema = {
...baseInput,
scope: "TEAM",
teamId: 1,
name: "Team Bookings",
};
await expect(
repository.create({
userId,
input,
})
).rejects.toThrow("You must be a team admin or owner to create team segments");
});
it("should throw error when creating team segment without teamId", async () => {
const invalidInput = {
...baseInput,
scope: "TEAM",
name: "Team Bookings",
};
await expect(
repository.create({
userId,
// @ts-expect-error - Testing invalid input where teamId is missing for TEAM scope
input: invalidInput,
})
).rejects.toThrow("Team ID is required for team scope");
});
it("should throw error when creating user segment with teamId", async () => {
const invalidInput = {
...baseInput,
scope: "USER",
name: "My Bookings",
teamId: 1,
};
await expect(
repository.create({
userId,
// @ts-expect-error - Testing invalid input where teamId is present for USER scope
input: invalidInput,
})
).rejects.toThrow("Team ID is not allowed for user scope");
});
});
@@ -0,0 +1,166 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it } from "vitest";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { FilterSegmentRepository } from "../../repositories/filterSegment";
import { type TDeleteFilterSegmentInputSchema } from "../../repositories/filterSegment.type";
const repository = new FilterSegmentRepository();
describe("FilterSegmentRepository.delete()", () => {
const userId = 1;
const mockUser = {
id: userId,
name: "Test User",
} as NonNullable<TrpcSessionUser>;
it("should delete a user-scoped filter segment", async () => {
// Create a user-scoped segment first
const segment = await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "My Bookings",
activeFilters: { f: "status" },
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
const input: TDeleteFilterSegmentInputSchema = {
id: segment.id,
};
await expect(
repository.delete({
userId,
id: segment.id,
})
).resolves.not.toThrow();
// Verify segment is deleted
const deletedSegment = await prismock.filterSegment.findUnique({
where: { id: segment.id },
});
expect(deletedSegment).toBeNull();
});
it("should delete a team-scoped filter segment for admin user", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.ADMIN,
},
});
// Create a team-scoped segment
const segment = await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
activeFilters: { f: "status" },
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
const input: TDeleteFilterSegmentInputSchema = {
id: segment.id,
};
await expect(
repository.delete({
userId,
id: segment.id,
})
).resolves.not.toThrow();
// Verify segment is deleted
const deletedSegment = await prismock.filterSegment.findUnique({
where: { id: segment.id },
});
expect(deletedSegment).toBeNull();
});
it("should throw error when deleting non-existent segment", async () => {
const input: TDeleteFilterSegmentInputSchema = {
id: 999,
};
await expect(
repository.delete({
userId,
id: 999,
})
).rejects.toThrow("Filter segment not found or you don't have permission to delete it");
});
it("should throw error when deleting team segment without admin role", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership with MEMBER role
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.MEMBER,
},
});
// Create a team-scoped segment
const segment = await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
activeFilters: { f: "status" },
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
const input: TDeleteFilterSegmentInputSchema = {
id: segment.id,
};
await expect(
repository.delete({
userId,
id: segment.id,
})
).rejects.toThrow("Filter segment not found or you don't have permission to delete it");
});
});
@@ -0,0 +1,337 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it } from "vitest";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { FilterSegmentRepository } from "../../repositories/filterSegment";
import { type TListFilterSegmentsInputSchema } from "../../repositories/filterSegment.type";
const repository = new FilterSegmentRepository();
describe("FilterSegmentRepository.get()", () => {
const userId = 1;
const mockUser = {
id: userId,
name: "Test User",
} as NonNullable<TrpcSessionUser>;
it("should return user-scoped filter segments", async () => {
// Create user-scoped segments
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "My Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "My Other Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 20,
},
});
const input: TListFilterSegmentsInputSchema = {
tableIdentifier: "bookings",
};
const result = await repository.get({
userId,
tableIdentifier: input.tableIdentifier,
});
expect(result.segments).toHaveLength(2);
expect(result.segments).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "My Other Bookings",
scope: "USER",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 20,
}),
expect.objectContaining({
name: "My Bookings",
scope: "USER",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
}),
])
);
});
it("should return team-scoped filter segments for team member", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.MEMBER,
},
});
// Create team-scoped segments
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Other Team Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 15,
},
});
const input: TListFilterSegmentsInputSchema = {
tableIdentifier: "bookings",
};
const result = await repository.get({
userId,
tableIdentifier: input.tableIdentifier,
});
expect(result.segments).toHaveLength(2);
expect(result.segments).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "Other Team Bookings",
scope: "TEAM",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 15,
}),
expect.objectContaining({
name: "Team Bookings",
scope: "TEAM",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
}),
])
);
});
it("should return both user-scoped and team-scoped segments", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.MEMBER,
},
});
// Create user-scoped segment
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "My Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
// Create team-scoped segment
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 15,
},
});
const input: TListFilterSegmentsInputSchema = {
tableIdentifier: "bookings",
};
const result = await repository.get({
userId,
tableIdentifier: input.tableIdentifier,
});
expect(result.segments).toHaveLength(2);
expect(result.segments).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "My Bookings",
scope: "USER",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
}),
expect.objectContaining({
name: "Team Bookings",
scope: "TEAM",
activeFilters: [{ f: "status" }],
sorting: [{ id: "date", desc: false }],
columnVisibility: {},
columnSizing: {},
perPage: 15,
}),
])
);
});
it("should return empty array when no segments exist", async () => {
const input: TListFilterSegmentsInputSchema = {
tableIdentifier: "bookings",
};
const result = await repository.get({
userId,
tableIdentifier: input.tableIdentifier,
});
expect(result).toEqual({
segments: [],
preferredSegmentId: null,
});
});
it("should return segments with user preferences", async () => {
// Create a filter segment
const segment = await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "contacts",
name: "Important Contacts",
activeFilters: [{ f: "priority" }],
sorting: [{ id: "lastContact", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 50,
},
});
// Create a user preference for this segment
await prismock.userFilterSegmentPreference.create({
data: {
userId: mockUser.id,
tableIdentifier: "contacts",
segmentId: segment.id,
},
});
const result = await repository.get({
userId: mockUser.id,
tableIdentifier: "contacts",
});
expect(result.segments).toHaveLength(1);
expect(result.preferredSegmentId).toEqual({ id: segment.id, type: "user" });
expect(result.segments[0].name).toBe("Important Contacts");
});
it("should handle segments with null JSON fields gracefully", async () => {
// Create segment with minimal data (some fields will be null/undefined)
await prismock.filterSegment.create({
data: {
userId: mockUser.id,
scope: "USER",
tableIdentifier: "reports",
name: "Basic Report",
activeFilters: undefined, // This should be parsed to []
sorting: undefined, // This should be parsed to []
columnVisibility: undefined, // This should be parsed to {}
columnSizing: undefined, // This should be parsed to {}
perPage: 10,
searchTerm: null,
},
});
const result = await repository.get({
userId: mockUser.id,
tableIdentifier: "reports",
});
expect(result.segments).toHaveLength(1);
expect(result.segments[0]).toEqual(
expect.objectContaining({
name: "Basic Report",
activeFilters: [], // Should default to empty array
sorting: [], // Should default to empty array
columnVisibility: {}, // Should default to empty object
columnSizing: {}, // Should default to empty object
perPage: 10,
})
);
});
});
@@ -0,0 +1,248 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it } from "vitest";
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { FilterSegmentRepository } from "../../repositories/filterSegment";
import { type TUpdateFilterSegmentInputSchema } from "../../repositories/filterSegment.type";
const repository = new FilterSegmentRepository();
describe("FilterSegmentRepository.update()", () => {
const userId = 1;
const mockUser = {
id: userId,
name: "Test User",
} as NonNullable<TrpcSessionUser>;
const baseInput = {
tableIdentifier: "bookings",
activeFilters: [
{
f: "status",
v: {
type: ColumnFilterType.SINGLE_SELECT,
data: "active",
},
},
],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
searchTerm: "test search",
};
it("should update a user-scoped filter segment", async () => {
// Create a user-scoped segment first
const segment = await prismock.filterSegment.create({
data: {
...baseInput,
userId: mockUser.id,
scope: "USER",
name: "My Bookings",
},
});
const input: TUpdateFilterSegmentInputSchema = {
...baseInput,
id: segment.id,
scope: "USER",
name: "Updated Bookings",
searchTerm: "updated search",
activeFilters: [
{
f: "status",
v: {
type: ColumnFilterType.SINGLE_SELECT,
data: "inactive",
},
},
],
};
const result = await repository.update({
userId,
input,
});
expect(result).toEqual(
expect.objectContaining({
userId: mockUser.id,
scope: "USER",
tableIdentifier: "bookings",
name: "Updated Bookings",
searchTerm: "updated search",
activeFilters: [
{
f: "status",
v: { type: ColumnFilterType.SINGLE_SELECT, data: "inactive" },
},
],
})
);
});
it("should update a team-scoped filter segment for admin user", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership first
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.ADMIN,
},
});
// Create a team-scoped segment
const segment = await prismock.filterSegment.create({
data: {
...baseInput,
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
name: "Team Bookings",
},
});
const input: TUpdateFilterSegmentInputSchema = {
id: segment.id,
scope: "TEAM",
teamId: team.id,
name: "Updated Team Bookings",
searchTerm: "updated search",
activeFilters: [
{
f: "status",
v: {
type: ColumnFilterType.SINGLE_SELECT,
data: "inactive",
},
},
],
};
const result = await repository.update({
userId,
input,
});
expect(result).toEqual(
expect.objectContaining({
id: segment.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Updated Team Bookings",
searchTerm: "updated search",
activeFilters: [
{
f: "status",
v: { type: ColumnFilterType.SINGLE_SELECT, data: "inactive" },
},
],
})
);
});
it("should throw error when updating non-existent segment", async () => {
const input: TUpdateFilterSegmentInputSchema = {
id: 999,
scope: "USER",
name: "Updated Bookings",
activeFilters: [
{
f: "status",
v: { type: ColumnFilterType.SINGLE_SELECT, data: "inactive" },
},
],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
};
await expect(
repository.update({
userId,
input,
})
).rejects.toThrow("Filter segment not found or you don't have permission to update it");
});
it("should throw error when updating team segment without admin role", async () => {
// Create team first
const team = await prismock.team.create({
data: {
name: "Test Team",
slug: "test-team",
},
});
// Create team membership with MEMBER role
await prismock.membership.create({
data: {
userId: mockUser.id,
teamId: team.id,
accepted: true,
role: MembershipRole.MEMBER,
},
});
// Create a team-scoped segment
const segment = await prismock.filterSegment.create({
data: {
userId: mockUser.id,
teamId: team.id,
scope: "TEAM",
tableIdentifier: "bookings",
name: "Team Bookings",
activeFilters: [
{
f: "status",
v: { type: ColumnFilterType.SINGLE_SELECT, data: "active" },
},
],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
},
});
const input: TUpdateFilterSegmentInputSchema = {
id: segment.id,
scope: "TEAM",
teamId: team.id,
name: "Updated Team Bookings",
activeFilters: [
{
f: "status",
v: { type: ColumnFilterType.SINGLE_SELECT, data: "inactive" },
},
],
sorting: [{ id: "date", desc: true }],
columnVisibility: {},
columnSizing: {},
perPage: 10,
};
await expect(
repository.update({
userId,
input,
})
).rejects.toThrow("Filter segment not found or you don't have permission to update it");
});
});
@@ -0,0 +1,395 @@
import type { FilterSegmentOutput, SegmentIdentifier } from "@calcom/features/data-table/lib/types";
import {
ZActiveFilters,
ZSortingState,
ZColumnSizing,
ZColumnVisibility,
} from "@calcom/features/data-table/lib/types";
import { prisma } from "@calcom/prisma";
import type { UserFilterSegmentPreference } from "@calcom/prisma/client";
import type { TCreateFilterSegmentInputSchema, TUpdateFilterSegmentInputSchema } from "./filterSegment.type";
export interface IFilterSegmentRepository {
get({ userId, tableIdentifier }: { userId: number; tableIdentifier: string }): Promise<{
segments: FilterSegmentOutput[];
preferredSegmentId: SegmentIdentifier | null;
}>;
create({
userId,
input,
}: {
userId: number;
input: TCreateFilterSegmentInputSchema;
}): Promise<FilterSegmentOutput>;
update({
userId,
input,
}: {
userId: number;
input: TUpdateFilterSegmentInputSchema;
}): Promise<FilterSegmentOutput>;
delete({ userId, id }: { userId: number; id: number }): Promise<void>;
setPreference({
userId,
tableIdentifier,
segmentId,
}: {
userId: number;
tableIdentifier: string;
segmentId: SegmentIdentifier | null;
}): Promise<UserFilterSegmentPreference | null>;
}
export class FilterSegmentRepository implements IFilterSegmentRepository {
async get({ userId, tableIdentifier }: { userId: number; tableIdentifier: string }) {
// Get all teams that the user is a member of
const userTeamIds = await prisma.membership
.findMany({
where: {
userId,
accepted: true,
},
select: {
teamId: true,
},
})
.then((memberships) => memberships.map((m) => m.teamId));
// Fetch both user-scoped and team-scoped segments
const segments = await prisma.filterSegment.findMany({
where: {
tableIdentifier,
OR: [
// User-scoped segments created by the current user
{
scope: "USER",
userId,
},
// Team-scoped segments for teams the user belongs to
{
scope: "TEAM",
teamId: {
in: userTeamIds,
},
},
],
},
select: {
id: true,
name: true,
tableIdentifier: true,
scope: true,
activeFilters: true,
sorting: true,
columnVisibility: true,
columnSizing: true,
perPage: true,
searchTerm: true,
createdAt: true,
updatedAt: true,
userId: true,
teamId: true,
team: {
select: {
id: true,
name: true,
},
},
},
orderBy: [
{ scope: "desc" }, // USER segments first, then TEAM segments
{ createdAt: "desc" }, // Newest first within each scope
],
});
const parsedSegments: FilterSegmentOutput[] = segments.map((segment) => ({
...segment,
activeFilters: ZActiveFilters.catch([]).parse(segment.activeFilters),
sorting: ZSortingState.catch([]).parse(segment.sorting),
columnVisibility: ZColumnVisibility.catch({}).parse(segment.columnVisibility),
columnSizing: ZColumnSizing.catch({}).parse(segment.columnSizing),
}));
const preference = await prisma.userFilterSegmentPreference.findUnique({
where: {
userId_tableIdentifier: {
userId,
tableIdentifier,
},
},
select: {
segmentId: true,
systemSegmentId: true,
},
});
const preferredSegmentId = preference?.segmentId
? { id: preference.segmentId, type: "user" as const }
: preference?.systemSegmentId
? { id: preference.systemSegmentId, type: "system" as const }
: null;
return {
segments: parsedSegments,
preferredSegmentId,
};
}
async create({ userId, input }: { userId: number; input: TCreateFilterSegmentInputSchema }) {
const { scope, teamId, ...filterData } = input;
// If scope is TEAM, verify user has admin/owner permissions
if (scope === "TEAM") {
if (!teamId) {
throw new Error("Team ID is required for team scope");
}
const membership = await prisma.membership.findFirst({
select: {
id: true,
},
where: {
userId,
teamId,
accepted: true,
role: {
in: ["ADMIN", "OWNER"],
},
},
});
if (!membership) {
throw new Error("You must be a team admin or owner to create team segments");
}
}
// For USER scope, ensure no teamId is provided
if (scope === "USER" && teamId) {
throw new Error("Team ID is not allowed for user scope");
}
// Create the filter segment
const filterSegment = await prisma.filterSegment.create({
data: {
...filterData,
scope,
...(scope === "TEAM" ? { teamId } : {}),
userId,
},
select: {
id: true,
name: true,
tableIdentifier: true,
scope: true,
activeFilters: true,
sorting: true,
columnVisibility: true,
columnSizing: true,
perPage: true,
searchTerm: true,
createdAt: true,
updatedAt: true,
userId: true,
teamId: true,
team: {
select: {
id: true,
name: true,
},
},
},
});
// Parse the segment with Zod schemas
const parsedSegment: FilterSegmentOutput = {
...filterSegment,
activeFilters: ZActiveFilters.catch([]).parse(filterSegment.activeFilters),
sorting: ZSortingState.catch([]).parse(filterSegment.sorting),
columnVisibility: ZColumnVisibility.catch({}).parse(filterSegment.columnVisibility),
columnSizing: ZColumnSizing.catch({}).parse(filterSegment.columnSizing),
};
return parsedSegment;
}
async update({ userId, input }: { userId: number; input: TUpdateFilterSegmentInputSchema }) {
const { id, name, activeFilters, sorting, columnVisibility, columnSizing, perPage, searchTerm } = input;
// First, fetch the existing segment to check permissions
const existingSegment = await prisma.filterSegment.findFirst({
where: {
id,
...(input.scope === "TEAM"
? {
scope: "TEAM",
teamId: input.teamId,
team: {
members: {
some: {
userId,
accepted: true,
role: {
in: ["ADMIN", "OWNER"],
},
},
},
},
}
: {
scope: "USER",
userId,
}),
},
select: {
id: true,
},
});
if (!existingSegment) {
throw new Error("Filter segment not found or you don't have permission to update it");
}
// Update the filter segment with only the allowed fields
const updatedSegment = await prisma.filterSegment.update({
where: { id },
data: {
name,
activeFilters,
sorting,
columnVisibility,
columnSizing,
perPage,
searchTerm,
},
select: {
id: true,
name: true,
tableIdentifier: true,
scope: true,
activeFilters: true,
sorting: true,
columnVisibility: true,
columnSizing: true,
perPage: true,
searchTerm: true,
createdAt: true,
updatedAt: true,
userId: true,
teamId: true,
team: {
select: {
id: true,
name: true,
},
},
},
});
// Parse the segment with Zod schemas
const parsedSegment: FilterSegmentOutput = {
...updatedSegment,
activeFilters: ZActiveFilters.catch([]).parse(updatedSegment.activeFilters),
sorting: ZSortingState.catch([]).parse(updatedSegment.sorting),
columnVisibility: ZColumnVisibility.catch({}).parse(updatedSegment.columnVisibility),
columnSizing: ZColumnSizing.catch({}).parse(updatedSegment.columnSizing),
};
return parsedSegment;
}
async delete({ userId, id }: { userId: number; id: number }) {
// First, fetch the existing segment to check permissions
const existingSegment = await prisma.filterSegment.findFirst({
where: {
id,
OR: [
{
scope: "TEAM",
teamId: { not: null },
team: {
members: {
some: {
userId,
accepted: true,
role: {
in: ["ADMIN", "OWNER"],
},
},
},
},
},
{
scope: "USER",
userId,
},
],
},
select: {
id: true,
},
});
if (!existingSegment) {
throw new Error("Filter segment not found or you don't have permission to delete it");
}
// Delete the filter segment
await prisma.filterSegment.delete({
where: { id },
});
}
async setPreference({
userId,
tableIdentifier,
segmentId,
}: {
userId: number;
tableIdentifier: string;
segmentId: SegmentIdentifier | null;
}) {
if (segmentId === null) {
await prisma.userFilterSegmentPreference.deleteMany({
where: {
userId,
tableIdentifier,
},
});
return null;
}
const isSystemSegment = segmentId.type === "system";
const updateData = isSystemSegment
? {
segmentId: null,
systemSegmentId: segmentId.id,
}
: {
segmentId: segmentId.id,
systemSegmentId: null,
};
const preference = await prisma.userFilterSegmentPreference.upsert({
where: {
userId_tableIdentifier: {
userId,
tableIdentifier,
},
},
update: updateData,
create: {
userId,
tableIdentifier,
...updateData,
},
});
return preference;
}
}
@@ -0,0 +1,99 @@
import { z } from "zod";
import {
ZActiveFilters,
ZSortingState,
ZColumnSizing,
ZColumnVisibility,
} from "@calcom/features/data-table/lib/types";
export const ZListFilterSegmentsInputSchema = z.object({
tableIdentifier: z.string(),
});
export type TListFilterSegmentsInputSchema = z.infer<typeof ZListFilterSegmentsInputSchema>;
export const ZDeleteFilterSegmentInputSchema = z.object({
id: z.number().int().positive(),
});
export type TDeleteFilterSegmentInputSchema = z.infer<typeof ZDeleteFilterSegmentInputSchema>;
// Base schema for common fields
const baseCreateSchema = {
name: z.string().min(1),
tableIdentifier: z.string().min(1),
activeFilters: ZActiveFilters.optional(),
sorting: ZSortingState.optional(),
columnVisibility: ZColumnVisibility.optional(),
columnSizing: ZColumnSizing.optional(),
searchTerm: z.string().nullable().optional(),
perPage: z.number().int().min(1),
};
// Schema for team scope - requires teamId
const teamCreateSchema = z.object({
scope: z.literal("TEAM"),
teamId: z.number().int().positive(),
...baseCreateSchema,
});
// Schema for user scope - no teamId allowed
const userCreateSchema = z.object({
scope: z.literal("USER"),
teamId: z.undefined().optional(),
...baseCreateSchema,
});
export const ZCreateFilterSegmentInputSchema = z.discriminatedUnion("scope", [
teamCreateSchema,
userCreateSchema,
]);
export type TCreateFilterSegmentInputSchema = z.infer<typeof ZCreateFilterSegmentInputSchema>;
const ZSegmentIdentifier = z.discriminatedUnion("type", [
z.object({ id: z.string(), type: z.literal("system") }),
z.object({ id: z.number(), type: z.literal("user") }),
]);
export const ZSetFilterSegmentPreferenceInputSchema = z.object({
tableIdentifier: z.string(),
segmentId: ZSegmentIdentifier.nullable(),
});
export type TSetFilterSegmentPreferenceInputSchema = z.infer<typeof ZSetFilterSegmentPreferenceInputSchema>;
// Base schema for common fields that can be updated
const baseUpdateSchema = {
name: z.string().min(1).optional(),
tableIdentifier: z.string().min(1).optional(),
activeFilters: ZActiveFilters.optional(),
sorting: ZSortingState.optional(),
columnVisibility: ZColumnVisibility.optional(),
columnSizing: ZColumnSizing.optional(),
searchTerm: z.string().nullable().optional(),
perPage: z.number().int().min(1).optional(),
};
// Schema for team scope updates
const teamUpdateSchema = z.object({
id: z.number().int().positive(),
scope: z.literal("TEAM"),
teamId: z.number().int().positive(),
...baseUpdateSchema,
});
// Schema for user scope updates
const userUpdateSchema = z.object({
id: z.number().int().positive(),
scope: z.literal("USER"),
...baseUpdateSchema,
});
export const ZUpdateFilterSegmentInputSchema = z.discriminatedUnion("scope", [
teamUpdateSchema,
userUpdateSchema,
]);
export type TUpdateFilterSegmentInputSchema = z.infer<typeof ZUpdateFilterSegmentInputSchema>;
@@ -1,5 +1,5 @@
import { DI_TOKENS } from "@calcom/features/di/tokens";
import type { CheckBookingLimitsService } from "@calcom/lib/intervalLimits/server/checkBookingLimits";
import type { CheckBookingLimitsService } from "@calcom/features/bookings/lib/checkBookingLimits";
import { prismaModule } from "@calcom/prisma/prisma.module";
import type { CheckBookingAndDurationLimitsService } from "../../bookings/lib/handleNewBooking/checkBookingAndDurationLimits";
+1 -1
View File
@@ -1,7 +1,7 @@
import type { BusyTimesService } from "@calcom/features/busyTimes/services/getBusyTimes";
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { prismaModule } from "@calcom/prisma/prisma.module";
import type { BusyTimesService } from "@calcom/lib/getBusyTimes";
import { createContainer } from "../di";
import { bookingRepositoryModule } from "../modules/Booking";
import { busyTimesModule } from "../modules/BusyTimes";
@@ -3,8 +3,8 @@ import type {
InsightsBookingServicePublicOptions,
InsightsBookingServiceFilterOptions,
InsightsBookingBaseService,
} from "@calcom/lib/server/service/InsightsBookingBaseService";
import type { InsightsBookingService } from "@calcom/lib/server/service/InsightsBookingDIService";
} from "@calcom/features/insights/services/InsightsBookingBaseService";
import type { InsightsBookingService } from "@calcom/features/insights/services/InsightsBookingDIService";
import { prismaModule } from "@calcom/prisma/prisma.module";
import { createContainer } from "../di";
@@ -3,8 +3,8 @@ import type {
InsightsRoutingServicePublicOptions,
InsightsRoutingServiceFilterOptions,
InsightsRoutingBaseService,
} from "@calcom/lib/server/service/InsightsRoutingBaseService";
import type { InsightsRoutingService } from "@calcom/lib/server/service/InsightsRoutingDIService";
} from "@calcom/features/insights/services/InsightsRoutingBaseService";
import type { InsightsRoutingService } from "@calcom/features/insights/services/InsightsRoutingDIService";
import { prismaModule } from "@calcom/prisma/prisma.module";
import { createContainer } from "../di";
+1 -1
View File
@@ -1,5 +1,5 @@
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { BookingRepository } from "@calcom/lib/server/repository/booking";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { type Container, createModule } from "../di";
+3 -2
View File
@@ -1,5 +1,6 @@
import type { IBusyTimesService } from "@calcom/lib/getBusyTimes";
import { BusyTimesService } from "@calcom/lib/getBusyTimes";
import type { IBusyTimesService } from "@calcom/features/busyTimes/services/getBusyTimes";
import { BusyTimesService } from "@calcom/features/busyTimes/services/getBusyTimes";
import { createModule } from "../di";
import { DI_TOKENS } from "../tokens";
@@ -1,5 +1,5 @@
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { CheckBookingLimitsService } from "@calcom/lib/intervalLimits/server/checkBookingLimits";
import { CheckBookingLimitsService } from "@calcom/features/bookings/lib/checkBookingLimits";
import { type Container, createModule } from "../di";
+1 -1
View File
@@ -1,5 +1,5 @@
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
import { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
import { createModule } from "../di";
@@ -1,5 +1,5 @@
import type { IInsightsBookingService } from "@calcom/lib/server/service/InsightsBookingDIService";
import { InsightsBookingService } from "@calcom/lib/server/service/InsightsBookingDIService";
import type { IInsightsBookingService } from "@calcom/features/insights/services/InsightsBookingDIService";
import { InsightsBookingService } from "@calcom/features/insights/services/InsightsBookingDIService";
import { createModule } from "../di";
import { DI_TOKENS } from "../tokens";
@@ -1,5 +1,5 @@
import type { IInsightsRoutingService } from "@calcom/lib/server/service/InsightsRoutingDIService";
import { InsightsRoutingService } from "@calcom/lib/server/service/InsightsRoutingDIService";
import type { IInsightsRoutingService } from "@calcom/features/insights/services/InsightsRoutingDIService";
import { InsightsRoutingService } from "@calcom/features/insights/services/InsightsRoutingDIService";
import { createModule } from "../di";
import { DI_TOKENS } from "../tokens";
+1 -1
View File
@@ -1,5 +1,5 @@
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { createModule } from "../di";
+1 -1
View File
@@ -1,5 +1,5 @@
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { moduleLoader as prismaModuleLoader } from "@calcom/prisma/prisma.module";
import { createModule, bindModuleToClassOnToken, type ModuleLoader } from "../di";
@@ -0,0 +1,335 @@
import type { RatelimitResponse } from "@unkey/ratelimit";
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import { hashAPIKey } from "@calcom/features/ee/api-keys/lib/apiKeys";
import { RedisService } from "@calcom/features/redis/RedisService";
import prisma from "@calcom/prisma";
import { handleAutoLock } from "./autoLock";
// Mock the dependencies
vi.mock("@calcom/features/redis/RedisService");
vi.mock("@calcom/features/ee/api-keys/lib/apiKeys", () => ({
hashAPIKey: vi.fn((key) => `hashed_${key}`),
}));
vi.mock("@calcom/prisma", () => ({
default: {
user: {
update: vi.fn(),
},
apiKey: {
findUnique: vi.fn(),
},
},
}));
describe("autoLock", () => {
const mockRedis = {
get: vi.fn(),
set: vi.fn(),
del: vi.fn(),
expire: vi.fn(),
};
beforeEach(() => {
// Reset all mocks before each test
vi.clearAllMocks();
vi.mocked(RedisService).mockImplementation(() => mockRedis as any);
// Mock environment variables
process.env.UPSTASH_REDIS_REST_TOKEN = "test-token";
process.env.UPSTASH_REDIS_REST_URL = "test-url";
});
afterEach(() => {
delete process.env.UPSTASH_REDIS_REST_TOKEN;
delete process.env.UPSTASH_REDIS_REST_URL;
});
describe("handleAutoLock", () => {
it("should return early if Upstash env variables are not set", async () => {
delete process.env.UPSTASH_REDIS_REST_TOKEN;
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
await handleAutoLock({
identifier: "[email protected]",
identifierType: "email",
rateLimitResponse,
});
expect(mockRedis.get).not.toHaveBeenCalled();
});
it("should handle identifier with keyword correctly", async () => {
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
mockRedis.get.mockResolvedValue("0");
await handleAutoLock({
identifier: "[email protected]",
identifierType: "email",
rateLimitResponse,
identifierKeyword: "addSecondaryEmail",
});
expect(mockRedis.get).toHaveBeenCalledWith("autolock:email:addSecondaryEmail:[email protected]");
});
it("should increment counter when below threshold", async () => {
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
mockRedis.get.mockResolvedValue("2");
await handleAutoLock({
identifier: "[email protected]",
identifierType: "email",
rateLimitResponse,
});
expect(mockRedis.set).toHaveBeenCalledWith("autolock:email:[email protected]", "3");
expect(mockRedis.expire).toHaveBeenCalledWith("autolock:email:[email protected]", 1800);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("should lock user when threshold is reached", async () => {
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
mockRedis.get.mockResolvedValue("4");
await handleAutoLock({
identifier: "[email protected]",
identifierType: "email",
rateLimitResponse,
});
expect(prisma.user.update).toHaveBeenCalledWith({
where: { email: "[email protected]" },
data: { locked: true },
select: {
id: true,
email: true,
username: true,
},
});
expect(mockRedis.del).toHaveBeenCalledWith("autolock:email:[email protected]");
});
it("should respect custom threshold and duration", async () => {
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
mockRedis.get.mockResolvedValue("1");
await handleAutoLock({
identifier: "[email protected]",
identifierType: "email",
rateLimitResponse,
autolockThreshold: 3,
autolockDuration: 30 * 60 * 1000, // 30 minutes
});
expect(mockRedis.set).toHaveBeenCalledWith("autolock:email:[email protected]", "2");
expect(mockRedis.expire).toHaveBeenCalledWith("autolock:email:[email protected]", 1800);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("should lock API key and associated user", async () => {
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
mockRedis.get.mockResolvedValue("4");
const testApiKey = "test_api_key_123";
// Mock API key lookup
vi.mocked(prisma.apiKey.findUnique).mockResolvedValue({
hashedKey: `hashed_${testApiKey}`,
user: { id: 456 },
} as any);
await handleAutoLock({
identifier: testApiKey,
identifierType: "apiKey",
rateLimitResponse,
});
// Verify the API key was hashed
expect(hashAPIKey).toHaveBeenCalledWith(testApiKey);
// Verify the associated user was locked
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: 456 },
data: { locked: true },
select: {
id: true,
email: true,
username: true,
},
});
});
it("should throw error when API key has no associated user", async () => {
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
mockRedis.get.mockResolvedValue("4"); // Over threshold to trigger lock
const testApiKey = "test_api_key_123";
// Mock API key lookup with no user
vi.mocked(prisma.apiKey.findUnique).mockResolvedValue(null);
// Expect handleAutoLock to throw the error from lockUser
await expect(async () => {
await handleAutoLock({
identifier: testApiKey,
identifierType: "apiKey",
rateLimitResponse,
});
}).rejects.toThrow("No user found for this API key.");
});
it("should not increment counter when rate limit is successful", async () => {
const rateLimitResponse: RatelimitResponse = {
success: true,
remaining: 5,
limit: 5,
reset: 0,
};
await handleAutoLock({
identifier: "[email protected]",
identifierType: "email",
rateLimitResponse,
});
expect(mockRedis.get).not.toHaveBeenCalled();
expect(mockRedis.set).not.toHaveBeenCalled();
});
it("should initialize counter when it doesn't exist", async () => {
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
mockRedis.get.mockResolvedValue(null);
await handleAutoLock({
identifier: "[email protected]",
identifierType: "email",
rateLimitResponse,
});
expect(mockRedis.set).toHaveBeenCalledWith("autolock:email:[email protected]", "1");
expect(mockRedis.expire).toHaveBeenCalledWith("autolock:email:[email protected]", 1800);
});
it("should handle Redis errors gracefully", async () => {
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
mockRedis.get.mockRejectedValue(new Error("Redis connection error"));
const result = await handleAutoLock({
identifier: "[email protected]",
identifierType: "email",
rateLimitResponse,
});
expect(result).toBe(false);
});
});
describe("lockUser", () => {
it("should lock user by email", async () => {
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
mockRedis.get.mockResolvedValue("4");
await handleAutoLock({
identifier: "[email protected]",
identifierType: "email",
rateLimitResponse,
});
expect(prisma.user.update).toHaveBeenCalledWith({
where: { email: "[email protected]" },
data: { locked: true },
select: {
id: true,
email: true,
username: true,
},
});
});
it("should lock user by userId", async () => {
const rateLimitResponse: RatelimitResponse = {
success: false,
remaining: 0,
limit: 5,
reset: 0,
};
mockRedis.get.mockResolvedValue("4");
await handleAutoLock({
identifier: "123",
identifierType: "userId",
rateLimitResponse,
});
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: 123 },
data: { locked: true },
select: {
id: true,
email: true,
username: true,
},
});
});
});
});
@@ -0,0 +1,177 @@
import type { RatelimitResponse } from "@unkey/ratelimit";
import { RedisService } from "@calcom/features/redis/RedisService";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
import { hashAPIKey } from "./apiKeys";
// This is the number of times a user can exceed the rate limit before being locked
const DEFAULT_AUTOLOCK_THRESHOLD = 5;
// This is the duration of the rate limit check window
const DEFAULT_CHECK_THRESHOLD_WINDOW_DURATION = 60 * 30 * 1000; // 30 minutes in milliseconds
interface HandleAutoLockInput {
identifier: string;
identifierType: "email" | "userId" | "SMS" | "apiKey";
rateLimitResponse: RatelimitResponse;
identifierKeyword?: string; // For instances where we have like "addSecondaryEmail.${email}"
autolockThreshold?: number;
autolockDuration?: number; // in milliseconds
}
export enum LockReason {
RATE_LIMIT = "Auto-locking user due to rate limit exceeded",
SPAM_WORKFLOW_BODY = "Auto-locking user due to spam detected in workflow body",
}
const log = logger.getSubLogger({ prefix: ["[autoLock]"] });
/**
* The "Requests to Hit Limit × Threshold" shows how many requests would be needed to trigger an auto-lock if a user consistently hits
* its their rate limit. For example, in the "core" * namespace, a user would need to make at least 50 requests (10 limit × 5 threshold)
* within the 30-minute window to get auto-locked.
*/
export async function handleAutoLock({
identifier: _identifier,
identifierType,
rateLimitResponse,
identifierKeyword,
autolockThreshold = DEFAULT_AUTOLOCK_THRESHOLD,
autolockDuration = DEFAULT_CHECK_THRESHOLD_WINDOW_DURATION,
}: HandleAutoLockInput): Promise<boolean> {
const { success, remaining } = rateLimitResponse;
const UPSTASH_ENV_FOUND = process.env.UPSTASH_REDIS_REST_TOKEN && process.env.UPSTASH_REDIS_REST_URL;
if (!UPSTASH_ENV_FOUND) {
log.warn("Skipping auto lock because UPSTASH env variables are not set");
return false;
}
const identifier = identifierKeyword
? _identifier.toString().replace(`${identifierKeyword}.`, "")
: _identifier;
if (!success && remaining <= 0) {
const redis = new RedisService();
const lockKey = `autolock:${identifierType}${
identifierKeyword ? `:${identifierKeyword}` : ""
}:${identifier}.count`;
try {
const count = await redis.get(lockKey);
const currentCount = count ? parseInt(count.toString(), 10) : 0;
log.info(
`Rate limit exceeded for ${identifierType}: ${identifier}. Current count: ${currentCount}/${autolockThreshold}`
);
// If they have exceeded the threshold, lock them
if (currentCount + 1 >= autolockThreshold) {
log.warn(
`Auto-locking ${identifierType}: ${identifier}. Threshold reached: ${
currentCount + 1
}/${autolockThreshold}`
);
await lockUser(identifierType, identifier, LockReason.RATE_LIMIT);
await redis.del(lockKey);
return true;
}
await redis.set(lockKey, (currentCount + 1).toString());
await redis.expire(lockKey, Math.floor(autolockDuration / 1000));
return false;
} catch (err) {
if (err instanceof Error && err.message === "No user found for this API key.") {
log.error(`Error in auto-lock: No user found for API key: ${identifier}`);
throw err;
}
log.error(`Error in auto-lock process: ${err instanceof Error ? err.message : String(err)}`);
return false;
}
}
return false;
}
export async function lockUser(identifierType: string, identifier: string, lockReason: LockReason) {
if (!identifier) {
return;
}
type UserType = {
id: number;
email: string;
username: string | null;
} | null;
let user: UserType = null;
switch (identifierType) {
case "userId":
user = await prisma.user.update({
where: { id: Number(identifier) },
data: { locked: true },
select: {
id: true,
email: true,
username: true,
},
});
break;
case "email":
user = await prisma.user.update({
where: { email: identifier },
data: { locked: true },
select: {
id: true,
email: true,
username: true,
},
});
break;
case "apiKey":
const hashedApiKey = hashAPIKey(identifier);
const apiKey = await prisma.apiKey.findUnique({
where: { hashedKey: hashedApiKey },
include: {
user: {
select: {
id: true,
email: true,
username: true,
},
},
},
});
if (!apiKey?.user) {
throw new Error("No user found for this API key.");
}
user = await prisma.user.update({
where: { id: apiKey.user.id },
data: { locked: true },
select: {
id: true,
email: true,
username: true,
},
});
break;
// Leaving SMS here but it is handled differently via checkRateLimitForSMS that auto locks
case "SMS":
break;
default:
throw new Error("Invalid identifier type for locking");
}
if (user && process.env.NEXT_PUBLIC_SENTRY_DSN) {
log.warn(lockReason, {
userId: user.id,
email: user.email,
username: user.username,
});
}
}
@@ -4,7 +4,7 @@ import { describe, it, expect, beforeEach, vi } from "vitest";
import dayjs from "@calcom/dayjs";
import * as EmailManager from "@calcom/emails/email-manager";
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { TeamRepository } from "@calcom/lib/server/repository/team";
import { CreditType } from "@calcom/prisma/enums";
@@ -60,7 +60,7 @@ vi.mock("@calcom/prisma/enums", async (importOriginal) => {
});
vi.mock("@calcom/lib/server/repository/credits");
vi.mock("@calcom/lib/server/repository/membership");
vi.mock("@calcom/features/membership/repositories/MembershipRepository");
vi.mock("@calcom/lib/server/repository/team");
vi.mock("@calcom/emails/email-manager");
vi.mock("../workflows/lib/reminders/reminderScheduler", () => ({
@@ -12,7 +12,7 @@ import { IS_SMS_CREDITS_ENABLED } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { TeamRepository } from "@calcom/lib/server/repository/team";
import prisma, { type PrismaTransaction } from "@calcom/prisma";
import type { CreditUsageType } from "@calcom/prisma/enums";
@@ -4,7 +4,7 @@ import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import { addNewMembersToEventTypes } from "@calcom/features/ee/teams/lib/queries";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
import prisma from "@calcom/prisma";
import { IdentityProvider, MembershipRole } from "@calcom/prisma/enums";
import {
@@ -4,7 +4,7 @@ import removeUserFromOrg from "@calcom/features/ee/dsync/lib/removeUserFromOrg";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { assignValueToUserInOrgBulk } from "@calcom/lib/service/attribute/server/assignValueToUser";
import prisma from "@calcom/prisma";
import { IdentityProvider } from "@calcom/prisma/enums";
@@ -1,6 +1,6 @@
import type { TFunction } from "i18next";
import { createAProfileForAnExistingUser } from "@calcom/lib/createAProfileForAnExistingUser";
import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/createAProfileForAnExistingUser";
import prisma from "@calcom/prisma";
import { sendExistingUserTeamInviteEmails } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
import type { UserWithMembership } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
@@ -1,4 +1,4 @@
import { TeamService } from "@calcom/lib/server/service/teamService";
import { TeamService } from "@calcom/features/ee/teams/services/teamService";
const removeUserFromOrg = async ({ userId, orgId }: { userId: number; orgId: number }) => {
return TeamService.removeMembers({ teamIds: [orgId], userIds: [userId], isOrg: true });
@@ -1,5 +1,5 @@
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
import prisma from "@calcom/prisma";
import type { IdentityProvider } from "@calcom/prisma/enums";
import { CreationSource, MembershipRole } from "@calcom/prisma/enums";
@@ -1,6 +1,6 @@
import type { TFunction } from "i18next";
import { createAProfileForAnExistingUser } from "@calcom/lib/createAProfileForAnExistingUser";
import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/createAProfileForAnExistingUser";
import prisma from "@calcom/prisma";
import type { UserWithMembership } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
@@ -6,7 +6,7 @@ import { ensureOrganizationIsReviewed } from "@calcom/ee/organizations/lib/ensur
import { getOrgFullOrigin, subdomainSuffix } from "@calcom/ee/organizations/lib/orgDomains";
import { getSession } from "@calcom/features/auth/lib/getSession";
import { getSpecificPermissions } from "@calcom/features/pbac/lib/resource-permissions";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
import prisma from "@calcom/prisma";
import type { User } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
@@ -7,7 +7,7 @@ import {
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { prisma } from "@calcom/prisma";
import type { OrganizationOnboarding } from "@calcom/prisma/client";
import { UserPermissionRole, type BillingPeriod } from "@calcom/prisma/enums";
@@ -2,7 +2,7 @@ import { UserPermissionRole } from "@calcom/kysely/types";
import { ORGANIZATION_SELF_SERVE_MIN_SEATS, ORGANIZATION_SELF_SERVE_PRICE } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
@@ -1,4 +1,4 @@
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
/**
* It assumes that a user can only impersonate the members of the organization he is logged in to.
@@ -0,0 +1,10 @@
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
export const getBookerBaseUrlSync = (
orgSlug: string | null,
options?: {
protocol: boolean;
}
) => {
return getOrgFullOrigin(orgSlug ?? "", options);
};
@@ -0,0 +1,12 @@
import { getBrand } from "@calcom/features/ee/organizations/lib/getBrand";
import { WEBSITE_URL } from "@calcom/lib/constants";
export const getBookerBaseUrl = async (organizationId: number | null) => {
const orgBrand = await getBrand(organizationId);
return orgBrand?.fullDomain ?? WEBSITE_URL;
};
export const getTeamBookerUrl = async (team: { organizationId: number | null }) => {
const orgBrand = await getBrand(team.organizationId);
return orgBrand?.fullDomain ?? WEBSITE_URL;
};
@@ -0,0 +1,42 @@
import { subdomainSuffix, getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { prisma } from "@calcom/prisma";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
export const getBrand = async (orgId: number | null) => {
if (!orgId) {
return null;
}
const org = await prisma.team.findUnique({
where: {
id: orgId,
},
select: {
logoUrl: true,
name: true,
slug: true,
metadata: true,
isPlatform: true,
},
});
if (!org) {
return null;
}
// platform orgs don't have a brand nor a domain
if (org.isPlatform) {
return null;
}
const metadata = teamMetadataSchema.parse(org.metadata);
const slug = (org.slug || metadata?.requestedSlug) as string;
const fullDomain = getOrgFullOrigin(slug);
const domainSuffix = subdomainSuffix();
return {
...org,
metadata,
slug,
fullDomain,
domainSuffix,
};
};
@@ -0,0 +1,31 @@
import { describe, it, vi, expect } from "vitest";
import * as getBookerBaseUrlSyncExport from "@calcom/features/ee/organizations/lib/getBookerBaseUrlSync";
import { getTeamUrlSync } from "./getTeamUrlSync";
vi.mock("@calcom/features/ee/organizations/lib/getBookerBaseUrlSync", async () => {
return {
getBookerBaseUrlSync: vi.fn(),
};
});
describe("getBookerUrl:client", () => {
describe("getTeamUrlSync", () => {
it("if orgSlug is null, it should return a URL with /team in it", () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
getBookerBaseUrlSyncExport.getBookerBaseUrlSync.mockReturnValueOnce("https://abc.com");
const url = getTeamUrlSync({ orgSlug: null, teamSlug: "myTeam" });
expect(url).toBe("https://abc.com/team/myTeam");
});
it("if orgSlug is set, it should return a URL without /team in it", () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
getBookerBaseUrlSyncExport.getBookerBaseUrlSync.mockReturnValueOnce("https://acme.com");
const url = getTeamUrlSync({ orgSlug: "acme", teamSlug: "myTeam" });
expect(url).toBe("https://acme.com/myTeam");
});
});
});
@@ -0,0 +1,21 @@
import { getBookerBaseUrlSync } from "@calcom/features/ee/organizations/lib/getBookerBaseUrlSync";
export const getTeamUrlSync = (
{
orgSlug,
teamSlug,
}: {
orgSlug: string | null;
teamSlug: string | null;
},
options?: {
protocol: boolean;
}
) => {
const bookerUrl = getBookerBaseUrlSync(orgSlug, options);
teamSlug = teamSlug || "";
if (orgSlug) {
return `${bookerUrl}/${teamSlug}`;
}
return `${bookerUrl}/team/${teamSlug}`;
};
@@ -16,9 +16,9 @@ import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import { DeploymentRepository } from "@calcom/lib/server/repository/deployment";
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import slugify from "@calcom/lib/slugify";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
@@ -11,7 +11,7 @@ import {
import { createDomain } from "@calcom/lib/domainManager/organization";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { prisma } from "@calcom/prisma";
import { UserPermissionRole } from "@calcom/prisma/enums";
@@ -3,7 +3,7 @@
import { useState } from "react";
import { trackFormbricksAction } from "@calcom/lib/formbricks-client";
import type { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import type { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
import { trpc } from "@calcom/trpc/react";
import { showToast } from "@calcom/ui/components/toast";
@@ -1,7 +1,7 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import type { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import OtherTeamList from "./OtherTeamList";
@@ -0,0 +1,152 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, it, expect, beforeEach, vi } from "vitest";
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
import type { Prisma } from "@calcom/prisma/client";
vi.mock("@calcom/lib/server/repository/teamUtils", () => ({
getParsedTeam: (org: any) => org,
}));
async function createOrganization(
data: Prisma.TeamCreateInput & {
organizationSettings: {
create: Prisma.OrganizationSettingsCreateWithoutOrganizationInput;
};
}
) {
return await prismock.team.create({
data: {
isOrganization: true,
...data,
},
});
}
async function createReviewedOrganization({
name = "Test Org",
orgAutoAcceptEmail,
}: {
name: string;
orgAutoAcceptEmail: string;
}) {
return await createOrganization({
name,
organizationSettings: {
create: {
orgAutoAcceptEmail,
isOrganizationVerified: true,
isAdminReviewed: true,
},
},
});
}
async function createTeam({
name = "Test Team",
orgAutoAcceptEmail,
}: {
name: string;
orgAutoAcceptEmail: string;
}) {
return await prismock.team.create({
data: {
name,
isOrganization: false,
organizationSettings: {
create: {
orgAutoAcceptEmail,
},
},
},
});
}
beforeEach(async () => {
vi.resetAllMocks();
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
await prismock.reset();
});
describe("Organization.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail", () => {
it("should return null if no organization matches the email domain", async () => {
const result = await OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({
email: "[email protected]",
});
expect(result).toBeNull();
});
it("should throw an error if multiple organizations match the email domain", async () => {
await createReviewedOrganization({ name: "Test Org 1", orgAutoAcceptEmail: "example.com" });
await createReviewedOrganization({ name: "Test Org 2", orgAutoAcceptEmail: "example.com" });
await expect(
OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({ email: "[email protected]" })
).rejects.toThrow("Multiple organizations found with the same auto accept email domain");
});
it("should return the parsed organization if a single match is found", async () => {
const organization = await createReviewedOrganization({
name: "Test Org",
orgAutoAcceptEmail: "example.com",
});
const result = await OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({
email: "[email protected]",
});
expect(result).toEqual(organization);
});
it("should not confuse a team with organization", async () => {
await createTeam({ name: "Test Team", orgAutoAcceptEmail: "example.com" });
const result = await OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({
email: "[email protected]",
});
expect(result).toEqual(null);
});
it("should correctly match orgAutoAcceptEmail", async () => {
await createReviewedOrganization({ name: "Test Org", orgAutoAcceptEmail: "noexample.com" });
const result = await OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({
email: "[email protected]",
});
expect(result).toEqual(null);
});
});
describe("Organization.getVerifiedOrganizationByAutoAcceptEmailDomain", () => {
it("should return organization when domain matches and organization is verified", async () => {
const verifiedOrganization = await createOrganization({
name: "Test Org",
organizationSettings: { create: { orgAutoAcceptEmail: "cal.com", isOrganizationVerified: true } },
});
const result = await OrganizationRepository.getVerifiedOrganizationByAutoAcceptEmailDomain("cal.com");
expect(result).toEqual({
id: verifiedOrganization.id,
organizationSettings: {
orgAutoAcceptEmail: "cal.com",
},
});
});
it("should not return organization when organization is not verified", async () => {
await createOrganization({
name: "Test Org",
organizationSettings: { create: { orgAutoAcceptEmail: "cal.com", isOrganizationVerified: false } },
});
const result = await OrganizationRepository.getVerifiedOrganizationByAutoAcceptEmailDomain("cal.com");
expect(result).toEqual(null);
});
});
@@ -0,0 +1,478 @@
import type { z } from "zod";
import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/createAProfileForAnExistingUser";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getParsedTeam } from "@calcom/lib/server/repository/teamUtils";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import type { CreationSource } from "@calcom/prisma/enums";
import type { teamMetadataStrictSchema } from "@calcom/prisma/zod-utils";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
const orgSelect = {
id: true,
name: true,
slug: true,
logoUrl: true,
};
export class OrganizationRepository {
static async createWithExistingUserAsOwner({
orgData,
owner,
}: {
orgData: {
name: string;
slug: string | null;
isOrganizationConfigured: boolean;
isOrganizationAdminReviewed: boolean;
autoAcceptEmail: string;
seats: number | null;
pricePerSeat: number | null;
isPlatform: boolean;
billingPeriod?: "MONTHLY" | "ANNUALLY";
logoUrl: string | null;
bio: string | null;
requestedSlug?: string | null;
};
owner: {
id: number;
email: string;
nonOrgUsername: string;
};
}) {
logger.debug("createWithExistingUserAsOwner", safeStringify({ orgData, owner }));
const organization = await this.create(orgData);
const ownerProfile = await createAProfileForAnExistingUser({
user: {
id: owner.id,
email: owner.email,
currentUsername: owner.nonOrgUsername,
},
organizationId: organization.id,
});
await prisma.membership.create({
data: {
createdAt: new Date(),
userId: owner.id,
role: MembershipRole.OWNER,
accepted: true,
teamId: organization.id,
},
});
return { organization, ownerProfile };
}
static async createWithNonExistentOwner({
orgData,
owner,
creationSource,
}: {
orgData: {
name: string;
slug: string;
isOrganizationConfigured: boolean;
isOrganizationAdminReviewed: boolean;
autoAcceptEmail: string;
seats: number | null;
billingPeriod?: "MONTHLY" | "ANNUALLY";
pricePerSeat: number | null;
isPlatform: boolean;
logoUrl: string | null;
bio: string | null;
};
owner: {
email: string;
};
creationSource: CreationSource;
}) {
logger.debug("createWithNonExistentOwner", safeStringify({ orgData, owner }));
const organization = await this.create(orgData);
const ownerUsernameInOrg = getOrgUsernameFromEmail(owner.email, orgData.autoAcceptEmail);
const userRepo = new UserRepository(prisma);
const ownerInDb = await userRepo.create({
email: owner.email,
username: ownerUsernameInOrg,
organizationId: organization.id,
locked: false,
creationSource,
});
await prisma.membership.create({
data: {
createdAt: new Date(),
userId: ownerInDb.id,
role: MembershipRole.OWNER,
accepted: true,
teamId: organization.id,
},
});
return {
orgOwner: ownerInDb,
organization,
ownerProfile: {
username: ownerUsernameInOrg,
},
};
}
static async create(orgData: {
name: string;
slug: string | null;
isOrganizationConfigured: boolean;
isOrganizationAdminReviewed: boolean;
autoAcceptEmail: string;
seats: number | null;
billingPeriod?: "MONTHLY" | "ANNUALLY";
pricePerSeat: number | null;
isPlatform: boolean;
logoUrl: string | null;
bio: string | null;
requestedSlug?: string | null;
}) {
return await prisma.team.create({
data: {
name: orgData.name,
isOrganization: true,
slug: orgData.slug,
// This is huge and causes issues, we need to have the logic to convert logo to logoUrl and then use that url ehre.
// logoUrl: orgData.logoUrl,
bio: orgData.bio,
organizationSettings: {
create: {
isAdminReviewed: orgData.isOrganizationAdminReviewed,
isOrganizationVerified: true,
isOrganizationConfigured: orgData.isOrganizationConfigured,
orgAutoAcceptEmail: orgData.autoAcceptEmail,
},
},
metadata: {
isPlatform: orgData.isPlatform,
// We still have a case where we don't have slug set directly on organization. The reason is because we want to create an org first(with same slug as another regular team) and then move the team to org.
// Because in such cases there is a fallback existing at multiple places to use requestedSlug, we set it here still :(
requestedSlug: orgData.requestedSlug,
// We set these here still because some parts of code read it from metadata. This data exists in OrganizationOnboarding as well and should be used from there ideally
// We also need to think about existing Organizations that might not have OrganizationOnboarding, before taking any decision
orgSeats: orgData.seats,
orgPricePerSeat: orgData.pricePerSeat,
billingPeriod: orgData.billingPeriod,
},
isPlatform: orgData.isPlatform,
},
});
}
static async findById({ id }: { id: number }) {
return prisma.team.findUnique({
where: {
id,
isOrganization: true,
},
});
}
static async findBySlug({ slug }: { slug: string }) {
// Slug is unique but could be null as well, so we can't use findUnique
return prisma.team.findFirst({
where: {
slug,
isOrganization: true,
},
});
}
static async findBySlugIncludeOnboarding({ slug }: { slug: string }) {
return prisma.team.findFirst({
where: { slug, isOrganization: true },
include: {
organizationOnboarding: {
select: {
id: true,
isDomainConfigured: true,
isPlatform: true,
slug: true,
teams: true,
invitedMembers: true,
},
},
},
});
}
static async findByIdIncludeOrganizationSettings({ id }: { id: number }) {
return prisma.team.findUnique({
where: {
id,
isOrganization: true,
},
select: {
...orgSelect,
organizationSettings: true,
},
});
}
static async findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({ email }: { email: string }) {
const emailDomain = email.split("@").at(-1);
const orgs = await prisma.team.findMany({
where: {
isOrganization: true,
isPlatform: false,
organizationSettings: {
orgAutoAcceptEmail: emailDomain,
isOrganizationVerified: true,
isAdminReviewed: true,
},
},
});
if (orgs.length > 1) {
logger.error(
"Multiple organizations found with the same auto accept email domain",
safeStringify({ orgs, emailDomain })
);
// Detect and fail just in case this situation arises. We should really identify the problem in this case and fix the data.
throw new Error("Multiple organizations found with the same auto accept email domain");
}
const org = orgs[0];
if (!org) {
return null;
}
return getParsedTeam(org);
}
static async findCurrentOrg({ userId, orgId }: { userId: number; orgId: number }) {
const membership = await prisma.membership.findUnique({
where: {
userId_teamId: {
userId,
teamId: orgId,
},
},
include: {
team: true,
},
});
const organizationSettings = await prisma.organizationSettings.findUnique({
where: {
organizationId: orgId,
},
select: {
lockEventTypeCreationForUsers: true,
adminGetsNoSlotsNotification: true,
isAdminReviewed: true,
allowSEOIndexing: true,
orgProfileRedirectsToVerifiedDomain: true,
orgAutoAcceptEmail: true,
disablePhoneOnlySMSNotifications: true,
},
});
if (!membership) {
throw new Error("You do not have a membership to your organization");
}
const metadata = teamMetadataSchema.parse(membership?.team.metadata);
return {
canAdminImpersonate: !!organizationSettings?.isAdminReviewed,
organizationSettings: {
lockEventTypeCreationForUsers: organizationSettings?.lockEventTypeCreationForUsers,
adminGetsNoSlotsNotification: organizationSettings?.adminGetsNoSlotsNotification,
allowSEOIndexing: organizationSettings?.allowSEOIndexing,
orgProfileRedirectsToVerifiedDomain: organizationSettings?.orgProfileRedirectsToVerifiedDomain,
orgAutoAcceptEmail: organizationSettings?.orgAutoAcceptEmail,
disablePhoneOnlySMSNotifications: organizationSettings?.disablePhoneOnlySMSNotifications,
},
user: {
role: membership?.role,
accepted: membership?.accepted,
},
...membership?.team,
metadata,
};
}
static async findTeamsInOrgIamNotPartOf({ userId, parentId }: { userId: number; parentId: number | null }) {
const teamsInOrgIamNotPartOf = await prisma.team.findMany({
where: {
parentId,
members: {
none: {
userId,
},
},
},
select: {
parentId: true,
id: true,
name: true,
logoUrl: true,
slug: true,
},
});
return teamsInOrgIamNotPartOf;
}
static async adminFindById({ id }: { id: number }) {
const org = await prisma.team.findUnique({
where: {
id,
},
select: {
id: true,
name: true,
slug: true,
metadata: true,
isOrganization: true,
members: {
where: {
role: "OWNER",
},
select: {
user: {
select: {
id: true,
name: true,
email: true,
},
},
},
},
organizationSettings: {
select: {
isOrganizationConfigured: true,
isOrganizationVerified: true,
orgAutoAcceptEmail: true,
},
},
},
});
if (!org) {
throw new Error("Organization not found");
}
const parsedMetadata = teamMetadataSchema.parse(org.metadata);
if (!org?.isOrganization) {
throw new Error("Organization not found");
}
return { ...org, metadata: parsedMetadata };
}
static async findByMemberEmail({ email }: { email: string }) {
const organization = await prisma.team.findFirst({
where: {
isOrganization: true,
members: {
some: {
user: { email },
},
},
},
});
return organization ?? null;
}
static async findByMemberEmailId({ email }: { email: string }) {
const log = logger.getSubLogger({ prefix: ["findByMemberEmailId"] });
log.debug("called with", { email });
const organization = await prisma.team.findFirst({
where: {
isOrganization: true,
members: {
some: {
user: {
email,
},
},
},
},
});
return organization;
}
static async findCalVideoLogoByOrgId({ id }: { id: number }) {
const org = await prisma.team.findUnique({
where: {
id,
},
select: {
calVideoLogo: true,
},
});
return org?.calVideoLogo;
}
static async getVerifiedOrganizationByAutoAcceptEmailDomain(domain: string) {
return await prisma.team.findFirst({
where: {
organizationSettings: {
isOrganizationVerified: true,
orgAutoAcceptEmail: domain,
},
},
select: {
id: true,
organizationSettings: {
select: {
orgAutoAcceptEmail: true,
},
},
},
});
}
static async setSlug({ id, slug }: { id: number; slug: string }) {
return await prisma.team.update({
where: { id, isOrganization: true },
data: { slug },
});
}
static async updateStripeSubscriptionDetails({
id,
stripeSubscriptionId,
stripeSubscriptionItemId,
existingMetadata,
}: {
id: number;
stripeSubscriptionId: string;
stripeSubscriptionItemId: string;
existingMetadata: z.infer<typeof teamMetadataStrictSchema>;
}) {
return await prisma.team.update({
where: { id, isOrganization: true },
data: {
metadata: {
...existingMetadata,
subscriptionId: stripeSubscriptionId,
subscriptionItemId: stripeSubscriptionItemId,
},
},
});
}
static async checkIfPrivate({ orgId }: { orgId: number }) {
const team = await prisma.team.findUnique({
where: {
id: orgId,
isOrganization: true,
},
select: {
isPrivate: true,
},
});
return team?.isPrivate ?? false;
}
}
@@ -7,7 +7,7 @@ import type { SyntheticEvent } from "react";
import { useEffect, useState } from "react";
import getStripe from "@calcom/app-store/stripepayment/lib/client";
import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
import { useBookingSuccessRedirect } from "@calcom/features/bookings/lib/bookingSuccessRedirect";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -3,7 +3,7 @@ import { z } from "zod";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { getClientSecretFromPayment } from "@calcom/features/ee/payments/pages/getClientSecretFromPayment";
import { shouldHideBrandingForEvent } from "@calcom/lib/hideBranding";
import { shouldHideBrandingForEvent } from "@calcom/features/profile/lib/hideBranding";
import prisma from "@calcom/prisma";
import { BookingStatus } from "@calcom/prisma/enums";
import { paymentDataSelect } from "@calcom/prisma/selects/payment";
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff. Show more