Files
calendar/packages/lib/builders/CalendarEvent/builder.ts
T
devin-ai-integration[bot]GitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>alex@cal.com <me@alexvanandel.com>
79b6278883 refactor: replace Prisma.validator<Select>() with satisfies syntax (#22270)
* refactor: replace Prisma.validator<Select>() with satisfies syntax

- Convert all Prisma.validator<Prisma.SomeSelect>()({...}) patterns to {...} satisfies Prisma.SomeSelect
- Update import { Prisma } to import type { Prisma } where only used for types
- Maintain existing functionality while modernizing TypeScript syntax
- Covers 89+ files across packages/prisma/selects, repository classes, tRPC handlers, and API modules

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* refactor: complete remaining Prisma.validator conversions

- Update test fixture files with satisfies syntax
- Apply lint-staged formatting fixes
- Complete refactoring of all remaining files

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* revert: remove unintended platform library update

- Revert yarn.lock changes that updated @calcom/platform-libraries from 0.0.236 to 0.0.239
- This was an unintended side effect of the refactoring process
- Keep only the intended Prisma.validator → satisfies syntax changes

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* fix: update ESLint plugin references to correct package name

- Change @calcom/eslint to @calcom/eslint-plugin-eslint in eslint-preset.js
- Resolves 'Failed to load plugin @calcom/eslint' error causing CI failures

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: alex@cal.com <me@alexvanandel.com>
2025-07-04 21:08:05 +01:00

264 lines
7.7 KiB
TypeScript

import type { Prisma } from "@prisma/client";
import short from "short-uuid";
import { v5 as uuidv5 } from "uuid";
import dayjs from "@calcom/dayjs";
import { getRescheduleLink } from "@calcom/lib/CalEventParser";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import prisma from "@calcom/prisma";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { CalendarEventClass } from "./class";
const log = logger.getSubLogger({ prefix: ["builders", "CalendarEvent", "builder"] });
const translator = short();
const userSelect = {
select: {
id: true,
email: true,
name: true,
username: true,
timeZone: true,
credentials: true,
bufferTime: true,
destinationCalendar: true,
locale: true,
},
} satisfies Prisma.UserArgs;
type User = Omit<Prisma.UserGetPayload<typeof userSelect>, "selectedCalendars">;
type PersonAttendeeCommonFields = Pick<User, "id" | "email" | "name" | "locale" | "timeZone" | "username">;
interface ICalendarEventBuilder {
calendarEvent: CalendarEventClass;
eventType: Awaited<ReturnType<CalendarEventBuilder["getEventFromEventId"]>>;
users: Awaited<ReturnType<CalendarEventBuilder["getUserById"]>>[];
attendeesList: PersonAttendeeCommonFields[];
teamMembers: Awaited<ReturnType<CalendarEventBuilder["getTeamMembers"]>>;
rescheduleLink: string;
}
export class CalendarEventBuilder implements ICalendarEventBuilder {
calendarEvent!: CalendarEventClass;
eventType!: ICalendarEventBuilder["eventType"];
users!: ICalendarEventBuilder["users"];
attendeesList: ICalendarEventBuilder["attendeesList"] = [];
teamMembers: ICalendarEventBuilder["teamMembers"] = [];
rescheduleLink!: string;
constructor() {
this.reset();
}
private reset() {
this.calendarEvent = new CalendarEventClass();
}
public init(initProps: CalendarEventClass) {
this.calendarEvent = new CalendarEventClass(initProps);
}
public setEventType(eventType: ICalendarEventBuilder["eventType"]) {
this.eventType = eventType;
}
public async buildEventObjectFromInnerClass(eventId: number) {
const resultEvent = await this.getEventFromEventId(eventId);
if (resultEvent) {
this.eventType = resultEvent;
}
}
public async buildUsersFromInnerClass() {
if (!this.eventType) {
throw new Error("exec BuildEventObjectFromInnerClass before calling this function");
}
const users = this.eventType.users;
/* If this event was pre-relationship migration */
if (!users.length && this.eventType.userId) {
const eventTypeUser = await this.getUserById(this.eventType.userId);
if (!eventTypeUser) {
throw new Error("buildUsersFromINnerClass.eventTypeUser.notFound");
}
users.push(eventTypeUser);
}
this.setUsers(users);
}
public buildAttendeesList() {
// Language Function was set on builder init
this.attendeesList = [
...(this.calendarEvent.attendees as unknown as PersonAttendeeCommonFields[]),
...this.teamMembers,
];
}
private async getUserById(userId: number) {
let resultUser: User | null;
try {
resultUser = await prisma.user.findUniqueOrThrow({
where: {
id: userId,
},
...userSelect,
});
} catch (error) {
throw new Error("getUsersById.users.notFound");
}
return resultUser;
}
private async getEventFromEventId(eventTypeId: number) {
let resultEventType;
try {
resultEventType = await prisma.eventType.findUniqueOrThrow({
where: {
id: eventTypeId,
},
select: {
id: true,
users: userSelect,
team: {
select: {
id: true,
name: true,
slug: true,
},
},
description: true,
slug: true,
teamId: true,
title: true,
length: true,
eventName: true,
schedulingType: true,
periodType: true,
periodStartDate: true,
periodEndDate: true,
periodDays: true,
periodCountCalendarDays: true,
requiresConfirmation: true,
userId: true,
price: true,
currency: true,
metadata: true,
destinationCalendar: true,
hideCalendarNotes: true,
hideCalendarEventDetails: true,
},
});
} catch (error) {
throw new Error("Error while getting eventType");
}
log.debug("getEventFromEventId.resultEventType", safeStringify(resultEventType));
return resultEventType;
}
public async buildTeamMembers() {
this.teamMembers = await this.getTeamMembers();
}
private async getTeamMembers() {
// Users[0] its organizer so we are omitting with slice(1)
const teamMemberPromises = this.users.slice(1).map(async function (user) {
return {
id: user.id,
username: user.username,
email: user.email || "", // @NOTE: Should we change this "" to teamMemberId?
name: user.name || "",
timeZone: user.timeZone,
language: {
translate: await getTranslation(user.locale ?? "en", "common"),
locale: user.locale ?? "en",
},
locale: user.locale,
} as PersonAttendeeCommonFields;
});
return await Promise.all(teamMemberPromises);
}
public buildUIDCalendarEvent() {
if (this.users && this.users.length > 0) {
throw new Error("call buildUsers before calling this function");
}
const [mainOrganizer] = this.users;
const seed = `${mainOrganizer.username}:${dayjs(this.calendarEvent.startTime)
.utc()
.format()}:${new Date().getTime()}`;
const uid = translator.fromUUID(uuidv5(seed, uuidv5.URL));
this.calendarEvent.uid = uid;
}
public setLocation(location: CalendarEventClass["location"]) {
this.calendarEvent.location = location;
}
public setUId(uid: CalendarEventClass["uid"]) {
this.calendarEvent.uid = uid;
}
public setDestinationCalendar(destinationCalendar: CalendarEventClass["destinationCalendar"]) {
this.calendarEvent.destinationCalendar = destinationCalendar;
}
public setHideCalendarNotes(hideCalendarNotes: CalendarEventClass["hideCalendarNotes"]) {
this.calendarEvent.hideCalendarNotes = hideCalendarNotes;
}
public setHideCalendarEventDetails(
hideCalendarEventDetails: CalendarEventClass["hideCalendarEventDetails"]
) {
this.calendarEvent.hideCalendarEventDetails = hideCalendarEventDetails;
}
public setDescription(description: CalendarEventClass["description"]) {
this.calendarEvent.description = description;
}
public setNotes(notes: CalendarEvent["additionalNotes"]) {
this.calendarEvent.additionalNotes = notes;
}
public setCancellationReason(cancellationReason: CalendarEventClass["cancellationReason"]) {
this.calendarEvent.cancellationReason = cancellationReason;
}
public setUsers(users: User[]) {
this.users = users;
}
public async setUsersFromId(userId: User["id"]) {
let resultUser: User | null;
try {
resultUser = await prisma.user.findUniqueOrThrow({
where: {
id: userId,
},
...userSelect,
});
this.setUsers([resultUser]);
} catch (error) {
throw new Error("getUsersById.users.notFound");
}
}
public buildRescheduleLink({
allowRescheduleForCancelledBooking = false,
}: {
allowRescheduleForCancelledBooking?: boolean;
} = {}) {
try {
this.rescheduleLink = getRescheduleLink({
calEvent: this.calendarEvent,
allowRescheduleForCancelledBooking,
});
} catch (error) {
if (error instanceof Error) {
throw new Error(`buildRescheduleLink.error: ${error.message}`);
}
}
}
}