refactor: Migrate repositories/services from /lib to /features (#25925)

* deployment

* update imports

* booking report

* update import paths

* watch list

* watch list

* api key

* api key

* selected slots

* wip

* event type translation

* work flow step

* booking reference

* fix tests

* fix

* fix

* migrate

* wip

* address

* fix
This commit is contained in:
Benny Joo authored and GitHub committed 2025-12-17 14:14:50 +00:00
1 parent aaaff0705b
commit cb7844fd22
69 files changed
+197 -162

No files matched your search

@@ -4,11 +4,11 @@ import type { AuthOptions, Session } from "next-auth";
import { getToken } from "next-auth/jwt";
import { LicenseKeySingleton } from "@calcom/ee/common/server/LicenseKeyService";
import { DeploymentRepository } from "@calcom/features/ee/deployment/repositories/DeploymentRepository";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { DeploymentRepository } from "@calcom/lib/server/repository/deployment";
import prisma from "@calcom/prisma";
const log = logger.getSubLogger({ prefix: ["getServerSession"] });
@@ -13,6 +13,7 @@ import { updateProfilePhotoGoogle } from "@calcom/app-store/_utils/oauth/updateP
import GoogleCalendarService from "@calcom/app-store/googlecalendar/lib/CalendarService";
import { LicenseKeySingleton } from "@calcom/ee/common/server/LicenseKeyService";
import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
import { DeploymentRepository } from "@calcom/features/ee/deployment/repositories/DeploymentRepository";
import createUsersAndConnectToOrg from "@calcom/features/ee/dsync/lib/users/createUsersAndConnectToOrg";
import ImpersonationProvider from "@calcom/features/ee/impersonation/lib/ImpersonationProvider";
import { getOrganizationRepository } from "@calcom/features/ee/organizations/di/OrganizationRepository.container";
@@ -36,7 +37,6 @@ import logger from "@calcom/lib/logger";
import { randomString } from "@calcom/lib/random";
import { safeStringify } from "@calcom/lib/safeStringify";
import { hashEmail } from "@calcom/lib/server/PiiHasher";
import { DeploymentRepository } from "@calcom/lib/server/repository/deployment";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
import type { Membership, Team } from "@calcom/prisma/client";
@@ -0,0 +1,383 @@
import { describe, it, expect, beforeAll, afterAll, afterEach } from "vitest";
import prisma from "@calcom/prisma";
import type { Booking, Credential, User } from "@calcom/prisma/client";
import { BookingReferenceRepository } from "./BookingReferenceRepository";
describe("BookingReferenceRepository Integration Tests", () => {
let testUser: User;
let testCredential: Credential;
let testBooking: Booking;
const createdBookingReferenceIds: number[] = [];
beforeAll(async () => {
testUser = await prisma.user.create({
data: {
email: "[email protected]",
username: "bookingreference-test",
},
});
testCredential = await prisma.credential.create({
data: {
type: "google_calendar",
key: {},
userId: testUser.id,
},
});
testBooking = await prisma.booking.create({
data: {
uid: "test-booking-uid-123",
title: "Test Booking",
startTime: new Date(),
endTime: new Date(),
userId: testUser.id,
},
});
});
afterEach(async () => {
if (createdBookingReferenceIds.length > 0) {
await prisma.bookingReference.deleteMany({
where: {
id: {
in: createdBookingReferenceIds,
},
},
});
createdBookingReferenceIds.splice(0, createdBookingReferenceIds.length);
}
});
afterAll(async () => {
await prisma.booking.delete({
where: {
id: testBooking.id,
},
});
await prisma.credential.delete({
where: {
id: testCredential.id,
},
});
await prisma.user.delete({
where: {
id: testUser.id,
},
});
});
describe("replaceBookingReferences", () => {
it("should soft-delete existing references and create new ones", async () => {
const existingReference1 = await prisma.bookingReference.create({
data: {
type: "google_calendar",
uid: "old-ref-1",
meetingId: "old-meeting-1",
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(existingReference1.id);
const existingReference2 = await prisma.bookingReference.create({
data: {
type: "google_calendar",
uid: "old-ref-2",
meetingId: "old-meeting-2",
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(existingReference2.id);
const newReferences = [
{
type: "google_calendar",
uid: "new-ref-1",
meetingId: "new-meeting-1",
credentialId: testCredential.id,
},
{
type: "google_calendar",
uid: "new-ref-2",
meetingId: "new-meeting-2",
credentialId: testCredential.id,
},
];
await BookingReferenceRepository.replaceBookingReferences({
bookingId: testBooking.id,
newReferencesToCreate: newReferences,
});
const allReferences = await prisma.bookingReference.findMany({
where: {
bookingId: testBooking.id,
},
});
const oldReferences = allReferences.filter((ref) => ref.uid === "old-ref-1" || ref.uid === "old-ref-2");
const newlyCreatedReferences = allReferences.filter(
(ref) => ref.uid === "new-ref-1" || ref.uid === "new-ref-2"
);
expect(oldReferences).toHaveLength(2);
expect(oldReferences.every((ref) => ref.deleted === true)).toBe(true);
expect(newlyCreatedReferences).toHaveLength(2);
expect(newlyCreatedReferences.every((ref) => ref.deleted === null)).toBe(true);
newlyCreatedReferences.forEach((ref) => {
createdBookingReferenceIds.push(ref.id);
});
});
it("should only soft-delete references of the same type as new references being created", async () => {
const googleRef = await prisma.bookingReference.create({
data: {
type: "google_calendar",
uid: "google-ref",
meetingId: "google-meeting",
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(googleRef.id);
const zoomRef = await prisma.bookingReference.create({
data: {
type: "zoom_video",
uid: "zoom-ref",
meetingId: "zoom-meeting",
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(zoomRef.id);
const newGoogleReferences = [
{
type: "google_calendar",
uid: "new-google-ref",
meetingId: "new-google-meeting",
credentialId: testCredential.id,
},
];
await BookingReferenceRepository.replaceBookingReferences({
bookingId: testBooking.id,
newReferencesToCreate: newGoogleReferences,
});
const googleRefAfter = await prisma.bookingReference.findUnique({
where: { id: googleRef.id },
});
expect(googleRefAfter?.deleted).toBe(true);
const zoomRefAfter = await prisma.bookingReference.findUnique({
where: { id: zoomRef.id },
});
expect(zoomRefAfter?.deleted).toBe(null);
const newRef = await prisma.bookingReference.findFirst({
where: {
uid: "new-google-ref",
bookingId: testBooking.id,
},
});
expect(newRef).toBeDefined();
expect(newRef?.deleted).toBe(null);
if (newRef) {
createdBookingReferenceIds.push(newRef.id);
}
});
it("should persist soft-deleted records in database", async () => {
const reference = await prisma.bookingReference.create({
data: {
type: "daily_video",
uid: "daily-ref",
meetingId: "daily-meeting",
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(reference.id);
const newReferences = [
{
type: "daily_video",
uid: "new-daily-ref",
meetingId: "new-daily-meeting",
credentialId: testCredential.id,
},
];
await BookingReferenceRepository.replaceBookingReferences({
bookingId: testBooking.id,
newReferencesToCreate: newReferences,
});
const deletedRefInDb = await prisma.bookingReference.findUnique({
where: { id: reference.id },
});
expect(deletedRefInDb).toBeDefined();
expect(deletedRefInDb?.deleted).toBe(true);
expect(deletedRefInDb?.uid).toBe("daily-ref");
const newRef = await prisma.bookingReference.findFirst({
where: {
uid: "new-daily-ref",
bookingId: testBooking.id,
},
});
if (newRef) {
createdBookingReferenceIds.push(newRef.id);
}
});
});
describe("findDailyVideoReferenceByRoomName", () => {
it("should find active daily video references", async () => {
const roomName = "test-daily-room-123";
const dailyRef = await prisma.bookingReference.create({
data: {
type: "daily_video",
uid: roomName,
meetingId: roomName,
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(dailyRef.id);
const result = await BookingReferenceRepository.findDailyVideoReferenceByRoomName({
roomName,
});
expect(result).toBeDefined();
expect(result?.id).toBe(dailyRef.id);
expect(result?.uid).toBe(roomName);
expect(result?.deleted).toBe(null);
});
it("should exclude soft-deleted daily video references", async () => {
const roomName = "test-daily-room-deleted-456";
const dailyRef = await prisma.bookingReference.create({
data: {
type: "daily_video",
uid: roomName,
meetingId: roomName,
credentialId: testCredential.id,
bookingId: testBooking.id,
deleted: true,
},
});
createdBookingReferenceIds.push(dailyRef.id);
const result = await BookingReferenceRepository.findDailyVideoReferenceByRoomName({
roomName,
});
expect(result).toBeNull();
});
it("should return null when room name does not exist", async () => {
const result = await BookingReferenceRepository.findDailyVideoReferenceByRoomName({
roomName: "non-existent-room",
});
expect(result).toBeNull();
});
it("should not return daily video references without a booking", async () => {
const roomName = "test-daily-room-no-booking";
const dailyRef = await prisma.bookingReference.create({
data: {
type: "daily_video",
uid: roomName,
meetingId: roomName,
credentialId: testCredential.id,
bookingId: null,
},
});
createdBookingReferenceIds.push(dailyRef.id);
const result = await BookingReferenceRepository.findDailyVideoReferenceByRoomName({
roomName,
});
expect(result).toBeNull();
});
});
describe("Soft-delete behavior verification", () => {
it("should not return soft-deleted references in regular queries", async () => {
const activeRef = await prisma.bookingReference.create({
data: {
type: "zoom_video",
uid: "active-zoom",
meetingId: "active-zoom-meeting",
credentialId: testCredential.id,
bookingId: testBooking.id,
},
});
createdBookingReferenceIds.push(activeRef.id);
const deletedRef = await prisma.bookingReference.create({
data: {
type: "zoom_video",
uid: "deleted-zoom",
meetingId: "deleted-zoom-meeting",
credentialId: testCredential.id,
bookingId: testBooking.id,
deleted: true,
},
});
createdBookingReferenceIds.push(deletedRef.id);
const foundReferences = await prisma.bookingReference.findMany({
where: {
bookingId: testBooking.id,
type: "zoom_video",
deleted: null,
},
});
expect(foundReferences).toHaveLength(1);
expect(foundReferences[0].id).toBe(activeRef.id);
expect(foundReferences[0].uid).toBe("active-zoom");
});
it("should allow querying soft-deleted references explicitly", async () => {
const deletedRef = await prisma.bookingReference.create({
data: {
type: "office365_calendar",
uid: "deleted-office365",
meetingId: "deleted-office365-meeting",
credentialId: testCredential.id,
bookingId: testBooking.id,
deleted: true,
},
});
createdBookingReferenceIds.push(deletedRef.id);
const foundDeletedReferences = await prisma.bookingReference.findMany({
where: {
bookingId: testBooking.id,
deleted: true,
},
});
expect(foundDeletedReferences.length).toBeGreaterThan(0);
const ourDeletedRef = foundDeletedReferences.find((ref) => ref.id === deletedRef.id);
expect(ourDeletedRef).toBeDefined();
expect(ourDeletedRef?.uid).toBe("deleted-office365");
});
});
});
@@ -0,0 +1,60 @@
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import type { PartialReference } from "@calcom/types/EventManager";
const bookingReferenceSelect = {
id: true,
type: true,
uid: true,
meetingId: true,
meetingUrl: true,
credentialId: true,
deleted: true,
bookingId: true,
} satisfies Prisma.BookingReferenceSelect;
export class BookingReferenceRepository {
static async findDailyVideoReferenceByRoomName({ roomName }: { roomName: string }) {
return prisma.bookingReference.findFirst({
where: {
type: "daily_video",
uid: roomName,
meetingId: roomName,
bookingId: { not: null },
deleted: null,
},
select: bookingReferenceSelect,
});
}
/**
* If rescheduling a booking with new references from the EventManager. Delete the previous references and replace them with new ones
*/
static async replaceBookingReferences({
bookingId,
newReferencesToCreate,
}: {
bookingId: number;
newReferencesToCreate: PartialReference[];
}) {
const newReferenceTypes = newReferencesToCreate.map((reference) => reference.type);
await prisma.bookingReference.updateMany({
where: {
bookingId,
type: {
in: newReferenceTypes,
},
},
data: {
deleted: true,
},
});
await prisma.bookingReference.createMany({
data: newReferencesToCreate.map((reference) => {
return { ...reference, bookingId };
}),
});
}
}
@@ -0,0 +1,104 @@
import type { BookingReportReason, BookingReportStatus } from "@calcom/prisma/enums";
export interface CreateBookingReportInput {
bookingUid: string;
bookerEmail: string;
reportedById: number;
reason: BookingReportReason;
description?: string;
cancelled: boolean;
organizationId?: number | null;
}
export interface BookingReportSummary {
id: string;
reportedById: number | null;
reason: BookingReportReason;
description: string | null;
createdAt: Date;
}
export interface ListBookingReportsFilters {
reason?: BookingReportReason[];
cancelled?: boolean;
hasWatchlist?: boolean;
status?: BookingReportStatus[];
}
export interface BookingReportWithDetails {
id: string;
bookingUid: string;
bookerEmail: string;
reportedById: number | null;
reason: BookingReportReason;
description: string | null;
cancelled: boolean;
createdAt: Date;
status: BookingReportStatus;
watchlistId: string | null;
reporter: {
id: number;
email: string;
name: string | null;
} | null;
booking: {
id: number;
uid: string;
title: string | null;
startTime: Date;
endTime: Date;
};
watchlist: {
id: string;
type: string;
value: string;
action: string;
description: string | null;
} | null;
organization: {
id: number;
name: string;
slug: string | null;
} | null;
}
export interface IBookingReportRepository {
createReport(input: CreateBookingReportInput): Promise<{ id: string }>;
findAllReportedBookings(params: {
organizationId?: number;
skip?: number;
take?: number;
searchTerm?: string;
filters?: ListBookingReportsFilters;
}): Promise<{
rows: BookingReportWithDetails[];
meta: { totalRowCount: number };
}>;
findReportsByIds(params: {
reportIds: string[];
organizationId?: number;
}): Promise<BookingReportWithDetails[]>;
linkWatchlistToReport(params: { reportId: string; watchlistId: string }): Promise<void>;
updateReportStatus(params: {
reportId: string;
status: BookingReportStatus;
organizationId?: number;
}): Promise<void>;
bulkUpdateReportStatus(params: {
reportIds: string[];
status: BookingReportStatus;
organizationId?: number;
}): Promise<{ updated: number }>;
bulkLinkWatchlistWithStatus(params: {
links: Array<{ reportId: string; watchlistId: string }>;
status: BookingReportStatus;
}): Promise<void>;
countPendingReports(params: { organizationId: number }): Promise<number>;
}
@@ -0,0 +1,208 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { PrismaClient } from "@calcom/prisma";
import { BookingReportReason } from "@calcom/prisma/enums";
import type { CreateBookingReportInput } from "./IBookingReportRepository";
import { PrismaBookingReportRepository } from "./PrismaBookingReportRepository";
vi.mock("@sentry/nextjs", () => ({
captureException: vi.fn(),
}));
describe("PrismaBookingReportRepository", () => {
let repository: PrismaBookingReportRepository;
const mockPrisma = {
bookingReport: {
create: vi.fn(),
findUnique: vi.fn(),
findMany: vi.fn(),
findFirst: vi.fn(),
updateMany: vi.fn(),
count: vi.fn(),
},
} as unknown as PrismaClient;
beforeEach(() => {
vi.clearAllMocks();
repository = new PrismaBookingReportRepository(mockPrisma);
});
describe("createReport", () => {
it("should create a booking report with all fields", async () => {
const input: CreateBookingReportInput = {
bookingUid: "test-booking-uid-1",
bookerEmail: "[email protected]",
reportedById: 1,
reason: BookingReportReason.SPAM,
description: "This is spam",
cancelled: true,
organizationId: 10,
};
const mockCreatedReport = { id: "report-123" };
mockPrisma.bookingReport.create.mockResolvedValue(mockCreatedReport);
const result = await repository.createReport(input);
expect(result).toEqual({ id: "report-123" });
expect(mockPrisma.bookingReport.create).toHaveBeenCalledWith({
data: {
bookingUid: "test-booking-uid-1",
bookerEmail: "[email protected]",
reportedById: 1,
reason: BookingReportReason.SPAM,
description: "This is spam",
cancelled: true,
organizationId: 10,
},
select: { id: true },
});
});
it("should create a booking report without optional fields", async () => {
const input: CreateBookingReportInput = {
bookingUid: "test-booking-uid-2",
bookerEmail: "[email protected]",
reportedById: 2,
reason: BookingReportReason.DONT_KNOW_PERSON,
cancelled: false,
};
const mockCreatedReport = { id: "report-456" };
mockPrisma.bookingReport.create.mockResolvedValue(mockCreatedReport);
const result = await repository.createReport(input);
expect(result).toEqual({ id: "report-456" });
expect(mockPrisma.bookingReport.create).toHaveBeenCalledWith({
data: {
bookingUid: "test-booking-uid-2",
bookerEmail: "[email protected]",
reportedById: 2,
reason: BookingReportReason.DONT_KNOW_PERSON,
description: undefined,
cancelled: false,
organizationId: undefined,
},
select: { id: true },
});
});
});
describe("findAllReportedBookings", () => {
it("should find all reported bookings with pagination", async () => {
const mockReports = [
{
id: "report-1",
bookingUid: "booking-1",
bookerEmail: "[email protected]",
reportedById: 1,
reason: BookingReportReason.SPAM,
description: "Spam",
cancelled: false,
createdAt: new Date("2025-01-01T10:00:00Z"),
status: "PENDING",
watchlistId: null,
reportedBy: null,
booking: {
id: 1,
uid: "booking-1",
title: "Test Booking",
startTime: new Date(),
endTime: new Date(),
},
watchlist: null,
},
{
id: "report-2",
bookingUid: "booking-2",
bookerEmail: "[email protected]",
reportedById: 2,
reason: BookingReportReason.DONT_KNOW_PERSON,
description: null,
cancelled: false,
createdAt: new Date("2025-01-01T11:00:00Z"),
status: "PENDING",
watchlistId: null,
reportedBy: null,
booking: {
id: 2,
uid: "booking-2",
title: "Test Booking 2",
startTime: new Date(),
endTime: new Date(),
},
watchlist: null,
},
];
mockPrisma.bookingReport.findMany.mockResolvedValue(mockReports);
mockPrisma.bookingReport.count.mockResolvedValue(2);
const result = await repository.findAllReportedBookings({ skip: 0, take: 10 });
expect(result).toEqual({
rows: mockReports.map((r) => ({ ...r, reporter: r.reportedBy })),
meta: { totalRowCount: 2 },
});
expect(mockPrisma.bookingReport.findMany).toHaveBeenCalled();
expect(mockPrisma.bookingReport.count).toHaveBeenCalled();
});
});
describe("updateReportStatus", () => {
it("should update report status with organizationId", async () => {
mockPrisma.bookingReport.updateMany.mockResolvedValue({ count: 1 });
await repository.updateReportStatus({
reportId: "report-123",
status: "BLOCKED",
organizationId: 100,
});
expect(mockPrisma.bookingReport.updateMany).toHaveBeenCalledWith({
where: {
id: "report-123",
organizationId: 100,
},
data: { status: "BLOCKED" },
});
});
it("should update report status without organizationId", async () => {
mockPrisma.bookingReport.updateMany.mockResolvedValue({ count: 1 });
await repository.updateReportStatus({
reportId: "report-456",
status: "DISMISSED",
});
expect(mockPrisma.bookingReport.updateMany).toHaveBeenCalledWith({
where: {
id: "report-456",
},
data: { status: "DISMISSED" },
});
});
it("should update report status to PENDING", async () => {
mockPrisma.bookingReport.updateMany.mockResolvedValue({ count: 1 });
await repository.updateReportStatus({
reportId: "report-789",
status: "PENDING",
organizationId: 200,
});
expect(mockPrisma.bookingReport.updateMany).toHaveBeenCalledWith({
where: {
id: "report-789",
organizationId: 200,
},
data: { status: "PENDING" },
});
});
});
});
@@ -0,0 +1,286 @@
import type { PrismaClient } from "@calcom/prisma";
import type { BookingReportStatus } from "@calcom/prisma/enums";
import type { Prisma } from "@calcom/prisma/generated/prisma/client";
import type {
IBookingReportRepository,
CreateBookingReportInput,
BookingReportWithDetails,
ListBookingReportsFilters,
} from "./IBookingReportRepository";
export class PrismaBookingReportRepository implements IBookingReportRepository {
constructor(private readonly prismaClient: PrismaClient) {}
async createReport(input: CreateBookingReportInput): Promise<{ id: string }> {
const report = await this.prismaClient.bookingReport.create({
data: {
bookingUid: input.bookingUid,
bookerEmail: input.bookerEmail,
reportedById: input.reportedById,
reason: input.reason,
description: input.description,
cancelled: input.cancelled,
organizationId: input.organizationId,
},
select: { id: true },
});
return report;
}
async findAllReportedBookings(params: {
organizationId?: number;
skip?: number;
take?: number;
searchTerm?: string;
filters?: ListBookingReportsFilters;
}): Promise<{
rows: BookingReportWithDetails[];
meta: { totalRowCount: number };
}> {
const where: Prisma.BookingReportWhereInput = {};
if (params.organizationId) {
where.organizationId = params.organizationId;
}
if (params.searchTerm) {
where.OR = [
{ bookerEmail: { contains: params.searchTerm, mode: "insensitive" } },
{
reportedBy: {
email: { contains: params.searchTerm, mode: "insensitive" },
},
},
];
}
if (params.filters?.hasWatchlist !== undefined) {
where.watchlistId = params.filters.hasWatchlist ? { not: null } : null;
}
if (params.filters?.reason && params.filters.reason.length > 0) {
where.reason = { in: params.filters.reason };
}
if (params.filters?.cancelled !== undefined) {
where.cancelled = params.filters.cancelled;
}
if (params.filters?.status && params.filters.status.length > 0) {
where.status = { in: params.filters.status };
}
const [reports, totalCount] = await Promise.all([
this.prismaClient.bookingReport.findMany({
where,
skip: params.skip,
take: params.take,
select: {
id: true,
bookingUid: true,
bookerEmail: true,
reportedById: true,
reason: true,
description: true,
cancelled: true,
createdAt: true,
status: true,
watchlistId: true,
organizationId: true,
reportedBy: {
select: {
id: true,
email: true,
name: true,
},
},
booking: {
select: {
id: true,
uid: true,
title: true,
startTime: true,
endTime: true,
},
},
watchlist: {
select: {
id: true,
type: true,
value: true,
action: true,
description: true,
},
},
organization: {
select: {
id: true,
name: true,
slug: true,
},
},
},
orderBy: { createdAt: "desc" },
}),
this.prismaClient.bookingReport.count({ where }),
]);
const rows = reports.map((report) => ({
...report,
reporter: report.reportedBy,
}));
return {
rows,
meta: { totalRowCount: totalCount },
};
}
async findReportsByIds(params: {
reportIds: string[];
organizationId?: number;
}): Promise<BookingReportWithDetails[]> {
const where: Prisma.BookingReportWhereInput = {
id: { in: params.reportIds },
};
if (params.organizationId) {
where.organizationId = params.organizationId;
}
const reports = await this.prismaClient.bookingReport.findMany({
where,
select: {
id: true,
bookingUid: true,
bookerEmail: true,
reportedById: true,
reason: true,
description: true,
cancelled: true,
createdAt: true,
status: true,
watchlistId: true,
organizationId: true,
reportedBy: {
select: {
id: true,
email: true,
name: true,
},
},
booking: {
select: {
id: true,
uid: true,
title: true,
startTime: true,
endTime: true,
},
},
watchlist: {
select: {
id: true,
type: true,
value: true,
action: true,
description: true,
},
},
organization: {
select: {
id: true,
name: true,
slug: true,
},
},
},
});
return reports.map((report) => ({
...report,
reporter: report.reportedBy,
}));
}
async linkWatchlistToReport(params: { reportId: string; watchlistId: string }): Promise<void> {
await this.prismaClient.bookingReport.update({
where: { id: params.reportId },
data: { watchlistId: params.watchlistId },
});
}
async updateReportStatus(params: {
reportId: string;
status: BookingReportStatus;
organizationId?: number;
}): Promise<void> {
const where: Prisma.BookingReportWhereInput = {
id: params.reportId,
};
if (params.organizationId) {
where.organizationId = params.organizationId;
}
await this.prismaClient.bookingReport.updateMany({
where,
data: { status: params.status },
});
}
async bulkUpdateReportStatus(params: {
reportIds: string[];
status: BookingReportStatus;
organizationId?: number;
}): Promise<{ updated: number }> {
const where: Prisma.BookingReportWhereInput = {
id: { in: params.reportIds },
};
if (params.organizationId !== undefined) {
where.organizationId = params.organizationId;
}
const result = await this.prismaClient.bookingReport.updateMany({
where,
data: { status: params.status },
});
return { updated: result.count };
}
async bulkLinkWatchlistWithStatus(params: {
links: Array<{ reportId: string; watchlistId: string }>;
status: BookingReportStatus;
}): Promise<void> {
if (params.links.length === 0) return;
const groupedByWatchlist = new Map<string, string[]>();
for (const link of params.links) {
const reportIds = groupedByWatchlist.get(link.watchlistId) || [];
reportIds.push(link.reportId);
groupedByWatchlist.set(link.watchlistId, reportIds);
}
await Promise.all(
Array.from(groupedByWatchlist.entries()).map(([watchlistId, reportIds]) =>
this.prismaClient.bookingReport.updateMany({
where: { id: { in: reportIds } },
data: { watchlistId, status: params.status },
})
)
);
}
async countPendingReports(params: { organizationId: number }): Promise<number> {
return this.prismaClient.bookingReport.count({
where: {
organizationId: params.organizationId,
status: "PENDING",
watchlistId: null,
},
});
}
}
@@ -1,13 +1,13 @@
import { isValidPhoneNumber } from "libphonenumber-js/max";
import { v4 as uuidv4 } from "uuid";
import { PrismaApiKeyRepository } from "@calcom/features/ee/api-keys/repositories/PrismaApiKeyRepository";
import { replaceEventTypePlaceholders } from "@calcom/features/ee/workflows/components/agent-configuration/utils/promptUtils";
import { EventTypeRepository } from "@calcom/features/eventtypes/repositories/eventTypeRepository";
import { RETELL_AI_TEST_MODE, RETELL_AI_TEST_EVENT_TYPE_MAP } from "@calcom/lib/constants";
import { timeZoneSchema } from "@calcom/lib/dayjs/timeZone.schema";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { PrismaApiKeyRepository } from "@calcom/lib/server/repository/PrismaApiKeyRepository";
import prisma from "@calcom/prisma";
import type {
@@ -0,0 +1,25 @@
import type { PrismaClient as PrismaClientWithExtensions } from "@calcom/prisma";
import type { PrismaClient as PrismaClientWithoutExtensions } from "@calcom/prisma/client";
import type { IDeploymentRepository } from "./IDeploymentRepository";
export class DeploymentRepository implements IDeploymentRepository {
constructor(private prisma: PrismaClientWithoutExtensions | PrismaClientWithExtensions) {}
async getLicenseKeyWithId(id: number): Promise<string | null> {
// This repository is special as it is used within prisma extensions
const deployment = await (this.prisma as PrismaClientWithoutExtensions).deployment.findUnique({
where: { id },
select: { licenseKey: true },
});
return deployment?.licenseKey || null;
}
async getSignatureToken(id: number): Promise<string | null> {
const deployment = await (this.prisma as PrismaClientWithoutExtensions).deployment.findUnique({
where: { id },
select: { signatureTokenEncrypted: true },
});
return deployment?.signatureTokenEncrypted || null;
}
}
@@ -0,0 +1,4 @@
export interface IDeploymentRepository {
getLicenseKeyWithId(id: number): Promise<string | null>;
getSignatureToken(id: number): Promise<string | null>;
}
@@ -1,5 +1,5 @@
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { PrismaSelectedSlotRepository } from "@calcom/lib/server/repository/PrismaSelectedSlotRepository";
import { PrismaSelectedSlotRepository } from "@calcom/features/selectedSlots/repositories/PrismaSelectedSlotRepository";
import { createModule } from "../di";
@@ -1,9 +1,11 @@
import { createContainer } from "@evyweb/ioctopus";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { PrismaBookingReportRepository } from "@calcom/features/bookingReport/repositories/PrismaBookingReportRepository";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
import { moduleLoader as loggerModuleLoader } from "@calcom/features/di/shared/services/logger.service";
import { taskerServiceModule } from "@calcom/features/di/shared/services/tasker.service";
import { SHARED_TOKENS } from "@calcom/features/di/shared/shared.tokens";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import {
createWatchlistFeature,
@@ -11,6 +13,7 @@ import {
} from "@calcom/features/watchlist/lib/facade/WatchlistFeature";
import type { IGlobalWatchlistRepository } from "@calcom/features/watchlist/lib/interface/IWatchlistRepositories";
import type { IOrganizationWatchlistRepository } from "@calcom/features/watchlist/lib/interface/IWatchlistRepositories";
import { WatchlistRepository } from "@calcom/features/watchlist/lib/repository/WatchlistRepository";
import { AdminWatchlistOperationsService } from "@calcom/features/watchlist/lib/service/AdminWatchlistOperationsService";
import { AdminWatchlistQueryService } from "@calcom/features/watchlist/lib/service/AdminWatchlistQueryService";
import type { GlobalBlockingService } from "@calcom/features/watchlist/lib/service/GlobalBlockingService";
@@ -19,10 +22,7 @@ import { OrganizationWatchlistOperationsService } from "@calcom/features/watchli
import { OrganizationWatchlistQueryService } from "@calcom/features/watchlist/lib/service/OrganizationWatchlistQueryService";
import type { WatchlistAuditService } from "@calcom/features/watchlist/lib/service/WatchlistAuditService";
import type { WatchlistService } from "@calcom/features/watchlist/lib/service/WatchlistService";
import { PrismaBookingReportRepository } from "@calcom/lib/server/repository/bookingReport";
import { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
import { prisma } from "@calcom/prisma";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
import { WATCHLIST_DI_TOKENS } from "../Watchlist.tokens";
import { watchlistModule } from "../modules/Watchlist.module";
@@ -0,0 +1,87 @@
import { v4 as uuidv4 } from "uuid";
import type { PrismaClient } from "@calcom/prisma";
import { generateUniqueAPIKey as generateHashedApiKey } from "../lib/apiKeys";
export class PrismaApiKeyRepository {
constructor(private prismaClient: PrismaClient) {}
static async withGlobalPrisma() {
return new PrismaApiKeyRepository((await import("@calcom/prisma")).prisma);
}
async findByHashedKey(hashedKey: string) {
return this.prismaClient.apiKey.findUnique({
where: { hashedKey },
select: {
id: true,
hashedKey: true,
userId: true,
expiresAt: true,
user: {
select: {
role: true,
locked: true,
email: true,
},
},
},
});
}
async findApiKeysFromUserId({ userId }: { userId: number }) {
const apiKeys = await this.prismaClient.apiKey.findMany({
where: {
userId,
OR: [
{
NOT: {
appId: "zapier",
},
},
{
appId: null,
},
],
},
orderBy: { createdAt: "desc" },
});
return apiKeys.filter((apiKey) => {
if (apiKey.note?.startsWith("Cal.ai Phone API Key")) {
return false;
}
return true;
});
}
async createApiKey({
userId,
teamId,
note,
expiresAt,
}: {
userId: number;
teamId?: number;
note?: string;
expiresAt?: Date | null;
}) {
const [hashedApiKey, apiKey] = generateHashedApiKey();
await this.prismaClient.apiKey.create({
data: {
id: uuidv4(),
userId,
teamId,
expiresAt,
hashedKey: hashedApiKey,
note: note,
},
});
const apiKeyPrefix = process.env.API_KEY_PREFIX ?? "cal_";
const prefixedApiKey = `${apiKeyPrefix}${apiKey}`;
return prefixedApiKey;
}
}
@@ -0,0 +1,47 @@
import type { PrismaApiKeyRepository } from "../repositories/PrismaApiKeyRepository";
type Deps = {
apiKeyRepo: PrismaApiKeyRepository;
};
interface VerifyKeyResult {
valid: boolean;
error?: string;
userId?: number;
user?: {
role: string;
locked: boolean;
email: string;
};
}
export class ApiKeyService {
constructor(private readonly deps: Deps) {}
async verifyKeyByHashedKey(hashedKey: string): Promise<VerifyKeyResult> {
const apiKey = await this.deps.apiKeyRepo.findByHashedKey(hashedKey);
if (!apiKey) {
return { valid: false, error: "Your API key is not valid." };
}
if (apiKey.expiresAt && this.isExpired(apiKey.expiresAt)) {
return { valid: false, error: "This API key is expired." };
}
if (!apiKey.userId || !apiKey.user) {
return { valid: false, error: "No user found for this API key." };
}
return {
valid: true,
userId: apiKey.userId,
user: apiKey.user,
};
}
private isExpired(expiresAt: Date): boolean {
const now = new Date();
return now.setHours(0, 0, 0, 0) > expiresAt.setHours(0, 0, 0, 0);
}
}
@@ -4,9 +4,9 @@ import {
getDeploymentKey,
getDeploymentSignatureToken,
} from "@calcom/features/ee/deployment/lib/getDeploymentKey";
import type { IDeploymentRepository } from "@calcom/features/ee/deployment/repositories/IDeploymentRepository";
import { CALCOM_PRIVATE_API_ROUTE } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import type { IDeploymentRepository } from "@calcom/lib/server/repository/deployment.interface";
import { generateNonce, createSignature } from "./private-api-utils";
@@ -1,6 +1,6 @@
import type { IDeploymentRepository } from "@calcom/features/ee/deployment/repositories/IDeploymentRepository";
import { symmetricDecrypt } from "@calcom/lib/crypto";
import logger from "@calcom/lib/logger";
import type { IDeploymentRepository } from "@calcom/lib/server/repository/deployment.interface";
const log = logger.getSubLogger({ prefix: ["getDeploymentKey"] });
@@ -0,0 +1,25 @@
import type { PrismaClient as PrismaClientWithExtensions } from "@calcom/prisma";
import type { PrismaClient as PrismaClientWithoutExtensions } from "@calcom/prisma/client";
import type { IDeploymentRepository } from "./IDeploymentRepository";
export class DeploymentRepository implements IDeploymentRepository {
constructor(private prisma: PrismaClientWithoutExtensions | PrismaClientWithExtensions) {}
async getLicenseKeyWithId(id: number): Promise<string | null> {
// This repository is special as it is used within prisma extensions
const deployment = await (this.prisma as PrismaClientWithoutExtensions).deployment.findUnique({
where: { id },
select: { licenseKey: true },
});
return deployment?.licenseKey || null;
}
async getSignatureToken(id: number): Promise<string | null> {
const deployment = await (this.prisma as PrismaClientWithoutExtensions).deployment.findUnique({
where: { id },
select: { signatureTokenEncrypted: true },
});
return deployment?.signatureTokenEncrypted || null;
}
}
@@ -0,0 +1,4 @@
export interface IDeploymentRepository {
getLicenseKeyWithId(id: number): Promise<string | null>;
getSignatureToken(id: number): Promise<string | null>;
}
@@ -1,4 +1,5 @@
import { LicenseKeySingleton } from "@calcom/ee/common/server/LicenseKeyService";
import { DeploymentRepository } from "@calcom/features/ee/deployment/repositories/DeploymentRepository";
import { getOrganizationRepository } from "@calcom/features/ee/organizations/di/OrganizationRepository.container";
import { findUserToBeOrgOwner } from "@calcom/features/ee/organizations/lib/server/orgCreationUtils";
import { OrganizationOnboardingRepository } from "@calcom/features/organizations/repositories/OrganizationOnboardingRepository";
@@ -6,7 +7,6 @@ import { IS_SELF_HOSTED } from "@calcom/lib/constants";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import { DeploymentRepository } from "@calcom/lib/server/repository/deployment";
import { prisma } from "@calcom/prisma";
import type { Team, User } from "@calcom/prisma/client";
import { BillingPeriod } from "@calcom/prisma/enums";
@@ -5,7 +5,7 @@ import { describe, it, expect, beforeEach, vi } from "vitest";
import { OrganizationRepository } from "@calcom/features/ee/organizations/repositories/OrganizationRepository";
import type { Prisma } from "@calcom/prisma/client";
vi.mock("@calcom/lib/server/repository/teamUtils", () => ({
vi.mock("@calcom/features/ee/teams/lib/getParsedTeam", () => ({
getParsedTeam: <T>(org: T) => org,
}));
@@ -1,11 +1,11 @@
import type { z } from "zod";
import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";
import { getParsedTeam } from "@calcom/features/ee/teams/lib/getParsedTeam";
import { createAProfileForAnExistingUser } from "@calcom/features/profile/lib/createAProfileForAnExistingUser";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getParsedTeam } from "@calcom/lib/server/repository/teamUtils";
import type { PrismaClient } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import type { CreationSource } from "@calcom/prisma/enums";
@@ -1,19 +1,19 @@
import { metadata as GoogleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
import { MeetLocationType } from "@calcom/app-store/locations";
import getICalUID from "@calcom/emails/lib/getICalUID";
import { BookingReferenceRepository } from "@calcom/features/bookingReference/repositories/BookingReferenceRepository";
import EventManager from "@calcom/features/bookings/lib/EventManager";
import type { EventManagerInitParams } from "@calcom/features/bookings/lib/EventManager";
import { getAllCredentialsIncludeServiceAccountKey } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import type { EventType } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import { getVideoCallDetails } from "@calcom/features/bookings/lib/handleNewBooking/getVideoCallDetails";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import EventManager from "@calcom/features/bookings/lib/EventManager";
import type { EventManagerInitParams } from "@calcom/features/bookings/lib/EventManager";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { BookingReferenceRepository } from "@calcom/lib/server/repository/bookingReference";
import { prisma } from "@calcom/prisma";
import type { DestinationCalendar } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
import type { CalendarEvent, AdditionalInformation } from "@calcom/types/Calendar";
import getICalUID from "@calcom/emails/lib/getICalUID";
type InitParams = {
user: {
@@ -165,9 +165,9 @@ export const handleRescheduleEventManager = async ({
const calendarResult = results.find((result) => result.type.includes("_calendar"));
if (changedOrganizer) {
const providerICalUID = evt.iCalUID = Array.isArray(calendarResult?.createdEvent)
const providerICalUID = (evt.iCalUID = Array.isArray(calendarResult?.createdEvent)
? calendarResult?.createdEvent[0]?.iCalUID
: calendarResult?.createdEvent?.iCalUID;
: calendarResult?.createdEvent?.iCalUID);
evt.iCalUID = providerICalUID || getICalUID({});
} else {
evt.iCalUID = Array.isArray(calendarResult?.updatedEvent)
@@ -0,0 +1,19 @@
import type { Team } from "@calcom/prisma/client";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
export const getParsedTeam = <T extends { metadata: Team["metadata"] }>(team: T) => {
const metadata = teamMetadataSchema.parse(team.metadata);
const requestedSlug = metadata?.requestedSlug ?? null;
const { metadata: _1, ...rest } = team;
return {
...rest,
requestedSlug,
metadata: {
...metadata,
/**
* @deprecated New orgs that are being created won't have requestedSlug set as the organizations are created after payment and thus slug is always available
*/
requestedSlug,
},
};
};
@@ -1,8 +1,8 @@
import type { z } from "zod";
import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";
import { getParsedTeam } from "@calcom/features/ee/teams/lib/getParsedTeam";
import logger from "@calcom/lib/logger";
import { getParsedTeam } from "@calcom/lib/server/repository/teamUtils";
import type { PrismaClient } from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
@@ -0,0 +1,22 @@
import type { Prisma, PrismaClient } from "@calcom/prisma/client";
export class WorkflowStepRepository {
constructor(private prismaClient: PrismaClient) {}
async deleteById(id: number) {
return await this.prismaClient.workflowStep.delete({
where: { id },
});
}
async createWorkflowStep(data: Prisma.WorkflowStepUncheckedCreateInput) {
return await this.prismaClient.workflowStep.create({ data });
}
async updateWorkflowStep(id: number, data: Prisma.WorkflowStepUncheckedUpdateInput) {
return await this.prismaClient.workflowStep.update({
where: { id },
data,
});
}
}
@@ -0,0 +1,68 @@
import { prisma } from "@calcom/prisma";
import type { EventTypeTranslation } from "@calcom/prisma/client";
import { EventTypeAutoTranslatedField } from "@calcom/prisma/enums";
export type CreateEventTypeTranslation = Omit<
EventTypeTranslation,
| "uid"
| "createdAt"
| "createdBy"
| "updatedAt"
| "updatedBy"
| "eventType"
| "field"
| "creator"
| "updater"
> & { userId: number };
export class EventTypeTranslationRepository {
static async upsertManyTitleTranslations(translations: Array<CreateEventTypeTranslation>) {
return await Promise.all(
translations.map(({ userId, ...translation }) => {
return prisma.eventTypeTranslation.upsert({
where: {
eventTypeId_field_targetLocale: {
eventTypeId: translation.eventTypeId,
field: EventTypeAutoTranslatedField.TITLE,
targetLocale: translation.targetLocale,
},
},
update: {
translatedText: translation.translatedText,
updatedBy: userId,
},
create: {
...translation,
field: EventTypeAutoTranslatedField.TITLE,
createdBy: userId,
},
});
})
);
}
static async upsertManyDescriptionTranslations(translations: Array<CreateEventTypeTranslation>) {
return await Promise.all(
translations.map(({ userId, ...translation }) => {
return prisma.eventTypeTranslation.upsert({
where: {
eventTypeId_field_targetLocale: {
eventTypeId: translation.eventTypeId,
field: EventTypeAutoTranslatedField.DESCRIPTION,
targetLocale: translation.targetLocale,
},
},
update: {
translatedText: translation.translatedText,
updatedBy: userId,
},
create: {
...translation,
field: EventTypeAutoTranslatedField.DESCRIPTION,
createdBy: userId,
},
});
})
);
}
}
@@ -1,7 +1,7 @@
import { vi, describe, it, expect, beforeEach } from "vitest";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { isOrganisationAdmin, isOrganisationOwner } from "@calcom/lib/server/queries/organisations";
import { isOrganisationAdmin, isOrganisationOwner } from "@calcom/features/pbac/utils/isOrganisationAdmin";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
@@ -24,7 +24,7 @@ vi.mock("@calcom/prisma", () => ({
},
},
}));
vi.mock("@calcom/lib/server/queries/organisations", () => ({
vi.mock("@calcom/features/pbac/utils/isOrganisationAdmin", () => ({
isOrganisationAdmin: vi.fn(),
isOrganisationOwner: vi.fn(),
}));
@@ -1,5 +1,5 @@
import { isTeamOwner } from "@calcom/features/ee/teams/lib/queries";
import { isOrganisationAdmin, isOrganisationOwner } from "@calcom/lib/server/queries/organisations";
import { isOrganisationAdmin, isOrganisationOwner } from "@calcom/features/pbac/utils/isOrganisationAdmin";
import { prisma } from "@calcom/prisma";
import type { Membership } from "@calcom/prisma/client";
import { MembershipRole } from "@calcom/prisma/enums";
@@ -0,0 +1,37 @@
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
// export type OrganisationWithMembers = Awaited<ReturnType<typeof getOrganizationMembers>>;
// also returns team
export async function isOrganisationAdmin(userId: number, orgId: number) {
return (
(await prisma.membership.findFirst({
where: {
userId,
teamId: orgId,
OR: [{ role: MembershipRole.ADMIN }, { role: MembershipRole.OWNER }],
},
})) || false
);
}
export async function isOrganisationOwner(userId: number, orgId: number) {
return !!(await prisma.membership.findFirst({
where: {
userId,
teamId: orgId,
role: MembershipRole.OWNER,
},
}));
}
export async function isOrganisationMember(userId: number, orgId: number) {
return !!(await prisma.membership.findUnique({
where: {
userId_teamId: {
userId,
teamId: orgId,
},
},
}));
}
@@ -2,11 +2,12 @@ import prismock from "../../../../tests/libs/__mocks__/prisma";
import { describe, it, expect, beforeEach, vi } from "vitest";
import { ProfileRepository, LookupTarget } from "./ProfileRepository";
import { MembershipRole } from "@calcom/prisma/enums";
import type { Prisma } from "@calcom/prisma/client";
import { MembershipRole } from "@calcom/prisma/enums";
vi.mock("@calcom/lib/server/repository/teamUtils", () => ({
import { ProfileRepository, LookupTarget } from "./ProfileRepository";
vi.mock("@calcom/features/ee/teams/lib/getParsedTeam", () => ({
getParsedTeam: <T>(org: T) => org,
}));
@@ -478,4 +479,3 @@ describe("ProfileRepository.findByUpIdWithAuth - IDOR Security Fix", () => {
});
});
});
@@ -2,10 +2,10 @@ import { v4 as uuidv4 } from "uuid";
import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";
import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";
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 { getParsedTeam } from "@calcom/lib/server/repository/teamUtils";
import prisma from "@calcom/prisma";
import type { User as PrismaUser } from "@calcom/prisma/client";
import type { Prisma } from "@calcom/prisma/client";
@@ -0,0 +1,24 @@
import type { SelectedSlot } from "./dto/SelectedSlot";
export type TimeSlot = {
utcStartIso: string;
utcEndIso: string;
};
export interface ISelectedSlotRepository {
findReservedByOthers(args: {
slot: TimeSlot;
eventTypeId: number;
uid: string;
}): Promise<SelectedSlot | null>;
findManyReservedByOthers(
slots: TimeSlot[],
eventTypeId: number,
uid: string
): Promise<Array<Pick<SelectedSlot, "slotUtcEndDate" | "slotUtcStartDate">>>;
findManyUnexpiredSlots(args: {
userIds: number[];
currentTimeInUtc: string;
}): Promise<Array<Omit<SelectedSlot, "releaseAt">>>;
deleteManyExpiredSlots(args: { eventTypeId: number; currentTimeInUtc: string }): Promise<{ count: number }>;
}
@@ -0,0 +1,92 @@
import type { PrismaClient } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import type { ISelectedSlotRepository } from "./ISelectedSlotRepository";
import type { TimeSlot } from "./ISelectedSlotRepository";
export class PrismaSelectedSlotRepository implements ISelectedSlotRepository {
constructor(private prismaClient: PrismaClient) {}
private async findFirst({ where }: { where: Prisma.SelectedSlotsWhereInput }) {
return await this.prismaClient.selectedSlots.findFirst({
where,
});
}
async findReservedByOthers({
slot,
eventTypeId,
uid,
}: {
slot: TimeSlot;
eventTypeId: number;
uid: string;
}) {
return await this.findFirst({
where: {
slotUtcStartDate: slot.utcStartIso,
slotUtcEndDate: slot.utcEndIso,
eventTypeId,
uid: { not: uid },
releaseAt: { gt: new Date() },
},
});
}
async findManyReservedByOthers(slots: TimeSlot[], eventTypeId: number, uid: string) {
return await this.prismaClient.selectedSlots.findMany({
where: {
OR: slots.map((slot) => ({
slotUtcStartDate: slot.utcStartIso,
slotUtcEndDate: slot.utcEndIso,
eventTypeId,
uid: { not: uid },
releaseAt: { gt: new Date() },
})),
},
select: {
slotUtcStartDate: true,
slotUtcEndDate: true,
},
});
}
async findManyUnexpiredSlots({
userIds,
currentTimeInUtc,
}: {
userIds: number[];
currentTimeInUtc: string;
}) {
return this.prismaClient.selectedSlots.findMany({
where: {
userId: { in: userIds },
releaseAt: { gt: currentTimeInUtc },
},
select: {
id: true,
slotUtcStartDate: true,
slotUtcEndDate: true,
userId: true,
isSeat: true,
eventTypeId: true,
uid: true,
},
});
}
async deleteManyExpiredSlots({
eventTypeId,
currentTimeInUtc,
}: {
eventTypeId: number;
currentTimeInUtc: string;
}) {
return this.prismaClient.selectedSlots.deleteMany({
where: {
eventTypeId: { equals: eventTypeId },
releaseAt: { lt: currentTimeInUtc },
},
});
}
}
@@ -0,0 +1,6 @@
import type { SelectedSlots } from "@calcom/prisma/client";
export type SelectedSlot = Pick<
SelectedSlots,
"id" | "uid" | "eventTypeId" | "slotUtcStartDate" | "slotUtcEndDate" | "releaseAt" | "isSeat"
>;
@@ -1,8 +1,8 @@
import { z } from "zod";
import { EventTypeTranslationRepository } from "@calcom/features/eventTypeTranslation/repositories/EventTypeTranslationRepository";
import { locales as i18nLocales } from "@calcom/lib/i18n";
import logger from "@calcom/lib/logger";
import { EventTypeTranslationRepository } from "@calcom/lib/server/repository/eventTypeTranslation";
import { EventTypeAutoTranslatedField } from "@calcom/prisma/enums";
export const ZTranslateEventDataPayloadSchema = z.object({
@@ -1,13 +1,13 @@
import type { z } from "zod";
import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";
import { getParsedTeam } from "@calcom/features/ee/teams/lib/getParsedTeam";
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
import { buildNonDelegationCredentials } from "@calcom/lib/delegationCredential";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getParsedTeam } from "@calcom/lib/server/repository/teamUtils";
import { withSelectedCalendars } from "@calcom/lib/server/withSelectedCalendars";
import type { PrismaClient } from "@calcom/prisma";
import { availabilityUserSelect } from "@calcom/prisma";
@@ -123,7 +123,7 @@ const userSelect = {
} satisfies Prisma.UserSelect;
export class UserRepository {
constructor(private prismaClient: PrismaClient) { }
constructor(private prismaClient: PrismaClient) {}
async findTeamsByUserId({ userId }: { userId: UserType["id"] }) {
const teamMemberships = await this.prismaClient.membership.findMany({
@@ -236,35 +236,35 @@ export class UserRepository {
// Lookup in profiles because that's where the organization usernames exist
const profiles = orgSlug
? (
await ProfileRepository.findManyByOrgSlugOrRequestedSlug({
orgSlug: orgSlug,
usernames: usernameList,
})
).map((profile) => ({
...profile,
organization: getParsedTeam(profile.organization),
}))
await ProfileRepository.findManyByOrgSlugOrRequestedSlug({
orgSlug: orgSlug,
usernames: usernameList,
})
).map((profile) => ({
...profile,
organization: getParsedTeam(profile.organization),
}))
: null;
const where =
profiles && profiles.length > 0
? {
// Get UserIds from profiles
id: {
in: profiles.map((profile) => profile.user.id),
},
}
// Get UserIds from profiles
id: {
in: profiles.map((profile) => profile.user.id),
},
}
: {
username: {
in: usernameList,
},
...(orgSlug
? {
organization: whereClauseForOrgWithSlugOrRequestedSlug(orgSlug),
}
: {
organization: null,
}),
};
username: {
in: usernameList,
},
...(orgSlug
? {
organization: whereClauseForOrgWithSlugOrRequestedSlug(orgSlug),
}
: {
organization: null,
}),
};
return { where, profiles };
}
@@ -681,27 +681,27 @@ export class UserRepository {
async enrichEntityWithProfile<
T extends
| {
profile: {
id: number;
username: string | null;
organizationId: number | null;
organization?: {
id: number;
name: string;
calVideoLogo?: string | null;
bannerUrl: string | null;
slug: string | null;
metadata: Prisma.JsonValue;
};
};
}
| {
user: {
username: string | null;
id: number;
};
}
| {
profile: {
id: number;
username: string | null;
organizationId: number | null;
organization?: {
id: number;
name: string;
calVideoLogo?: string | null;
bannerUrl: string | null;
slug: string | null;
metadata: Prisma.JsonValue;
};
};
}
| {
user: {
username: string | null;
id: number;
};
}
>(entity: T) {
if ("profile" in entity) {
const { profile, ...entityWithoutProfile } = entity;
@@ -714,11 +714,11 @@ export class UserRepository {
...profileWithoutOrganization,
...(parsedOrg
? {
organization: parsedOrg,
}
organization: parsedOrg,
}
: {
organization: null,
}),
organization: null,
}),
},
};
return ret;
@@ -754,10 +754,10 @@ export class UserRepository {
data: {
movedToProfile: data.movedToProfileId
? {
connect: {
id: data.movedToProfileId,
},
}
connect: {
id: data.movedToProfileId,
},
}
: undefined,
},
});
@@ -803,15 +803,15 @@ export class UserRepository {
locked,
...(organizationIdValue
? {
organizationId: organizationIdValue,
profiles: {
create: {
username,
organizationId: organizationIdValue,
uid: ProfileRepository.generateProfileUid(),
organizationId: organizationIdValue,
profiles: {
create: {
username,
organizationId: organizationIdValue,
uid: ProfileRepository.generateProfileUid(),
},
},
},
}
}
: {}),
...rest,
},
@@ -1014,19 +1014,19 @@ export class UserRepository {
};
}
async findUnlockedUserForSession({ userId }: { userId: number }) {
const user = await this.prismaClient.user.findUnique({
where: {
id: userId,
// Locked users can't login
locked: false,
},
select: {
id: true,
uuid: true,
username: true,
name: true,
email: true,
async findUnlockedUserForSession({ userId }: { userId: number }) {
const user = await this.prismaClient.user.findUnique({
where: {
id: userId,
// Locked users can't login
locked: false,
},
select: {
id: true,
uuid: true,
username: true,
name: true,
email: true,
emailVerified: true,
bio: true,
avatarUrl: true,
@@ -0,0 +1,89 @@
import type { WatchlistType, WatchlistAction, WatchlistSource } from "@calcom/prisma/enums";
export interface WatchlistEntry {
id: string;
type: WatchlistType;
value: string;
action: WatchlistAction;
description: string | null;
organizationId: number | null;
isGlobal: boolean;
source: WatchlistSource;
createdAt?: Date;
lastUpdatedAt?: Date;
}
export interface WatchlistAuditEntry {
id: string;
watchlistId: string | null;
type: WatchlistType;
value: string;
description: string | null;
action: WatchlistAction;
eventType?: string;
changedByUserId: number | null;
changedAt: Date;
}
export interface CreateWatchlistInput {
type: WatchlistType;
value: string;
organizationId: number | null;
action: WatchlistAction;
description?: string;
userId: number;
isGlobal?: boolean;
}
export interface CheckWatchlistInput {
type: WatchlistType;
value: string;
organizationId?: number | null;
isGlobal?: boolean;
}
export interface FindAllEntriesInput {
organizationId?: number | null;
isGlobal?: boolean;
limit: number;
offset: number;
searchTerm?: string;
filters?: {
type?: WatchlistType;
source?: WatchlistSource;
};
}
export interface IWatchlistRepository {
createEntry(params: CreateWatchlistInput): Promise<WatchlistEntry>;
createEntryIfNotExists(params: CreateWatchlistInput): Promise<WatchlistEntry>;
checkExists(params: CheckWatchlistInput): Promise<WatchlistEntry | null>;
findAllEntriesWithLatestAudit(params: FindAllEntriesInput): Promise<{
rows: (WatchlistEntry & {
latestAudit: { changedByUserId: number | null } | null;
})[];
meta: { totalRowCount: number };
}>;
findEntryWithAuditAndReports(id: string): Promise<{
entry:
| (WatchlistEntry & {
bookingReports?: Array<{
booking: {
uid: string;
title: string | null;
};
}>;
})
| null;
auditHistory: WatchlistAuditEntry[];
}>;
findEntriesByIds(ids: string[]): Promise<
Array<{
id: string;
isGlobal: boolean;
organizationId: number | null;
}>
>;
deleteEntry(id: string, userId: number): Promise<void>;
bulkDeleteEntries(params: { ids: string[]; userId: number }): Promise<{ deleted: number }>;
}
@@ -0,0 +1,338 @@
import type { PrismaClient } from "@calcom/prisma";
import { WatchlistAction, WatchlistSource } from "@calcom/prisma/enums";
import type {
IWatchlistRepository,
CreateWatchlistInput,
CheckWatchlistInput,
WatchlistEntry,
FindAllEntriesInput,
WatchlistAuditEntry,
} from "./IWatchlistRepository";
export class WatchlistRepository implements IWatchlistRepository {
constructor(private readonly prismaClient: PrismaClient) {}
async createEntry(params: CreateWatchlistInput): Promise<WatchlistEntry> {
const watchlist = await this.prismaClient.$transaction(async (tx) => {
const created = await tx.watchlist.create({
data: {
type: params.type,
value: params.value,
organizationId: params.organizationId,
action: params.action,
description: params.description,
source: WatchlistSource.MANUAL,
isGlobal: params.isGlobal ?? false,
},
});
await tx.watchlistAudit.create({
data: {
watchlistId: created.id,
type: params.type,
value: params.value,
description: params.description,
action: params.action,
changedByUserId: params.userId,
},
});
return created;
});
return watchlist;
}
async createEntryIfNotExists(params: CreateWatchlistInput): Promise<WatchlistEntry> {
const existing = await this.checkExists({
type: params.type,
value: params.value,
organizationId: params.organizationId,
isGlobal: params.isGlobal,
});
if (existing) {
return existing;
}
return this.createEntry(params);
}
async checkExists(params: CheckWatchlistInput): Promise<WatchlistEntry | null> {
if (!params.isGlobal && !params.organizationId) {
throw new Error("Both isGlobal and organizationId are missing");
}
if (params.isGlobal) {
const entry = await this.prismaClient.watchlist.findFirst({
where: {
type: params.type,
value: params.value,
isGlobal: true,
organizationId: null,
},
});
return entry;
} else if (params.organizationId) {
const entry = await this.prismaClient.watchlist.findUnique({
where: {
type_value_organizationId: {
type: params.type,
value: params.value,
organizationId: params.organizationId,
},
},
});
return entry;
}
return null;
}
async findAllEntriesWithLatestAudit(params: FindAllEntriesInput): Promise<{
rows: (WatchlistEntry & { latestAudit: { changedByUserId: number | null } | null })[];
meta: { totalRowCount: number };
}> {
const where = {
organizationId: params.organizationId,
isGlobal: params.isGlobal,
...(params.searchTerm && {
value: {
contains: params.searchTerm,
mode: "insensitive" as const,
},
}),
...(params.filters?.type && {
type: params.filters.type,
}),
...(params.filters?.source && {
source: params.filters.source,
}),
};
const [entries, totalRowCount] = await Promise.all([
this.prismaClient.watchlist.findMany({
where,
take: params.limit,
skip: params.offset,
orderBy: {
lastUpdatedAt: "desc",
},
select: {
id: true,
type: true,
value: true,
action: true,
description: true,
organizationId: true,
isGlobal: true,
source: true,
lastUpdatedAt: true,
audits: {
take: 1,
orderBy: {
changedAt: "desc",
},
select: {
changedByUserId: true,
},
},
},
}),
this.prismaClient.watchlist.count({ where }),
]);
const rows = entries.map((entry) => ({
...entry,
latestAudit: entry.audits[0] ?? null,
audits: undefined,
}));
return {
rows,
meta: { totalRowCount },
};
}
async findEntryWithAuditAndReports(id: string): Promise<{
entry:
| (WatchlistEntry & {
bookingReports?: Array<{
booking: {
uid: string;
title: string | null;
};
}>;
})
| null;
auditHistory: WatchlistAuditEntry[];
}> {
const entry = await this.prismaClient.watchlist.findUnique({
where: { id },
select: {
id: true,
type: true,
value: true,
action: true,
description: true,
organizationId: true,
isGlobal: true,
source: true,
lastUpdatedAt: true,
bookingReports: {
select: {
booking: {
select: {
uid: true,
title: true,
},
},
},
},
audits: {
select: {
id: true,
watchlistId: true,
type: true,
value: true,
description: true,
action: true,
changedByUserId: true,
changedAt: true,
},
orderBy: {
changedAt: "desc",
},
},
},
});
return {
entry: entry
? {
id: entry.id,
type: entry.type,
value: entry.value,
action: entry.action,
description: entry.description ?? null,
organizationId: entry.organizationId ?? null,
isGlobal: entry.isGlobal,
source: entry.source,
lastUpdatedAt: entry.lastUpdatedAt,
bookingReports: entry.bookingReports,
}
: null,
auditHistory: entry?.audits || [],
};
}
async findEntriesByIds(ids: string[]): Promise<
Array<{
id: string;
isGlobal: boolean;
organizationId: number | null;
}>
> {
return this.prismaClient.watchlist.findMany({
where: { id: { in: ids } },
select: {
id: true,
isGlobal: true,
organizationId: true,
},
});
}
async deleteEntry(id: string, userId: number): Promise<void> {
const existing = await this.prismaClient.watchlist.findUnique({
where: { id },
select: {
id: true,
type: true,
value: true,
description: true,
action: true,
},
});
if (!existing) {
throw new Error("Watchlist entry not found");
}
await this.prismaClient.$transaction(async (tx) => {
await tx.watchlistAudit.create({
data: {
watchlistId: id,
type: existing.type,
value: existing.value,
description: existing.description,
action: existing.action,
changedByUserId: userId,
},
});
await tx.watchlist.delete({
where: { id },
});
});
}
async bulkDeleteEntries(params: { ids: string[]; userId: number }): Promise<{ deleted: number }> {
const entries = await this.prismaClient.watchlist.findMany({
where: { id: { in: params.ids } },
select: {
id: true,
type: true,
value: true,
description: true,
action: true,
},
});
if (entries.length === 0) {
return { deleted: 0 };
}
await this.prismaClient.$transaction(async (tx) => {
await tx.watchlistAudit.createMany({
data: entries.map((entry) => ({
watchlistId: entry.id,
type: entry.type,
value: entry.value,
description: entry.description,
action: entry.action,
changedByUserId: params.userId,
})),
});
await tx.watchlist.deleteMany({
where: { id: { in: entries.map((e) => e.id) } },
});
});
return { deleted: entries.length };
}
async createEntryFromReport(params: {
type: CreateWatchlistInput["type"];
value: string;
organizationId: number | null;
isGlobal: boolean;
userId: number;
description?: string;
}): Promise<{ watchlistEntry: WatchlistEntry; value: string }> {
const watchlistEntry = await this.createEntryIfNotExists({
type: params.type,
value: params.value,
organizationId: params.organizationId,
isGlobal: params.isGlobal,
action: WatchlistAction.BLOCK,
description: params.description,
userId: params.userId,
});
return { watchlistEntry, value: params.value };
}
}
@@ -1,6 +1,6 @@
import type { PrismaBookingReportRepository } from "@calcom/features/bookingReport/repositories/PrismaBookingReportRepository";
import type { WatchlistRepository } from "@calcom/features/watchlist/lib/repository/WatchlistRepository";
import logger from "@calcom/lib/logger";
import type { PrismaBookingReportRepository } from "@calcom/lib/server/repository/bookingReport";
import type { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
import { BookingReportStatus } from "@calcom/prisma/enums";
import { WatchlistErrors } from "../errors/WatchlistErrors";
@@ -1,7 +1,7 @@
import type { ListBookingReportsFilters } from "@calcom/features/bookingReport/repositories/IBookingReportRepository";
import type { PrismaBookingReportRepository } from "@calcom/features/bookingReport/repositories/PrismaBookingReportRepository";
import type { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import type { ListBookingReportsFilters } from "@calcom/lib/server/repository/bookingReport.interface";
import type { PrismaBookingReportRepository } from "@calcom/lib/server/repository/bookingReport";
import type { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
import type { WatchlistRepository } from "@calcom/features/watchlist/lib/repository/WatchlistRepository";
import type { PrismaClient } from "@calcom/prisma";
import type { WatchlistType, WatchlistSource } from "@calcom/prisma/enums";
@@ -1,7 +1,7 @@
import type { PrismaBookingReportRepository } from "@calcom/features/bookingReport/repositories/PrismaBookingReportRepository";
import type { PermissionString } from "@calcom/features/pbac/domain/types/permission-registry";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import type { PrismaBookingReportRepository } from "@calcom/lib/server/repository/bookingReport";
import type { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
import type { WatchlistRepository } from "@calcom/features/watchlist/lib/repository/WatchlistRepository";
import { MembershipRole } from "@calcom/prisma/enums";
import { WatchlistErrors } from "../errors/WatchlistErrors";
@@ -60,7 +60,9 @@ export class OrganizationWatchlistOperationsService extends WatchlistOperationsS
});
if (!hasPermission) {
throw WatchlistErrors.permissionDenied(`You are not authorized to ${permission.split(".")[1]} watchlist entries`);
throw WatchlistErrors.permissionDenied(
`You are not authorized to ${permission.split(".")[1]} watchlist entries`
);
}
}
@@ -1,6 +1,6 @@
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import type { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import type { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
import type { WatchlistRepository } from "@calcom/features/watchlist/lib/repository/WatchlistRepository";
import { MembershipRole, WatchlistType, WatchlistSource } from "@calcom/prisma/enums";
import { WatchlistErrors } from "../errors/WatchlistErrors";
@@ -1,8 +1,8 @@
import type { PrismaBookingReportRepository } from "@calcom/features/bookingReport/repositories/PrismaBookingReportRepository";
import type { WatchlistEntry } from "@calcom/features/watchlist/lib/repository/IWatchlistRepository";
import type { WatchlistRepository } from "@calcom/features/watchlist/lib/repository/WatchlistRepository";
import { domainRegex, emailRegex } from "@calcom/lib/emailSchema";
import logger from "@calcom/lib/logger";
import type { PrismaBookingReportRepository } from "@calcom/lib/server/repository/bookingReport";
import type { WatchlistEntry } from "@calcom/lib/server/repository/watchlist.interface";
import type { WatchlistRepository } from "@calcom/lib/server/repository/watchlist.repository";
import { WatchlistAction, WatchlistType } from "@calcom/prisma/enums";
import { WatchlistErrors } from "../errors/WatchlistErrors";