refactor: Move repositories from @calcom/lib to @calcom/features domain folders (#27570)

* refactor: move repositories from lib to features domain folders

- Move HolidayRepository to features/holidays/repositories
- Move PrismaTrackingRepository to features/bookings/repositories
- Move PrismaBookingPaymentRepository to features/bookings/repositories
- Move PrismaRoutingFormResponseRepository to features/routing-forms/repositories
- Move PrismaAssignmentReasonRepository to features/assignment-reason/repositories
- Move VerificationTokenRepository to features/auth/repositories
- Move WorkspacePlatformRepository to features/workspace-platform/repositories
- Move DTO files to their respective feature domains
- Merge lib DestinationCalendarRepository into features version
- Merge lib SelectedCalendarRepository into features version
- Update all import paths across the codebase

This follows the vertical slice architecture pattern by organizing
repositories by domain rather than by technical layer.

Co-Authored-By: [email protected] <[email protected]>

* fix: update VerificationTokenService import path to new location

Co-Authored-By: [email protected] <[email protected]>

* fix: update test file imports to use new repository locations

Co-Authored-By: [email protected] <[email protected]>

* mv

* fix structure

* fix

* refactor: merge unit tests for SelectedCalendarRepository into single file

Co-Authored-By: [email protected] <[email protected]>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2026-02-09 08:41:04 -03:00
1 parent d4a059033e
commit 96bec9f7b9
78 files changed
+1027 -1036

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
import dayjs from "@calcom/dayjs";
import { HolidayRepository } from "@calcom/lib/server/repository/HolidayRepository";
import { HolidayRepository } from "@calcom/features/holidays/repositories/HolidayRepository";
import {
getHolidayServiceCachingProxy,
@@ -1,5 +1,5 @@
import dayjs from "@calcom/dayjs";
import { HolidayRepository } from "@calcom/lib/server/repository/HolidayRepository";
import { HolidayRepository } from "@calcom/features/holidays/repositories/HolidayRepository";
import { GOOGLE_HOLIDAY_CALENDARS, HOLIDAY_CACHE_DAYS } from "./constants";
import { getGoogleCalendarClient, type GoogleCalendarClient, type GoogleCalendarHoliday } from "./GoogleCalendarClient";
@@ -1,52 +0,0 @@
import type { Payment, PaymentOption, Prisma } from "@calcom/prisma/client";
import type { JsonValue } from "@calcom/types/Json";
export interface BookingPaymentWithCredentials {
id: number;
amount: number;
success: boolean;
bookingId: number;
booking: {
user: {
credentials: Array<{
key: JsonValue;
}>;
} | null;
} | null;
}
export interface CreatePaymentData {
uid: string;
app: { connect: { slug: string } };
booking: { connect: { id: number } };
amount: number;
fee: number;
externalId: string;
refunded: boolean;
success: boolean;
currency: string;
data: Prisma.InputJsonValue;
}
export interface PaymentForAwaitingEmail {
success: boolean;
externalId: string | null;
uid: string;
paymentOption: PaymentOption | null;
amount: number;
currency: string;
app: {
slug: string | null;
} | null;
}
export interface IBookingPaymentRepository {
findByExternalIdIncludeBookingUserCredentials(
externalId: string,
credentialType: string
): Promise<BookingPaymentWithCredentials | null>;
createPaymentRecord(data: CreatePaymentData): Promise<Payment>;
findByIdForAwaitingPaymentEmail(id: number): Promise<PaymentForAwaitingEmail | null>;
}
@@ -1,326 +0,0 @@
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { HolidayRepository } from "./HolidayRepository";
describe("HolidayRepository", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("findUserSettings", () => {
it("should return user holiday settings when they exist", async () => {
const mockSettings = {
id: 1,
userId: 123,
countryCode: "US",
disabledIds: ["holiday_1", "holiday_2"],
createdAt: new Date(),
updatedAt: new Date(),
};
prismaMock.userHolidaySettings.findUnique.mockResolvedValue(mockSettings);
const result = await HolidayRepository.findUserSettings({ userId: 123 });
expect(prismaMock.userHolidaySettings.findUnique).toHaveBeenCalledWith({
where: { userId: 123 },
select: {
id: true,
userId: true,
countryCode: true,
disabledIds: true,
createdAt: true,
updatedAt: true,
},
});
expect(result).toEqual(mockSettings);
});
it("should return null when user has no holiday settings", async () => {
prismaMock.userHolidaySettings.findUnique.mockResolvedValue(null);
const result = await HolidayRepository.findUserSettings({ userId: 456 });
expect(prismaMock.userHolidaySettings.findUnique).toHaveBeenCalledWith({
where: { userId: 456 },
select: expect.any(Object),
});
expect(result).toBeNull();
});
});
describe("findUserSettingsSelect", () => {
it("should return user settings with custom select", async () => {
const mockSettings = {
countryCode: "GB",
disabledIds: [],
};
prismaMock.userHolidaySettings.findUnique.mockResolvedValue(mockSettings);
const result = await HolidayRepository.findUserSettingsSelect({
userId: 123,
select: {
countryCode: true,
disabledIds: true,
},
});
expect(prismaMock.userHolidaySettings.findUnique).toHaveBeenCalledWith({
where: { userId: 123 },
select: {
countryCode: true,
disabledIds: true,
},
});
expect(result).toEqual(mockSettings);
});
});
describe("upsertUserSettings", () => {
it("should create new settings when user has none", async () => {
const mockSettings = {
id: 1,
userId: 123,
countryCode: "US",
disabledIds: [],
createdAt: new Date(),
updatedAt: new Date(),
};
prismaMock.userHolidaySettings.upsert.mockResolvedValue(mockSettings);
const result = await HolidayRepository.upsertUserSettings({
userId: 123,
countryCode: "US",
});
expect(prismaMock.userHolidaySettings.upsert).toHaveBeenCalledWith({
where: { userId: 123 },
create: {
userId: 123,
countryCode: "US",
disabledIds: [],
},
update: {
countryCode: "US",
},
select: expect.any(Object),
});
expect(result).toEqual(mockSettings);
});
it("should reset disabled holidays when resetDisabledHolidays is true", async () => {
const mockSettings = {
id: 1,
userId: 123,
countryCode: "GB",
disabledIds: [],
createdAt: new Date(),
updatedAt: new Date(),
};
prismaMock.userHolidaySettings.upsert.mockResolvedValue(mockSettings);
const result = await HolidayRepository.upsertUserSettings({
userId: 123,
countryCode: "GB",
resetDisabledHolidays: true,
});
expect(prismaMock.userHolidaySettings.upsert).toHaveBeenCalledWith({
where: { userId: 123 },
create: {
userId: 123,
countryCode: "GB",
disabledIds: [],
},
update: {
countryCode: "GB",
disabledIds: [],
},
select: expect.any(Object),
});
expect(result).toEqual(mockSettings);
});
});
describe("updateDisabledIds", () => {
it("should update disabled holiday IDs", async () => {
const mockSettings = {
id: 1,
userId: 123,
countryCode: "US",
disabledIds: ["christmas_2025", "thanksgiving_2025"],
createdAt: new Date(),
updatedAt: new Date(),
};
prismaMock.userHolidaySettings.update.mockResolvedValue(mockSettings);
const result = await HolidayRepository.updateDisabledIds({
userId: 123,
disabledIds: ["christmas_2025", "thanksgiving_2025"],
});
expect(prismaMock.userHolidaySettings.update).toHaveBeenCalledWith({
where: { userId: 123 },
data: { disabledIds: ["christmas_2025", "thanksgiving_2025"] },
select: expect.any(Object),
});
expect(result).toEqual(mockSettings);
});
});
describe("findManyCachedHolidays", () => {
it("should return cached holidays for country and year", async () => {
const mockHolidays = [
{
id: "1",
countryCode: "US",
calendarId: "en.usa.official#[email protected]",
eventId: "new_years_day_2025",
name: "New Year's Day",
date: new Date("2025-01-01"),
year: 2025,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "2",
countryCode: "US",
calendarId: "en.usa.official#[email protected]",
eventId: "christmas_2025",
name: "Christmas Day",
date: new Date("2025-12-25"),
year: 2025,
createdAt: new Date(),
updatedAt: new Date(),
},
];
prismaMock.holidayCache.findMany.mockResolvedValue(mockHolidays);
const result = await HolidayRepository.findManyCachedHolidays({
countryCode: "US",
year: 2025,
});
expect(prismaMock.holidayCache.findMany).toHaveBeenCalledWith({
where: {
countryCode: "US",
year: 2025,
},
orderBy: {
date: "asc",
},
select: expect.any(Object),
});
expect(result).toEqual(mockHolidays);
});
it("should return empty array when no holidays found", async () => {
prismaMock.holidayCache.findMany.mockResolvedValue([]);
const result = await HolidayRepository.findManyCachedHolidays({
countryCode: "XX",
year: 2025,
});
expect(result).toEqual([]);
});
});
describe("findFirstCacheEntry", () => {
it("should return first cache entry for staleness check", async () => {
const mockEntry = {
id: "1",
countryCode: "US",
calendarId: "en.usa.official#[email protected]",
eventId: "new_years_day_2025",
name: "New Year's Day",
date: new Date("2025-01-01"),
year: 2025,
createdAt: new Date(),
updatedAt: new Date("2025-01-15"),
};
prismaMock.holidayCache.findFirst.mockResolvedValue(mockEntry);
const result = await HolidayRepository.findFirstCacheEntry({
countryCode: "US",
year: 2025,
});
expect(prismaMock.holidayCache.findFirst).toHaveBeenCalledWith({
where: {
countryCode: "US",
year: 2025,
},
orderBy: {
updatedAt: "desc",
},
select: expect.any(Object),
});
expect(result).toEqual(mockEntry);
});
it("should return null when no cache entry exists", async () => {
prismaMock.holidayCache.findFirst.mockResolvedValue(null);
const result = await HolidayRepository.findFirstCacheEntry({
countryCode: "US",
year: 2030,
});
expect(result).toBeNull();
});
});
describe("findCachedHolidaysInRange", () => {
it("should return holidays within date range", async () => {
const mockHolidays = [
{
id: "1",
countryCode: "US",
calendarId: "en.usa.official#[email protected]",
eventId: "christmas_2025",
name: "Christmas Day",
date: new Date("2025-12-25"),
year: 2025,
createdAt: new Date(),
updatedAt: new Date(),
},
];
prismaMock.holidayCache.findMany.mockResolvedValue(mockHolidays);
const startDate = new Date("2025-12-01");
const endDate = new Date("2025-12-31");
const result = await HolidayRepository.findCachedHolidaysInRange({
countryCode: "US",
startDate,
endDate,
});
expect(prismaMock.holidayCache.findMany).toHaveBeenCalledWith({
where: {
countryCode: "US",
date: {
gte: startDate,
lte: endDate,
},
},
orderBy: {
date: "asc",
},
select: expect.any(Object),
});
expect(result).toEqual(mockHolidays);
});
});
});
@@ -1,217 +0,0 @@
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
const holidayCacheSelect = {
id: true,
countryCode: true,
calendarId: true,
eventId: true,
name: true,
date: true,
year: true,
createdAt: true,
updatedAt: true,
} satisfies Prisma.HolidayCacheSelect;
const userHolidaySettingsSelect = {
id: true,
userId: true,
countryCode: true,
disabledIds: true,
createdAt: true,
updatedAt: true,
} satisfies Prisma.UserHolidaySettingsSelect;
export class HolidayRepository {
static async findFirstCacheEntry({ countryCode, year }: { countryCode: string; year: number }) {
return prisma.holidayCache.findFirst({
where: {
countryCode,
year,
},
orderBy: {
updatedAt: "desc",
},
select: holidayCacheSelect,
});
}
static async findManyCachedHolidays({ countryCode, year }: { countryCode: string; year: number }) {
return prisma.holidayCache.findMany({
where: {
countryCode,
year,
},
orderBy: {
date: "asc",
},
select: holidayCacheSelect,
});
}
static async findCachedHolidaysInRange({
countryCode,
startDate,
endDate,
}: {
countryCode: string;
startDate: Date;
endDate: Date;
}) {
return prisma.holidayCache.findMany({
where: {
countryCode,
date: {
gte: startDate,
lte: endDate,
},
},
orderBy: {
date: "asc",
},
select: holidayCacheSelect,
});
}
static async deleteManyCacheEntries({ countryCode, year }: { countryCode: string; year: number }) {
return prisma.holidayCache.deleteMany({
where: {
countryCode,
year,
},
});
}
static async createManyCacheEntries(data: Prisma.HolidayCacheCreateManyInput[]) {
return prisma.holidayCache.createMany({
data,
skipDuplicates: true,
});
}
static async refreshCache({
countryCode,
year,
holidays,
}: {
countryCode: string;
year: number;
holidays: Prisma.HolidayCacheCreateManyInput[];
}) {
return prisma.$transaction(async (tx) => {
await tx.holidayCache.deleteMany({
where: {
countryCode,
year,
},
});
if (holidays.length > 0) {
await tx.holidayCache.createMany({
data: holidays,
skipDuplicates: true,
});
}
});
}
static async findUserSettings({ userId }: { userId: number }) {
return prisma.userHolidaySettings.findUnique({
where: { userId },
select: userHolidaySettingsSelect,
});
}
static async findUserSettingsSelect<T extends Prisma.UserHolidaySettingsSelect>({
userId,
select,
}: {
userId: number;
select: T;
}) {
return prisma.userHolidaySettings.findUnique({
where: { userId },
select,
});
}
static async upsertUserSettings({
userId,
countryCode,
disabledIds = [],
resetDisabledHolidays = false,
}: {
userId: number;
countryCode: string | null;
disabledIds?: string[];
resetDisabledHolidays?: boolean;
}) {
return prisma.userHolidaySettings.upsert({
where: { userId },
create: {
userId,
countryCode,
disabledIds,
},
update: {
countryCode,
...(resetDisabledHolidays ? { disabledIds: [] } : {}),
},
select: userHolidaySettingsSelect,
});
}
static async updateUserSettings({
userId,
data,
}: {
userId: number;
data: Prisma.UserHolidaySettingsUpdateInput;
}) {
return prisma.userHolidaySettings.update({
where: { userId },
data,
select: userHolidaySettingsSelect,
});
}
static async updateDisabledIds({ userId, disabledIds }: { userId: number; disabledIds: string[] }) {
return prisma.userHolidaySettings.update({
where: { userId },
data: { disabledIds },
select: userHolidaySettingsSelect,
});
}
static async findBookingsInDateRanges({
userId,
dateRanges,
}: {
userId: number;
dateRanges: Array<{ start: Date; end: Date }>;
}) {
if (dateRanges.length === 0) return [];
return prisma.booking.findMany({
where: {
userId,
status: { in: [BookingStatus.ACCEPTED, BookingStatus.PENDING] },
OR: dateRanges.map(({ start, end }) => ({
AND: [{ startTime: { lt: end } }, { endTime: { gt: start } }],
})),
},
select: {
id: true,
title: true,
startTime: true,
endTime: true,
attendees: {
take: 1,
select: { name: true },
},
},
});
}
}
@@ -1,16 +0,0 @@
import prisma from "@calcom/prisma";
export class PrismaAssignmentReasonRepository {
static async findLatestReasonFromBookingUid(bookingUid: string) {
return await prisma.assignmentReason.findFirst({
where: {
booking: {
uid: bookingUid,
},
},
orderBy: {
createdAt: "desc",
},
});
}
}
@@ -1,68 +0,0 @@
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import type {
IBookingPaymentRepository,
BookingPaymentWithCredentials,
CreatePaymentData,
PaymentForAwaitingEmail,
} from "./BookingPaymentRepository.interface";
export class PrismaBookingPaymentRepository implements IBookingPaymentRepository {
constructor(private readonly prismaClient: PrismaClient = prisma) {}
async findByExternalIdIncludeBookingUserCredentials(
externalId: string,
credentialType: string
): Promise<BookingPaymentWithCredentials | null> {
return await this.prismaClient.payment.findFirst({
where: {
externalId,
},
select: {
id: true,
amount: true,
success: true,
bookingId: true,
booking: {
select: {
user: {
select: {
credentials: {
where: { type: credentialType },
select: { key: true },
},
},
},
},
},
},
});
}
async createPaymentRecord(data: CreatePaymentData) {
const createdPayment = await this.prismaClient.payment.create({
data,
});
return createdPayment;
}
async findByIdForAwaitingPaymentEmail(id: number): Promise<PaymentForAwaitingEmail | null> {
return await this.prismaClient.payment.findUnique({
where: { id },
select: {
success: true,
externalId: true,
uid: true,
paymentOption: true,
amount: true,
currency: true,
app: {
select: {
slug: true,
},
},
},
});
}
}
@@ -1,38 +0,0 @@
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import type { RoutingFormResponseRepositoryInterface } from "./RoutingFormResponseRepository.interface";
export class PrismaRoutingFormResponseRepository implements RoutingFormResponseRepositoryInterface {
constructor(private readonly prismaClient: PrismaClient = prisma) {}
findByIdIncludeForm(id: number) {
return this.prismaClient.app_RoutingForms_FormResponse.findUnique({
where: {
id,
},
include: {
form: {
select: {
fields: true,
},
},
},
});
}
findByBookingUidIncludeForm(bookingUid: string) {
return this.prismaClient.app_RoutingForms_FormResponse.findUnique({
where: {
routedToBookingUid: bookingUid,
},
include: {
form: {
select: {
fields: true,
},
},
},
});
}
}
@@ -1,18 +0,0 @@
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import type { TrackingRepositoryInterface } from "./TrackingRepository.interface";
export class PrismaTrackingRepository implements TrackingRepositoryInterface {
constructor(private readonly prismaClient: PrismaClient = prisma) {}
async findByBookingUid(bookingUid: string) {
return await this.prismaClient.tracking.findFirst({
where: {
booking: {
uid: bookingUid,
},
},
});
}
}
@@ -1,11 +0,0 @@
import type { App_RoutingForms_Form, App_RoutingForms_FormResponse } from "@calcom/prisma/client";
export interface RoutingFormResponseRepositoryInterface {
findByIdIncludeForm(
id: number
): Promise<(App_RoutingForms_FormResponse & { form: { fields: App_RoutingForms_Form["fields"] } }) | null>;
findByBookingUidIncludeForm(
bookingUid: string
): Promise<(App_RoutingForms_FormResponse & { form: { fields: App_RoutingForms_Form["fields"] } }) | null>;
}
@@ -1,5 +0,0 @@
import type { Tracking } from "@calcom/prisma/client";
export interface TrackingRepositoryInterface {
findByBookingUid(bookingUid: string): Promise<Tracking | null>;
}
@@ -1,164 +0,0 @@
import { describe, test, expect, vi, beforeEach } from "vitest";
import type { VerificationToken } from "@calcom/prisma/client";
import { VerificationTokenRepository } from "../verificationToken";
vi.mock("@calcom/prisma", () => ({
default: {
verificationToken: {
create: vi.fn(),
findFirst: vi.fn(),
update: vi.fn(),
},
},
}));
const prismaMock = vi.hoisted(() => ({
verificationToken: {
create: vi.fn(),
findFirst: vi.fn(),
update: vi.fn(),
},
}));
vi.mock("@calcom/prisma", () => ({
default: prismaMock,
}));
describe("VerificationTokenRepository", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("create", () => {
test("should create a verification token", async () => {
const identifier = "[email protected]";
const token = "hashed-token-value";
const expires = new Date(Date.now() + 86400 * 1000);
const mockVerificationToken: VerificationToken = {
identifier,
token,
expires,
};
prismaMock.verificationToken.create.mockResolvedValue(mockVerificationToken);
const result = await VerificationTokenRepository.create({
identifier,
token,
expires,
});
expect(prismaMock.verificationToken.create).toHaveBeenCalledWith({
data: {
identifier,
token,
expires,
},
});
expect(result).toEqual(mockVerificationToken);
});
test("should create a verification token with correct data types", async () => {
const identifier = "[email protected]";
const token = "sha256-hashed-token";
const expires = new Date("2025-12-31T23:59:59.000Z");
const mockVerificationToken: VerificationToken = {
identifier,
token,
expires,
};
prismaMock.verificationToken.create.mockResolvedValue(mockVerificationToken);
await VerificationTokenRepository.create({
identifier,
token,
expires,
});
expect(prismaMock.verificationToken.create).toHaveBeenCalledWith({
data: {
identifier,
token,
expires,
},
});
});
});
describe("updateTeamInviteTokenExpirationDate", () => {
test("should update team invite token expiration date", async () => {
const email = "[email protected]";
const teamId = 123;
const expiresInDays = 7;
const existingToken: VerificationToken = {
identifier: email,
token: "existing-token",
expires: new Date(),
};
prismaMock.verificationToken.findFirst.mockResolvedValue(existingToken);
prismaMock.verificationToken.update.mockResolvedValue({
...existingToken,
expires: new Date(Date.now() + expiresInDays * 24 * 60 * 60 * 1000),
});
const result = await VerificationTokenRepository.updateTeamInviteTokenExpirationDate({
email,
teamId,
expiresInDays,
});
expect(prismaMock.verificationToken.findFirst).toHaveBeenCalledWith({
where: {
identifier: email,
teamId,
},
});
expect(prismaMock.verificationToken.update).toHaveBeenCalledWith({
where: {
identifier: email,
teamId,
token: existingToken.token,
},
data: { expires: expect.any(Date) },
});
expect(result.token).toBe(existingToken.token);
expect(result.expires).toBeInstanceOf(Date);
});
test("should calculate correct expiration date", async () => {
const email = "[email protected]";
const teamId = 456;
const expiresInDays = 3;
const existingToken: VerificationToken = {
identifier: email,
token: "token-123",
expires: new Date(),
};
prismaMock.verificationToken.findFirst.mockResolvedValue(existingToken);
const expectedExpires = new Date(Date.now() + expiresInDays * 24 * 60 * 60 * 1000);
prismaMock.verificationToken.update.mockImplementation(({ data }) => {
expect(data.expires.getTime()).toBeCloseTo(expectedExpires.getTime(), -2);
return Promise.resolve({ ...existingToken, expires: data.expires });
});
await VerificationTokenRepository.updateTeamInviteTokenExpirationDate({
email,
teamId,
expiresInDays,
});
});
});
});
@@ -1,36 +0,0 @@
import type { PrismaClient } from "@calcom/prisma";
export class DestinationCalendarRepository {
constructor(private prisma: PrismaClient) {}
async getCustomReminderByCredentialId(credentialId: number): Promise<number | null> {
const destinationCalendar = await this.prisma.destinationCalendar.findFirst({
where: { credentialId },
select: { customCalendarReminder: true },
});
return destinationCalendar?.customCalendarReminder ?? null;
}
async updateCustomReminder({
userId,
credentialId,
integration,
customCalendarReminder,
}: {
userId: number;
credentialId: number;
integration: string;
customCalendarReminder: number | null;
}) {
return await this.prisma.destinationCalendar.updateMany({
where: {
userId,
credentialId,
integration,
},
data: {
customCalendarReminder,
},
});
}
}
@@ -1,16 +0,0 @@
import type { Prisma } from "@calcom/prisma/client";
/**
* Interface for Booking Reference repository operations
*/
export interface IBookingReferenceRepository {
// ... Add existing methods as well here
/**
* Update all booking references associated with a booking
* Used during booking cancellation cleanup to soft-delete references
*/
updateManyByBookingId(
bookingId: number,
data: Prisma.BookingReferenceUpdateManyMutationInput
): Promise<void>;
}
@@ -1,55 +0,0 @@
import { Booking } from "@calcom/prisma/client";
import type { BookingStatus, WorkflowMethods } from "@calcom/prisma/enums";
export interface BookingWhereInput {
id?: number;
uid?: string;
recurringEventId?: string | null;
startTime?: {
gte?: Date;
};
}
export type BookingWhereUniqueInput =
| {
id: number;
}
| {
uid: string;
};
export interface BookingUpdateData {
status?: BookingStatus;
cancellationReason?: string | null;
cancelledBy?: string | null;
iCalSequence?: number;
}
interface BookingWithWorkflowReminders {
id: number;
startTime: Date;
endTime: Date;
references: {
uid: string;
type: string;
externalCalendarId: string | null;
credentialId: number | null;
}[];
workflowReminders: {
id: number;
method: WorkflowMethods;
referenceId: string | null;
}[];
uid: string;
}
export interface IBookingRepository {
// ... Add existing methods as well here
updateMany(params: { where: BookingWhereInput; data: BookingUpdateData }): Promise<{ count: number }>;
update(params: { where: BookingWhereUniqueInput; data: BookingUpdateData }): Promise<Booking>;
findManyIncludeWorkflowRemindersAndReferences(params: {
where: BookingWhereInput;
}): Promise<BookingWithWorkflowReminders[]>;
}
@@ -1,13 +0,0 @@
export interface OrganizationProfile {
id: number;
uid: string;
userId: number;
organizationId: number;
username: string;
createdAt: Date;
updatedAt: Date;
}
export interface IProfileRepository {
findFirstByUserId({ userId }: { userId: number }): Promise<OrganizationProfile | null>;
}
@@ -1,19 +0,0 @@
import type { Prisma } from "@calcom/prisma/client";
type EnforceTrueOrNested<T> = {
[K in keyof T]: T[K] extends object ? EnforceTrueOrNested<T[K]> : true; // only allow `true` at leaves
};
export type HashedLinkSelect = EnforceTrueOrNested<
Pick<Prisma.HashedLinkSelect, "id"> & {
eventType?: Pick<Prisma.EventTypeSelect, "userId" | "teamId"> & {
hosts?: {
user?: Prisma.UserSelect;
};
profile?: {
user?: Prisma.UserSelect;
};
owner?: Prisma.UserSelect;
};
}
>;
@@ -1,162 +0,0 @@
import type { PrismaClient } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
interface RecordFormResponseInput {
formId: string;
response: Record<string, any> | Prisma.JsonValue;
chosenRouteId: string | null;
}
export class RoutingFormResponseRepository {
constructor(private prismaClient: PrismaClient) {}
private generateCreateFormResponseData(
input: RecordFormResponseInput & { queuedFormResponseId?: string | null }
) {
return {
formId: input.formId,
response: input.response as Prisma.InputJsonValue,
chosenRouteId: input.chosenRouteId,
...(input.queuedFormResponseId
? {
queuedFormResponse: {
connect: {
id: input.queuedFormResponseId,
},
},
}
: {}),
};
}
async recordFormResponse(
input: RecordFormResponseInput & {
queuedFormResponseId?: string | null;
}
) {
return await this.prismaClient.app_RoutingForms_FormResponse.create({
data: this.generateCreateFormResponseData(input),
});
}
async recordQueuedFormResponse(input: RecordFormResponseInput) {
return await this.prismaClient.app_RoutingForms_QueuedFormResponse.create({
data: this.generateCreateFormResponseData(input),
});
}
async findFormResponseIncludeForm({ routingFormResponseId }: { routingFormResponseId: number }) {
return await this.prismaClient.app_RoutingForms_FormResponse.findUnique({
where: {
id: routingFormResponseId,
},
select: {
response: true,
form: {
select: {
routes: true,
fields: true,
},
},
chosenRouteId: true,
},
});
}
async findQueuedFormResponseIncludeForm({ queuedFormResponseId }: { queuedFormResponseId: string }) {
return await this.prismaClient.app_RoutingForms_QueuedFormResponse.findUnique({
where: {
id: queuedFormResponseId,
},
select: {
response: true,
form: {
select: {
routes: true,
fields: true,
},
},
chosenRouteId: true,
},
});
}
async getQueuedFormResponseFromId(id: string) {
return await this.prismaClient.app_RoutingForms_QueuedFormResponse.findUnique({
where: {
id,
},
select: {
id: true,
formId: true,
response: true,
chosenRouteId: true,
createdAt: true,
updatedAt: true,
actualResponseId: true,
form: {
select: {
team: {
select: {
parentId: true,
},
},
user: {
select: {
id: true,
email: true,
timeFormat: true,
locale: true,
},
},
id: true,
description: true,
position: true,
routes: true,
createdAt: true,
updatedAt: true,
name: true,
fields: true,
updatedById: true,
userId: true,
teamId: true,
disabled: true,
settings: true,
},
},
},
});
}
async findAllResponsesWithBooking({
formId,
responseId,
createdAfter,
createdBefore,
}: {
formId: string;
responseId: number;
createdAfter: Date;
createdBefore: Date;
}) {
return await this.prismaClient.app_RoutingForms_FormResponse.findMany({
where: {
formId,
createdAt: {
gte: createdAfter,
lt: createdBefore,
},
routedToBookingUid: {
not: null,
},
NOT: {
id: responseId,
},
},
select: {
id: true,
response: true,
},
});
}
}
@@ -1,493 +0,0 @@
import prismock from "@calcom/testing/lib/__mocks__/prisma";
import { describe, expect, it, beforeEach } from "vitest";
import type { FeatureId } from "@calcom/features/flags/config";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import prisma from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import { SelectedCalendarRepository } from "./selectedCalendar";
describe("SelectedCalendarRepository", () => {
beforeEach(() => {
prismock.selectedCalendar.deleteMany();
});
describe("getNextBatchToWatch", () => {
it("excludes calendars when calendar-cache feature is disabled on a team", async () => {
const user = await prisma.user.create({
data: {
email: "[email protected]",
username: "calendar-cache-disabled",
},
});
const team = await prisma.team.create({
data: {
name: "Calendar Cache Disabled Team",
slug: "calendar-cache-disabled-team",
},
});
await prisma.membership.create({
data: {
userId: user.id,
teamId: team.id,
role: MembershipRole.ADMIN,
accepted: true,
},
});
const featuresRepository = new FeaturesRepository(prismock);
await featuresRepository.setTeamFeatureState({
teamId: team.id,
featureId: "calendar-cache" as FeatureId,
state: "disabled",
assignedBy: "test",
});
await prisma.selectedCalendar.create({
data: {
userId: user.id,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
},
});
const nextBatch = await SelectedCalendarRepository.getNextBatchToWatch();
expect(nextBatch).toEqual([]);
});
});
describe("create", () => {
it("should create a selected calendar", async () => {
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
};
const result = await SelectedCalendarRepository.create(data);
expect(result).toEqual(expect.objectContaining(data));
});
it("should throw error if we try to create a user-level calendar with same userId_integration_externalId as an existing user-level calendar", async () => {
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null,
};
await SelectedCalendarRepository.create(data);
await expect(
SelectedCalendarRepository.create({
...data,
credentialId: 2,
})
).rejects.toThrow("Selected calendar already exists");
});
it("should allow creating a user-level calendar with same userId_integration_externalId as an existing event-type level calendar", async () => {
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: 1,
};
await SelectedCalendarRepository.create(data);
const userLevelCalendarData = {
...data,
eventTypeId: null,
};
const created = await SelectedCalendarRepository.create(userLevelCalendarData);
expect(created).toEqual(expect.objectContaining(userLevelCalendarData));
});
});
describe("update", () => {
it("should update a selected calendar and return it", async () => {
const calendarToUpdate = await SelectedCalendarRepository.create({
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
});
const updatedCalendar = await SelectedCalendarRepository.update({
where: { userId: 1, externalId: "[email protected]" },
data: { integration: "office365_calendar" },
});
expect(updatedCalendar.id).toBe(calendarToUpdate.id);
expect(updatedCalendar.integration).toBe("office365_calendar");
});
it("should throw error when trying to update multiple calendars", async () => {
await SelectedCalendarRepository.create({
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
});
await SelectedCalendarRepository.create({
userId: 1,
integration: "google_calendar2",
externalId: "[email protected]",
credentialId: 2,
});
await expect(
SelectedCalendarRepository.update({
where: { userId: 1, externalId: "[email protected]" },
data: { integration: "office365_calendar" },
})
).rejects.toThrow(
"Multiple SelectedCalendar records found to update. updateMany should be used instead"
);
});
});
describe("delete", () => {
it("should delete a selected calendar and return it", async () => {
const calendar = await SelectedCalendarRepository.create({
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
});
const deleted = await SelectedCalendarRepository.delete({
where: {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
},
});
expect(deleted).toEqual(calendar);
const result = await SelectedCalendarRepository.findFirst({
where: { id: calendar.id },
});
expect(result).toBeNull();
});
it("should throw error when trying to delete non-existent calendar", async () => {
await expect(
SelectedCalendarRepository.delete({
where: {
userId: 999,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 999,
},
})
).rejects.toThrow("SelectedCalendar not found");
});
});
describe("findUserLevelUniqueOrThrow", () => {
it("should find user level calendar", async () => {
const calendar = await SelectedCalendarRepository.create({
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null, // User level calendar
});
const result = await SelectedCalendarRepository.findUserLevelUniqueOrThrow({
where: { userId: 1, externalId: "[email protected]" },
});
expect(result).toEqual(
expect.objectContaining({
userId: calendar.userId,
externalId: calendar.externalId,
})
);
});
it("should not find event type level calendar", async () => {
await SelectedCalendarRepository.create({
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: 1, // Event type level calendar
});
await expect(
SelectedCalendarRepository.findUserLevelUniqueOrThrow({
where: { userId: 1, externalId: "[email protected]" },
})
).rejects.toThrow("SelectedCalendar not found");
});
});
describe("upsert", () => {
describe("User Level Calendar", () => {
const eventTypeId = null;
it("should update existing calendar as long as a record with same userId_integration_externalId is present for eventTypeId=null", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const updatedData = {
...initialData,
credentialId: 2,
eventTypeId,
};
const result = await SelectedCalendarRepository.upsert(updatedData);
expect(result.credentialId).toBe(2);
expect(existingCalendar.id).toBe(result.id);
});
it("should create new calendar if no record with same userId_integration_externalId is present when eventTypeId=null", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const updatedData = {
...initialData,
externalId: "[email protected]",
credentialId: 2,
eventTypeId,
};
const result = await SelectedCalendarRepository.upsert(updatedData);
expect(await prisma.selectedCalendar.count()).toBe(2);
expect(result).toEqual(expect.objectContaining(updatedData));
expect(existingCalendar.id).not.toBe(result.id);
});
});
describe("Event Type Level Calendar", () => {
const eventTypeId = 101;
it("should update existing calendar as long as record with same userId_integration_externalId_eventTypeId is present", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const updatedData = {
...initialData,
credentialId: 2,
eventTypeId,
};
const result = await SelectedCalendarRepository.upsert(updatedData);
expect(result.credentialId).toBe(2);
expect(existingCalendar.id).toBe(result.id);
});
it("should create new calendar if no record with same userId_integration_externalId_eventTypeId is present", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const updatedData = {
...initialData,
credentialId: 2,
externalId: "[email protected]",
eventTypeId,
};
const result = await SelectedCalendarRepository.upsert(updatedData);
expect(await prisma.selectedCalendar.count()).toBe(2);
expect(result).toEqual(expect.objectContaining(updatedData));
expect(existingCalendar.id).not.toBe(result.id);
});
});
});
describe("Delegation Credential", () => {
it("should create a selected calendar with delegationCredentialId", async () => {
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
delegationCredentialId: "delegationCredential-123",
};
const result = await SelectedCalendarRepository.create(data);
expect(result).toEqual(expect.objectContaining(data));
});
describe("upsert", () => {
describe("updation", () => {
it("should update existing record with delegationCredentialId if credentialId is -1", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: -1,
delegationCredentialId: "delegationCredential-123",
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).not.toBe(null);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(null);
expect(result.delegationCredentialId).toBe(data.delegationCredentialId);
});
it("should update existing record with credentialId if credentialId is valid(>0) even if delegationCredentialId is set", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 2,
delegationCredentialId: "delegationCredential-123",
};
const beforeDelegationCredentialId = data.delegationCredentialId;
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).not.toBe(null);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(data.credentialId);
expect(result.delegationCredentialId).toBe(beforeDelegationCredentialId);
});
});
describe("creation", () => {
it("should create a new record with delegationCredentialId if credentialId is -1", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: -1,
delegationCredentialId: "delegationCredential-123",
};
// It will create a new record because of unique constraint violation
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).not.toBe(null);
expect(result.id).not.toBe(existingCalendar.id);
expect(result.credentialId).toBe(null);
expect(result.delegationCredentialId).toBe(data.delegationCredentialId);
});
});
it("shouldnt update existing delegationCredentialId if upsert data doesn't have it", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
eventTypeId: null,
delegationCredentialId: "delegationCredential-123",
credentialId: 1,
};
const beforeDelegationCredentialId = initialData.delegationCredentialId;
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(existingCalendar.credentialId);
expect(result.delegationCredentialId).toBe(beforeDelegationCredentialId);
});
it("shouldnt update delegationCredentialId if it is undefined", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
eventTypeId: null,
delegationCredentialId: "delegationCredential-123",
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(existingCalendar.credentialId);
expect(result.delegationCredentialId).toBe(existingCalendar.delegationCredentialId);
});
});
});
});
@@ -1,438 +0,0 @@
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { SelectedCalendarEventTypeIds } from "@calcom/types/Calendar";
import { buildCredentialPayloadForPrisma } from "../buildCredentialPayloadForCalendar";
export type UpdateArguments = {
where: FindManyArgs["where"];
data: Prisma.SelectedCalendarUpdateManyArgs["data"];
};
export type FindManyArgs = {
// https://github.com/microsoft/TypeScript/issues/55217 It crashes atoms build with this if we become too generic here. Seems like a TS bug with complex prisma types.
where?: {
userId?:
| number
| {
in: number[];
};
credentialId?: number | null;
integration?: string;
externalId?: string;
eventTypeId?: number | null;
googleChannelId?:
| string
| null
| {
not: null;
};
};
orderBy?: {
userId?: "asc" | "desc";
};
select?: Prisma.SelectedCalendarSelect;
};
const ensureUserLevelWhere = {
eventTypeId: null,
};
export class SelectedCalendarRepository {
private static async findConflicting(data: {
userId: number;
integration: string;
externalId: string;
eventTypeId?: number | null;
}) {
// Because userId_integration_externalId_eventTypeId is a unique constraint but with eventTypeId being nullable,
// it allows for multiple entries with the same (userId, integration, externalId) with eventTypeId=null in DB.
// We restrict it at app level by ensuring that an entry doesn't exist already before creating a new one
return await SelectedCalendarRepository.findFirst({
where: {
userId: data.userId,
integration: data.integration,
externalId: data.externalId,
eventTypeId: data.eventTypeId || null,
},
});
}
static async findById(id: string) {
return await prisma.selectedCalendar.findUnique({ where: { id } });
}
static async create(data: Prisma.SelectedCalendarUncheckedCreateInput) {
const conflictingCalendar = await SelectedCalendarRepository.findConflicting(data);
if (conflictingCalendar) {
throw new Error(
`Selected calendar already exists for userId: ${data.userId}, integration: ${data.integration}, externalId: ${data.externalId}, eventTypeId: ${data.eventTypeId}`
);
}
return await prisma.selectedCalendar.create({
data: {
...data,
},
});
}
static async upsert(data: Prisma.SelectedCalendarUncheckedCreateInput) {
// userId_integration_externalId_eventTypeId is a unique constraint but with eventTypeId being nullable
// So, this unique constraint can't be used in upsert. Prisma doesn't allow that, So, we do create and update separately
const credentialPayload = buildCredentialPayloadForPrisma({
credentialId: data.credentialId,
delegationCredentialId: data.delegationCredentialId,
});
const newData = {
...data,
...credentialPayload,
};
const conflictingCalendar = await SelectedCalendarRepository.findConflicting(newData);
if (conflictingCalendar) {
return await prisma.selectedCalendar.update({
where: {
id: conflictingCalendar.id,
},
data: newData,
});
}
return await prisma.selectedCalendar.create({
data: newData,
});
}
static async delete({ where }: { where: Prisma.SelectedCalendarUncheckedCreateInput }) {
const calendarsToDelete = await SelectedCalendarRepository.findMany({ where });
if (calendarsToDelete.length === 0) {
// Same behaviour as Prisma.delete as it throws error if no record is found
throw new Error("SelectedCalendar not found");
}
if (calendarsToDelete.length > 1) {
throw new Error("Multiple SelectedCalendar records found to delete. deleteMany should be used instead");
}
// We can't use delete because unique constraint on userId_integration_externalId_eventTypeId has eventTypeId as nullable
return await prisma.selectedCalendar.delete({
where: {
id: calendarsToDelete[0].id,
},
});
}
static async deleteById({ id }: { id: string }) {
return await prisma.selectedCalendar.delete({
where: {
id,
},
});
}
static async createIfNotExists(data: Prisma.SelectedCalendarUncheckedCreateInput) {
const conflictingCalendar = await SelectedCalendarRepository.findConflicting(data);
if (conflictingCalendar) return conflictingCalendar;
return await prisma.selectedCalendar.create({
data,
});
}
/** Retrieve calendars that need to be watched */
static async getNextBatchToWatch(limit = 100) {
// Get selected calendars from users that belong to a team that has calendar cache enabled
const oneDayInMS = 24 * 60 * 60 * 1000;
const tomorrowTimestamp = String(new Date().getTime() + oneDayInMS);
const nextBatch = await prisma.selectedCalendar.findMany({
take: limit,
where: {
user: {
teams: {
some: {
team: {
features: {
some: {
featureId: "calendar-cache",
enabled: true,
},
},
},
},
},
},
// RN we only support google calendar subscriptions for now
integration: "google_calendar",
AND: [
{
OR: [
// Either is a calendar that has not errored
{ error: null },
// Or is a calendar that has errored but has not reached max attempts
{
error: { not: null },
watchAttempts: {
lt: {
// @ts-expect-error - _ref is a Prisma extension field
_ref: "maxAttempts",
_container: "SelectedCalendar",
},
},
},
],
},
{
OR: [
// Either is a calendar pending to be watched
{ googleChannelExpiration: null },
// Or is a calendar that is about to expire
{ googleChannelExpiration: { lt: tomorrowTimestamp } },
],
},
],
},
});
return nextBatch;
}
/**
* Retrieve calendars that are being watched but shouldn't be anymore
* e.g. when a user disables calendar cache for the organization
*/
static async getNextBatchToUnwatch(limit = 100) {
const where: Prisma.SelectedCalendarWhereInput = {
// RN we only support google calendar subscriptions for now
integration: "google_calendar",
googleChannelExpiration: { not: null },
AND: [
{
OR: [
// Either is a calendar that has not errored during unwatch
{ error: null },
// Or is a calendar that has errored during unwatch but has not reached max attempts
{
error: { not: null },
unwatchAttempts: {
lt: {
// @ts-expect-error - _ref is a Prisma extension field
_ref: "maxAttempts",
_container: "SelectedCalendar",
},
},
},
],
},
{
user: {
teams: {
every: {
team: {
features: {
none: {
featureId: "calendar-cache",
enabled: true,
},
},
},
},
},
},
},
],
};
// If calendar cache is disabled globally, we skip team features and unwatch all subscriptions
const nextBatch = await prisma.selectedCalendar.findMany({
take: limit,
where,
});
return nextBatch;
}
static async findMany({ where, select, orderBy }: FindManyArgs) {
const args = {
where,
select,
orderBy,
} satisfies Prisma.SelectedCalendarFindManyArgs;
return await prisma.selectedCalendar.findMany(args);
}
static async findUniqueOrThrow({ where }: { where: Prisma.SelectedCalendarWhereInput }) {
const calendars = await prisma.selectedCalendar.findMany({ where });
if (calendars.length === 0) {
throw new Error("SelectedCalendar not found");
}
return calendars[0];
}
static async findFirstByGoogleChannelId(googleChannelId: string) {
return await prisma.selectedCalendar.findFirst({
where: {
googleChannelId,
},
select: {
credential: {
select: {
...credentialForCalendarServiceSelect,
selectedCalendars: {
orderBy: {
externalId: "asc",
},
},
},
},
},
});
}
static async findFirst({ where }: { where: Prisma.SelectedCalendarWhereInput }) {
return await prisma.selectedCalendar.findFirst({
where,
});
}
static async findFirstOrThrow({ where }: { where: Prisma.SelectedCalendarWhereInput }) {
const calendar = await SelectedCalendarRepository.findFirst({ where });
if (!calendar) {
throw new Error("SelectedCalendar not found");
}
return calendar;
}
static async update(args: UpdateArguments) {
const calendarsToUpdate = await SelectedCalendarRepository.findMany({ where: args.where });
if (calendarsToUpdate.length === 0) {
throw new Error("SelectedCalendar not found");
}
if (calendarsToUpdate.length > 1) {
throw new Error("Multiple SelectedCalendar records found to update. updateMany should be used instead");
}
const calendarToUpdate = calendarsToUpdate[0];
return await prisma.selectedCalendar.update({
where: {
id: calendarToUpdate.id,
},
data: args.data,
});
}
/**
* Following methods ensure that they operate on user level calendars only
*/
static async findUserLevelUniqueOrThrow({ where }: { where: Prisma.SelectedCalendarWhereInput }) {
const calendars = await SelectedCalendarRepository.findUniqueOrThrow({
where: {
...where,
...ensureUserLevelWhere,
},
});
if (!calendars) {
throw new Error("SelectedCalendar not found");
}
return calendars;
}
static async findManyUserLevel(args: FindManyArgs) {
return SelectedCalendarRepository.findMany({
...args,
where: {
...args.where,
...ensureUserLevelWhere,
},
});
}
static async updateUserLevel(args: UpdateArguments) {
return SelectedCalendarRepository.update({
where: {
...args.where,
...ensureUserLevelWhere,
},
data: args.data,
});
}
static async deleteUserLevel({ where }: { where: Prisma.SelectedCalendarUncheckedCreateInput }) {
return await SelectedCalendarRepository.delete({
where: {
...where,
...ensureUserLevelWhere,
},
});
}
static async upsertManyForEventTypeIds({
data,
eventTypeIds,
}: {
data: Prisma.SelectedCalendarUncheckedCreateInput;
eventTypeIds: SelectedCalendarEventTypeIds;
}) {
const userId = data.userId;
return await Promise.all(
eventTypeIds.map((eventTypeId) =>
SelectedCalendarRepository.upsert({
...data,
eventTypeId,
userId,
integration: data.integration,
externalId: data.externalId,
credentialId: data.credentialId,
})
)
);
}
static async updateById(id: string, data: Prisma.SelectedCalendarUpdateInput) {
return await prisma.selectedCalendar.update({
where: { id },
data,
});
}
static async updateManyByCredentialId(credentialId: number, data: Prisma.SelectedCalendarUpdateInput) {
return await prisma.selectedCalendar.updateMany({
where: { credentialId },
data,
});
}
static async setErrorInWatching({ id, error }: { id: string; error: string }) {
await SelectedCalendarRepository.updateById(id, {
error,
lastErrorAt: new Date(),
watchAttempts: { increment: 1 },
});
}
static async setErrorInUnwatching({ id, error }: { id: string; error: string }) {
await SelectedCalendarRepository.updateById(id, {
error,
lastErrorAt: new Date(),
unwatchAttempts: { increment: 1 },
});
}
static async removeWatchingError({ id }: { id: string }) {
await SelectedCalendarRepository.updateById(id, {
error: null,
lastErrorAt: null,
watchAttempts: 0,
});
}
static async removeUnwatchingError({ id }: { id: string }) {
await SelectedCalendarRepository.updateById(id, {
error: null,
lastErrorAt: null,
unwatchAttempts: 0,
});
}
}
@@ -1,51 +0,0 @@
import prisma from "@calcom/prisma";
export class VerificationTokenRepository {
static async updateTeamInviteTokenExpirationDate({
email,
teamId,
expiresInDays,
}: {
email: string;
teamId: number;
expiresInDays: number;
}) {
const expires = new Date(Date.now() + expiresInDays * 24 * 60 * 60 * 1000);
const token = await prisma.verificationToken.findFirst({
where: {
identifier: email,
teamId,
},
});
await prisma.verificationToken.update({
where: {
identifier: email,
teamId,
token: token?.token,
},
data: { expires },
});
return { ...token, expires };
}
static async create({
identifier,
token,
expires,
}: {
identifier: string;
token: string;
expires: Date;
}) {
return prisma.verificationToken.create({
data: {
identifier,
token,
expires,
},
});
}
}
@@ -1,104 +0,0 @@
import { prisma } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import type { TServiceAccountKeySchema } from "@calcom/prisma/zod-utils";
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
type WorkspacePlatformServiceAccountKey = TServiceAccountKeySchema | null;
const safeWorkspacePlatformSelect = {
id: true,
name: true,
enabled: true,
slug: true,
description: true,
};
const workspacePlatformSelectWithServiceAccountKey = {
...safeWorkspacePlatformSelect,
defaultServiceAccountKey: true,
};
export class WorkspacePlatformRepository {
private static withParsedServiceAccountKey<T extends { defaultServiceAccountKey: Prisma.JsonValue }>(
data: T
) {
return {
...data,
defaultServiceAccountKey: serviceAccountKeySchema.parse(data.defaultServiceAccountKey),
};
}
static async create(data: {
slug: string;
name: string;
description: string;
defaultServiceAccountKey?: WorkspacePlatformServiceAccountKey;
enabled: boolean;
}) {
const { defaultServiceAccountKey: _defaultServiceAccountKey, ...rest } = data;
const defaultServiceAccountKey =
_defaultServiceAccountKey === undefined || _defaultServiceAccountKey === null
? Prisma.JsonNull
: _defaultServiceAccountKey;
return await prisma.workspacePlatform.create({
data: {
defaultServiceAccountKey: defaultServiceAccountKey as unknown as Prisma.InputJsonValue,
...rest,
},
select: safeWorkspacePlatformSelect,
});
}
static async findAll() {
return await prisma.workspacePlatform.findMany({
select: safeWorkspacePlatformSelect,
});
}
static async findAllBySlug({ slug }: { slug: string }) {
return await prisma.workspacePlatform.findMany({
where: { slug },
select: safeWorkspacePlatformSelect,
});
}
static async findBySlug({ slug }: { slug: string }) {
return await prisma.workspacePlatform.findUnique({
where: { slug },
select: safeWorkspacePlatformSelect,
});
}
static async findBySlugIncludeSensitiveServiceAccountKey({ slug }: { slug: string }) {
const workspacePlatform = await prisma.workspacePlatform.findUnique({
where: { slug },
select: workspacePlatformSelectWithServiceAccountKey,
});
if (!workspacePlatform) {
return null;
}
return this.withParsedServiceAccountKey(workspacePlatform);
}
static async updateById({
id,
data,
}: {
id: number;
data: Partial<{
slug: string;
name: string;
description: string;
defaultServiceAccountKey: TServiceAccountKeySchema;
enabled: boolean;
}>;
}) {
return await prisma.workspacePlatform.update({
where: { id },
data: {
...data,
defaultServiceAccountKey: data.defaultServiceAccountKey as unknown as Prisma.InputJsonValue,
},
select: safeWorkspacePlatformSelect,
});
}
}
@@ -1,16 +0,0 @@
import { randomBytes, createHash } from "node:crypto";
import { VerificationTokenRepository } from "../repository/verificationToken";
export class VerificationTokenService {
static async create({ identifier, expires }: { identifier: string; expires: Date }) {
const token = randomBytes(32).toString("hex");
const hashedToken = createHash("sha256")
.update(`${token}${process.env.NEXTAUTH_SECRET}`)
.digest("hex");
await VerificationTokenRepository.create({ identifier, token: hashedToken, expires });
return token;
}
}
@@ -1,134 +0,0 @@
import { describe, test, expect, vi, beforeEach, afterEach } from "vitest";
import { VerificationTokenRepository } from "@calcom/lib/server/repository/verificationToken";
import { VerificationTokenService } from "../VerificationTokenService";
vi.mock("@calcom/lib/server/repository/verificationToken", () => ({
VerificationTokenRepository: {
create: vi.fn(),
},
}));
describe("VerificationTokenService", () => {
const originalEnv = process.env;
beforeEach(() => {
vi.clearAllMocks();
process.env = { ...originalEnv };
process.env.NEXTAUTH_SECRET = "test-secret";
vi.mocked(VerificationTokenRepository.create).mockResolvedValue({
identifier: "[email protected]",
token: "hashed-token",
expires: new Date(),
} as any); // eslint-disable-line @typescript-eslint/no-explicit-any
});
afterEach(() => {
process.env = originalEnv;
});
describe("create", () => {
test("should create a verification token and return unhashed token", async () => {
const identifier = "[email protected]";
const expires = new Date(Date.now() + 86400 * 1000);
const result = await VerificationTokenService.create({
identifier,
expires,
});
expect(result).toBeTruthy();
expect(typeof result).toBe("string");
expect(result.length).toBeGreaterThan(0);
expect(VerificationTokenRepository.create).toHaveBeenCalled();
});
test("should call repository with correct identifier and expires", async () => {
const identifier = "[email protected]";
const expires = new Date("2025-12-31T23:59:59.000Z");
await VerificationTokenService.create({
identifier,
expires,
});
expect(VerificationTokenRepository.create).toHaveBeenCalledWith({
identifier,
token: expect.any(String),
expires,
});
const callArgs = vi.mocked(VerificationTokenRepository.create).mock.calls[0][0];
expect(callArgs.identifier).toBe(identifier);
expect(callArgs.expires).toBe(expires);
expect(callArgs.token).toBeTruthy();
});
test("should hash token with NEXTAUTH_SECRET", async () => {
const identifier = "[email protected]";
const expires = new Date(Date.now() + 86400 * 1000);
await VerificationTokenService.create({
identifier,
expires,
});
const callArgs = vi.mocked(VerificationTokenRepository.create).mock.calls[0][0];
// The hashed token should be a 64-character hex string (SHA-256)
expect(callArgs.token).toMatch(/^[a-f0-9]{64}$/);
});
test("should generate unique tokens on multiple calls", async () => {
const identifier = "[email protected]";
const expires = new Date(Date.now() + 86400 * 1000);
const result1 = await VerificationTokenService.create({
identifier,
expires,
});
const result2 = await VerificationTokenService.create({
identifier,
expires,
});
expect(result1).not.toBe(result2);
expect(VerificationTokenRepository.create).toHaveBeenCalledTimes(2);
});
test("should handle Date objects for expires", async () => {
const identifier = "[email protected]";
const expires = new Date(2025, 11, 31, 23, 59, 59);
await VerificationTokenService.create({
identifier,
expires,
});
expect(VerificationTokenRepository.create).toHaveBeenCalledWith({
identifier,
token: expect.any(String),
expires: expect.any(Date),
});
const callArgs = vi.mocked(VerificationTokenRepository.create).mock.calls[0][0];
expect(callArgs.expires).toBeInstanceOf(Date);
expect(callArgs.expires.getTime()).toBe(expires.getTime());
});
test("should generate 32-byte random token in hex format", async () => {
const identifier = "[email protected]";
const expires = new Date(Date.now() + 86400 * 1000);
const token = await VerificationTokenService.create({
identifier,
expires,
});
// 32 bytes = 64 hex characters
expect(token).toMatch(/^[a-f0-9]{64}$/);
});
});
});