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,4 +1,4 @@
import type { RoutingFormResponseRepositoryInterface } from "@calcom/lib/server/repository/RoutingFormResponseRepository.interface";
import type { RoutingFormResponseRepositoryInterface } from "@calcom/features/routing-forms/repositories/RoutingFormResponseRepository.interface";
import type { BookingAuditViewerService, DisplayBookingAuditLog } from "./BookingAuditViewerService";
import { getFieldResponseByIdentifier } from "@calcom/features/routing-forms/lib/getFieldResponseByIdentifier";
@@ -2,7 +2,7 @@ import { prisma } from "@calcom/prisma";
import type { Prisma, PrismaClient } from "@calcom/prisma/client";
import type { PartialReference } from "@calcom/types/EventManager";
import type { IBookingReferenceRepository } from "@calcom/lib/server/repository/dto/IBookingReferenceRepository";
import type { IBookingReferenceRepository } from "./IBookingReferenceRepository";
const bookingReferenceSelect = {
id: true,
@@ -0,0 +1,16 @@
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,6 +1,6 @@
import { bindModuleToClassOnToken, createModule } from "@calcom/features/di/di";
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { BookingReferenceRepository } from "@calcom/lib/server/repository/bookingReference";
import { BookingReferenceRepository } from "@calcom/features/bookingReference/repositories/BookingReferenceRepository";
import { moduleLoader as prismaModuleLoader } from "@calcom/prisma/prisma.module";
export const bookingReferenceRepositoryModule = createModule();
@@ -0,0 +1,52 @@
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,10 +1,4 @@
import { withReporting } from "@calcom/lib/sentryWrapper";
import type {
BookingUpdateData,
BookingWhereInput,
BookingWhereUniqueInput,
IBookingRepository,
} from "@calcom/lib/server/repository/dto/IBookingRepository";
import type { PrismaClient } from "@calcom/prisma";
import type { Booking, Prisma } from "@calcom/prisma/client";
import { BookingStatus, RRTimestampBasis } from "@calcom/prisma/enums";
@@ -15,6 +9,12 @@ import {
} from "@calcom/prisma/selects/booking";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type {
BookingWhereInput,
IBookingRepository,
BookingUpdateData,
BookingWhereUniqueInput,
} from "./IBookingRepository";
import { workflowSelect } from "../../ee/workflows/lib/getAllWorkflows";
const workflowReminderSelect = {
@@ -0,0 +1,55 @@
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[]>;
}
@@ -0,0 +1,68 @@
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,
},
},
},
});
}
}
@@ -0,0 +1,18 @@
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,
},
},
});
}
}
@@ -0,0 +1,5 @@
import type { Tracking } from "@calcom/prisma/client";
export interface TrackingRepositoryInterface {
findByBookingUid(bookingUid: string): Promise<Tracking | null>;
}
@@ -8,7 +8,7 @@ import {
import { DestinationCalendarRepository } from "@calcom/features/calendars/repositories/DestinationCalendarRepository";
import { isDelegationCredential } from "@calcom/lib/delegationCredential";
import logger from "@calcom/lib/logger";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import { SelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import type { DestinationCalendar, SelectedCalendar, User } from "@calcom/prisma/client";
@@ -1,11 +1,49 @@
import logger from "@calcom/lib/logger";
import { buildCredentialPayloadForPrisma } from "@calcom/lib/server/buildCredentialPayloadForCalendar";
import type { PrismaClient } from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
const log = logger.getSubLogger({ prefix: ["DestinationCalendarRepository"] });
export class DestinationCalendarRepository {
private prismaClient: PrismaClient;
constructor(prismaClient?: PrismaClient) {
this.prismaClient = prismaClient ?? prisma;
}
async getCustomReminderByCredentialId(credentialId: number): Promise<number | null> {
const destinationCalendar = await this.prismaClient.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.prismaClient.destinationCalendar.updateMany({
where: {
userId,
credentialId,
integration,
},
data: {
customCalendarReminder,
},
});
}
static async create(data: Prisma.DestinationCalendarCreateInput) {
return await prisma.destinationCalendar.create({
data,
@@ -1,4 +1,4 @@
import type { DestinationCalendarRepository } from "@calcom/lib/server/repository/destinationCalendar";
import type { DestinationCalendarRepository } from "@calcom/features/calendars/repositories/DestinationCalendarRepository";
import { createContainer } from "../di";
import { moduleLoader as destinationCalendarRepositoryModuleLoader } from "../modules/DestinationCalendar";
@@ -1,4 +1,4 @@
import { DestinationCalendarRepository } from "@calcom/lib/server/repository/destinationCalendar";
import { DestinationCalendarRepository } from "@calcom/features/calendars/repositories/DestinationCalendarRepository";
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
@@ -1,5 +1,5 @@
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { RoutingFormResponseRepository } from "@calcom/lib/server/repository/formResponse";
import { RoutingFormResponseRepository } from "@calcom/features/routing-forms/repositories/RoutingFormResponseRepository";
import { createModule } from "../di";
@@ -13,7 +13,7 @@ import { zodRoutes as routesSchema } from "@calcom/app-store/routing-forms/zod";
/* eslint-enable */
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { RoutingFormResponseRepository } from "@calcom/lib/server/repository/formResponse";
import { RoutingFormResponseRepository } from "@calcom/features/routing-forms/repositories/RoutingFormResponseRepository";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { SchedulingType } from "@calcom/prisma/enums";
@@ -0,0 +1,19 @@
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;
};
}
>;
@@ -0,0 +1,326 @@
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);
});
});
});
@@ -0,0 +1,217 @@
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 },
},
},
});
}
}
@@ -0,0 +1,13 @@
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>;
}
@@ -4,7 +4,7 @@ import { getParsedTeam } from "@calcom/features/ee/teams/lib/getParsedTeam";
import { DATABASE_CHUNK_SIZE } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import type { IProfileRepository } from "@calcom/lib/server/repository/dto/IProfileRepository";
import type { IProfileRepository } from "./IProfileRepository";
import prisma from "@calcom/prisma";
import type { Prisma, PrismaClient, User as PrismaUser, Team } from "@calcom/prisma/client";
import { MembershipRole } from "@calcom/prisma/enums";
@@ -1,4 +1,4 @@
import { PrismaRoutingFormResponseRepository } from "@calcom/lib/server/repository/PrismaRoutingFormResponseRepository";
import { PrismaRoutingFormResponseRepository } from "@calcom/features/routing-forms/repositories/PrismaRoutingFormResponseRepository";
import { ROUTING_FORM_DI_TOKENS } from "@calcom/features/routing-forms/di/tokens";
import { bindModuleToClassOnToken } from "@calcom/features/di/di";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
@@ -7,7 +7,7 @@ import routerGetCrmContactOwnerEmail from "@calcom/app-store/routing-forms/lib/c
import type { TargetRoutingFormForResponse } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
import { onSubmissionOfFormResponse } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
import isRouter from "@calcom/app-store/routing-forms/lib/isRouter";
import { RoutingFormResponseRepository } from "@calcom/lib/server/repository/formResponse";
import { RoutingFormResponseRepository } from "@calcom/features/routing-forms/repositories/RoutingFormResponseRepository";
import { findTeamMembersMatchingAttributeLogic } from "./findTeamMembersMatchingAttributeLogic";
import { handleResponse } from "./handleResponse";
@@ -16,7 +16,7 @@ vi.mock("./findTeamMembersMatchingAttributeLogic", () => ({
findTeamMembersMatchingAttributeLogic: vi.fn(),
}));
vi.mock("@calcom/lib/server/repository/formResponse");
vi.mock("@calcom/features/routing-forms/repositories/RoutingFormResponseRepository");
const mockRoutingFormResponseRepository = {
recordQueuedFormResponse: vi.fn(),
@@ -11,7 +11,7 @@ import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { RoutingFormResponseRepository } from "@calcom/lib/server/repository/formResponse";
import { RoutingFormResponseRepository } from "@calcom/features/routing-forms/repositories/RoutingFormResponseRepository";
import { prisma } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { z } from "zod";
@@ -0,0 +1,38 @@
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,
},
},
},
});
}
}
@@ -0,0 +1,11 @@
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>;
}
@@ -0,0 +1,162 @@
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,7 +1,12 @@
import prismock from "@calcom/testing/lib/__mocks__/prisma";
import type { FeatureId } from "@calcom/features/flags/config";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { SelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import type { Prisma, SelectedCalendar } from "@calcom/prisma/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { MembershipRole } from "@calcom/prisma/enums";
import { beforeEach, describe, expect, test, vi, it } from "vitest";
const mockPrismaClient = {
selectedCalendar: {
@@ -367,4 +372,486 @@ describe("SelectedCalendarRepository", () => {
expect(result).toEqual(updatedCalendar);
});
});
describe("Static Methods", () => {
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,
});
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,
});
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",
};
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,12 +1,49 @@
import type { ISelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository.interface";
import { buildCredentialPayloadForPrisma } from "@calcom/lib/server/buildCredentialPayloadForCalendar";
import type { PrismaClient } from "@calcom/prisma";
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";
export type UpdateArguments = {
where: FindManyArgs["where"];
data: Prisma.SelectedCalendarUpdateManyArgs["data"];
};
export type FindManyArgs = {
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,
};
const MAX_SUBSCRIBE_ERRORS = 3;
export class SelectedCalendarRepository implements ISelectedCalendarRepository {
constructor(private prismaClient: PrismaClient) {}
// Instance method for DI (implements interface)
async findById(id: string) {
return this.prismaClient.selectedCalendar.findUnique({
where: { id },
@@ -104,4 +141,379 @@ export class SelectedCalendarRepository implements ISelectedCalendarRepository {
data,
});
}
// Static methods for direct usage (from lib version)
private static async findConflicting(data: {
userId: number;
integration: string;
externalId: string;
eventTypeId?: number | null;
}) {
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) {
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) {
throw new Error("SelectedCalendar not found");
}
if (calendarsToDelete.length > 1) {
throw new Error("Multiple SelectedCalendar records found to delete. deleteMany should be used instead");
}
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,
});
}
static async getNextBatchToWatch(limit = 100) {
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,
},
},
},
},
},
},
integration: "google_calendar",
AND: [
{
OR: [
{ error: null },
{
error: { not: null },
watchAttempts: {
lt: {
// @ts-expect-error - _ref is a Prisma extension field
_ref: "maxAttempts",
_container: "SelectedCalendar",
},
},
},
],
},
{
OR: [
{ googleChannelExpiration: null },
{ googleChannelExpiration: { lt: tomorrowTimestamp } },
],
},
],
},
});
return nextBatch;
}
static async getNextBatchToUnwatch(limit = 100) {
const where: Prisma.SelectedCalendarWhereInput = {
integration: "google_calendar",
googleChannelExpiration: { not: null },
AND: [
{
OR: [
{ error: null },
{
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,
},
},
},
},
},
},
},
],
};
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,
});
}
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,
});
}
}
@@ -7,7 +7,7 @@ import { AttendeeRepository } from "@calcom/features/bookings/repositories/Atten
import stripe from "@calcom/features/ee/payments/server/stripe";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { PrismaBookingPaymentRepository } from "@calcom/lib/server/repository/PrismaBookingPaymentRepository";
import { PrismaBookingPaymentRepository } from "@calcom/features/bookings/repositories/PrismaBookingPaymentRepository";
import prisma from "@calcom/prisma";
const log = logger.getSubLogger({ prefix: ["sendAwaitingPaymentEmail"] });
@@ -1,5 +1,5 @@
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { RoutingFormResponseRepository } from "@calcom/lib/server/repository/formResponse";
import { RoutingFormResponseRepository } from "@calcom/features/routing-forms/repositories/RoutingFormResponseRepository";
import prisma from "@calcom/prisma";
import type { FORM_SUBMITTED_WEBHOOK_RESPONSES } from "@calcom/routing-forms/lib/formSubmissionUtils";
@@ -0,0 +1,104 @@
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,
});
}
}