2022-06-10 18:38:46 +00:00
|
|
|
import { Prisma } from "@prisma/client";
|
|
|
|
import { z } from "zod";
|
|
|
|
|
2022-07-07 15:26:22 +00:00
|
|
|
import dayjs, { Dayjs } from "@calcom/dayjs";
|
2022-10-12 05:29:04 +00:00
|
|
|
import { parseBookingLimit } from "@calcom/lib";
|
2022-06-10 18:38:46 +00:00
|
|
|
import { getWorkingHours } from "@calcom/lib/availability";
|
|
|
|
import { HttpError } from "@calcom/lib/http-error";
|
2022-07-07 15:26:22 +00:00
|
|
|
import logger from "@calcom/lib/logger";
|
2022-10-12 05:29:04 +00:00
|
|
|
import { checkLimit } from "@calcom/lib/server";
|
2022-08-12 18:18:13 +00:00
|
|
|
import { performance } from "@calcom/lib/server/perfObserver";
|
2022-06-10 18:38:46 +00:00
|
|
|
import prisma, { availabilityUserSelect } from "@calcom/prisma";
|
2022-11-03 14:24:07 +00:00
|
|
|
import { EventTypeMetaDataSchema, stringToDayjs } from "@calcom/prisma/zod-utils";
|
2022-10-12 05:29:04 +00:00
|
|
|
import { BookingLimit, EventBusyDetails } from "@calcom/types/Calendar";
|
2022-06-10 18:38:46 +00:00
|
|
|
|
|
|
|
import { getBusyTimes } from "./getBusyTimes";
|
|
|
|
|
|
|
|
const availabilitySchema = z
|
|
|
|
.object({
|
|
|
|
dateFrom: stringToDayjs,
|
|
|
|
dateTo: stringToDayjs,
|
|
|
|
eventTypeId: z.number().optional(),
|
|
|
|
username: z.string().optional(),
|
|
|
|
userId: z.number().optional(),
|
2022-07-11 11:00:08 +00:00
|
|
|
afterEventBuffer: z.number().optional(),
|
2022-11-02 09:40:30 +00:00
|
|
|
beforeEventBuffer: z.number().optional(),
|
2022-09-07 19:28:43 +00:00
|
|
|
withSource: z.boolean().optional(),
|
2022-06-10 18:38:46 +00:00
|
|
|
})
|
|
|
|
.refine((data) => !!data.username || !!data.userId, "Either username or userId should be filled in.");
|
|
|
|
|
2022-11-03 14:24:07 +00:00
|
|
|
const getEventType = async (id: number) => {
|
|
|
|
const eventType = await prisma.eventType.findUnique({
|
2022-06-10 18:38:46 +00:00
|
|
|
where: { id },
|
|
|
|
select: {
|
2022-06-15 20:54:31 +00:00
|
|
|
id: true,
|
2022-06-10 18:38:46 +00:00
|
|
|
seatsPerTimeSlot: true,
|
2022-10-12 05:29:04 +00:00
|
|
|
bookingLimits: true,
|
2022-06-10 18:38:46 +00:00
|
|
|
timeZone: true,
|
2022-11-03 14:24:07 +00:00
|
|
|
metadata: true,
|
2022-06-10 18:38:46 +00:00
|
|
|
schedule: {
|
|
|
|
select: {
|
|
|
|
availability: true,
|
|
|
|
timeZone: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
availability: {
|
|
|
|
select: {
|
|
|
|
startTime: true,
|
|
|
|
endTime: true,
|
|
|
|
days: true,
|
2022-12-14 17:30:55 +00:00
|
|
|
date: true,
|
2022-06-10 18:38:46 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
2022-11-03 14:24:07 +00:00
|
|
|
if (!eventType) {
|
|
|
|
return eventType;
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
...eventType,
|
|
|
|
metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
|
|
|
|
};
|
|
|
|
};
|
2022-06-10 18:38:46 +00:00
|
|
|
|
|
|
|
type EventType = Awaited<ReturnType<typeof getEventType>>;
|
|
|
|
|
|
|
|
const getUser = (where: Prisma.UserWhereUniqueInput) =>
|
|
|
|
prisma.user.findUnique({
|
|
|
|
where,
|
|
|
|
select: availabilityUserSelect,
|
|
|
|
});
|
|
|
|
|
|
|
|
type User = Awaited<ReturnType<typeof getUser>>;
|
|
|
|
|
2022-06-15 20:54:31 +00:00
|
|
|
export const getCurrentSeats = (eventTypeId: number, dateFrom: Dayjs, dateTo: Dayjs) =>
|
|
|
|
prisma.booking.findMany({
|
|
|
|
where: {
|
|
|
|
eventTypeId,
|
|
|
|
startTime: {
|
|
|
|
gte: dateFrom.format(),
|
|
|
|
lte: dateTo.format(),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
uid: true,
|
|
|
|
startTime: true,
|
|
|
|
_count: {
|
|
|
|
select: {
|
|
|
|
attendees: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
export type CurrentSeats = Awaited<ReturnType<typeof getCurrentSeats>>;
|
|
|
|
|
2022-08-22 23:53:51 +00:00
|
|
|
/** This should be called getUsersWorkingHoursAndBusySlots (...and remaining seats, and final timezone) */
|
2022-06-10 18:38:46 +00:00
|
|
|
export async function getUserAvailability(
|
2022-06-14 21:23:18 +00:00
|
|
|
query: {
|
2022-09-07 19:28:43 +00:00
|
|
|
withSource?: boolean;
|
2022-06-14 21:23:18 +00:00
|
|
|
username?: string;
|
|
|
|
userId?: number;
|
2022-06-10 18:38:46 +00:00
|
|
|
dateFrom: string;
|
|
|
|
dateTo: string;
|
|
|
|
eventTypeId?: number;
|
2022-07-11 11:00:08 +00:00
|
|
|
afterEventBuffer?: number;
|
2022-11-02 09:40:30 +00:00
|
|
|
beforeEventBuffer?: number;
|
2022-06-10 18:38:46 +00:00
|
|
|
},
|
|
|
|
initialData?: {
|
|
|
|
user?: User;
|
|
|
|
eventType?: EventType;
|
2022-06-15 20:54:31 +00:00
|
|
|
currentSeats?: CurrentSeats;
|
2022-06-10 18:38:46 +00:00
|
|
|
}
|
|
|
|
) {
|
2022-11-02 09:40:30 +00:00
|
|
|
const { username, userId, dateFrom, dateTo, eventTypeId, afterEventBuffer, beforeEventBuffer } =
|
2022-07-11 11:00:08 +00:00
|
|
|
availabilitySchema.parse(query);
|
2022-06-10 18:38:46 +00:00
|
|
|
|
|
|
|
if (!dateFrom.isValid() || !dateTo.isValid())
|
|
|
|
throw new HttpError({ statusCode: 400, message: "Invalid time range given." });
|
|
|
|
|
|
|
|
const where: Prisma.UserWhereUniqueInput = {};
|
|
|
|
if (username) where.username = username;
|
|
|
|
if (userId) where.id = userId;
|
|
|
|
|
|
|
|
let user: User | null = initialData?.user || null;
|
|
|
|
if (!user) user = await getUser(where);
|
|
|
|
if (!user) throw new HttpError({ statusCode: 404, message: "No user found" });
|
|
|
|
|
|
|
|
let eventType: EventType | null = initialData?.eventType || null;
|
|
|
|
if (!eventType && eventTypeId) eventType = await getEventType(eventTypeId);
|
|
|
|
|
2022-06-15 20:54:31 +00:00
|
|
|
/* Current logic is if a booking is in a time slot mark it as busy, but seats can have more than one attendee so grab
|
|
|
|
current bookings with a seats event type and display them on the calendar, even if they are full */
|
|
|
|
let currentSeats: CurrentSeats | null = initialData?.currentSeats || null;
|
2022-10-12 05:29:04 +00:00
|
|
|
if (!currentSeats && eventType?.seatsPerTimeSlot) {
|
2022-06-15 20:54:31 +00:00
|
|
|
currentSeats = await getCurrentSeats(eventType.id, dateFrom, dateTo);
|
2022-10-12 05:29:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const bookingLimits = parseBookingLimit(eventType?.bookingLimits);
|
2022-06-15 20:54:31 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
const { selectedCalendars, ...currentUser } = user;
|
|
|
|
|
|
|
|
const busyTimes = await getBusyTimes({
|
|
|
|
credentials: currentUser.credentials,
|
|
|
|
startTime: dateFrom.toISOString(),
|
|
|
|
endTime: dateTo.toISOString(),
|
|
|
|
eventTypeId,
|
|
|
|
userId: currentUser.id,
|
|
|
|
selectedCalendars,
|
2022-11-02 09:40:30 +00:00
|
|
|
beforeEventBuffer,
|
|
|
|
afterEventBuffer,
|
2022-06-10 18:38:46 +00:00
|
|
|
});
|
|
|
|
|
2022-10-12 05:29:04 +00:00
|
|
|
const bufferedBusyTimes: EventBusyDetails[] = busyTimes.map((a) => ({
|
2022-09-07 19:28:43 +00:00
|
|
|
...a,
|
2022-11-02 09:40:30 +00:00
|
|
|
start: dayjs(a.start).toISOString(),
|
|
|
|
end: dayjs(a.end).toISOString(),
|
2022-08-03 07:19:16 +00:00
|
|
|
title: a.title,
|
2022-09-07 19:28:43 +00:00
|
|
|
source: query.withSource ? a.source : undefined,
|
2022-06-10 18:38:46 +00:00
|
|
|
}));
|
|
|
|
|
2022-10-12 05:29:04 +00:00
|
|
|
if (bookingLimits) {
|
|
|
|
// Get all dates between dateFrom and dateTo
|
|
|
|
const dates = []; // this is as dayjs date
|
|
|
|
let startDate = dayjs(dateFrom);
|
|
|
|
const endDate = dayjs(dateTo);
|
|
|
|
while (startDate.isBefore(endDate)) {
|
|
|
|
dates.push(startDate.add(1, "day"));
|
|
|
|
startDate = startDate.add(1, "day");
|
|
|
|
}
|
|
|
|
|
|
|
|
const ourBookings = busyTimes.filter((busyTime) =>
|
|
|
|
busyTime.source?.startsWith(`eventType-${eventType?.id}`)
|
|
|
|
);
|
|
|
|
|
|
|
|
// Apply booking limit filter against our bookings
|
|
|
|
|
|
|
|
for (const [key, limit] of Object.entries(bookingLimits)) {
|
|
|
|
const limitKey = key as keyof BookingLimit;
|
|
|
|
|
|
|
|
if (limitKey === "PER_YEAR") {
|
|
|
|
const yearlyBusyTime = await checkLimit({
|
|
|
|
eventStartDate: startDate.toDate(),
|
|
|
|
limitingNumber: limit,
|
|
|
|
eventId: eventType?.id as number,
|
|
|
|
key: "PER_YEAR",
|
|
|
|
returnBusyTimes: true,
|
|
|
|
});
|
|
|
|
if (!yearlyBusyTime) break;
|
|
|
|
bufferedBusyTimes.push({
|
|
|
|
start: yearlyBusyTime.start.toISOString(),
|
|
|
|
end: yearlyBusyTime.end.toISOString(),
|
|
|
|
});
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Take PER_DAY and turn it into day and PER_WEEK into week etc.
|
|
|
|
const filter = limitKey.split("_")[1].toLocaleLowerCase() as "day" | "week" | "month" | "year";
|
|
|
|
|
2022-12-20 13:10:54 +00:00
|
|
|
// loop through all dates and check if we have reached the limit
|
|
|
|
for (const date of dates) {
|
|
|
|
let total = 0;
|
|
|
|
const startDate = dayjs(date).startOf(filter);
|
2022-10-12 05:29:04 +00:00
|
|
|
// this is parsed above with parseBookingLimit so we know it's safe.
|
2022-12-20 13:10:54 +00:00
|
|
|
const endDate = dayjs(date).endOf(filter);
|
|
|
|
for (const booking of ourBookings) {
|
|
|
|
const bookingEventTypeId = booking.source?.split("-")[1];
|
|
|
|
if (
|
|
|
|
// Only check OUR booking that matches the current eventTypeId
|
|
|
|
// we don't care about another event type in this case as we dont need to know their booking limits
|
|
|
|
!(bookingEventTypeId == eventType?.id && dayjs(booking.start).isBetween(startDate, endDate))
|
|
|
|
) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// increment total and check against the limit, adding a busy time if condition is met.
|
|
|
|
total++;
|
|
|
|
if (total >= limit) {
|
|
|
|
bufferedBusyTimes.push({
|
|
|
|
start: startDate.toISOString(),
|
|
|
|
end: endDate.toISOString(),
|
|
|
|
});
|
|
|
|
break;
|
|
|
|
}
|
2022-11-22 03:17:54 +00:00
|
|
|
}
|
2022-12-20 13:10:54 +00:00
|
|
|
}
|
2022-10-12 05:29:04 +00:00
|
|
|
}
|
|
|
|
}
|
2022-11-03 14:24:07 +00:00
|
|
|
|
2022-12-21 19:32:42 +00:00
|
|
|
const userSchedule = currentUser.schedules.filter(
|
|
|
|
(schedule) => !currentUser.defaultScheduleId || schedule.id === currentUser.defaultScheduleId
|
|
|
|
)[0];
|
|
|
|
|
2022-11-03 14:24:07 +00:00
|
|
|
const schedule =
|
|
|
|
!eventType?.metadata?.config?.useHostSchedulesForTeamEvent && eventType?.schedule
|
|
|
|
? { ...eventType?.schedule }
|
|
|
|
: {
|
2022-12-21 19:32:42 +00:00
|
|
|
...userSchedule,
|
|
|
|
availability: userSchedule.availability.map((a) => ({
|
|
|
|
...a,
|
|
|
|
userId: currentUser.id,
|
|
|
|
})),
|
2022-11-03 14:24:07 +00:00
|
|
|
};
|
2022-06-10 18:38:46 +00:00
|
|
|
|
2022-07-07 15:26:22 +00:00
|
|
|
const startGetWorkingHours = performance.now();
|
2022-08-12 19:29:29 +00:00
|
|
|
|
2022-08-22 23:53:51 +00:00
|
|
|
const timeZone = schedule.timeZone || eventType?.timeZone || currentUser.timeZone;
|
2022-12-14 17:30:55 +00:00
|
|
|
|
|
|
|
const availability =
|
2022-06-10 18:38:46 +00:00
|
|
|
schedule.availability ||
|
2022-12-14 17:30:55 +00:00
|
|
|
(eventType?.availability.length ? eventType.availability : currentUser.availability);
|
|
|
|
|
|
|
|
const workingHours = getWorkingHours({ timeZone }, availability);
|
|
|
|
|
2022-07-07 15:26:22 +00:00
|
|
|
const endGetWorkingHours = performance.now();
|
|
|
|
logger.debug(`getWorkingHours took ${endGetWorkingHours - startGetWorkingHours}ms for userId ${userId}`);
|
2022-07-27 19:12:42 +00:00
|
|
|
|
2022-12-14 17:30:55 +00:00
|
|
|
const dateOverrides = availability
|
|
|
|
.filter((availability) => !!availability.date)
|
|
|
|
.map((override) => {
|
|
|
|
const startTime = dayjs.utc(override.startTime);
|
|
|
|
const endTime = dayjs.utc(override.endTime);
|
|
|
|
return {
|
|
|
|
start: dayjs.utc(override.date).hour(startTime.hour()).minute(startTime.minute()).toDate(),
|
|
|
|
end: dayjs.utc(override.date).hour(endTime.hour()).minute(endTime.minute()).toDate(),
|
|
|
|
};
|
|
|
|
});
|
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
return {
|
|
|
|
busy: bufferedBusyTimes,
|
|
|
|
timeZone,
|
|
|
|
workingHours,
|
2022-12-14 17:30:55 +00:00
|
|
|
dateOverrides,
|
2022-06-10 18:38:46 +00:00
|
|
|
currentSeats,
|
|
|
|
};
|
|
|
|
}
|