Feat Booking Limits (#4759)

* Add db relevant stuff

* Basic UI there still buggy

* This UI is hard - some progress

* Fix awful state mangament

* Fix re-ordering

* Working UI logic!

* Partical working minMax function

* Fix min max

* bookingLImits api + tests

* Moved checkBookingLimits to backend only code

* Fix httperror import

* Return busy times

* Remove avaliablity calc

* Working for everything but year

* Remove redundant + fix async forloop

* Add compatible type

* Future proof with evenTypeId filter

* Fix commonjson

* Sorting + validation + tests + passing

* Add empty test

* Move validation check  to backend

* Add bookinglimits in trpc

* Add test for undefined

* Apply suggestions from code review

Co-authored-by: Jeroen Reumkens <[email protected]>

* Update apps/web/components/v2/eventtype/EventLimitsTab.tsx

Co-authored-by: Jeroen Reumkens <[email protected]>

* Rename value for eligiability

* Rename keyof type

* status code

* Fix toggle not toggling off

* Update apps/web/pages/v2/event-types/[type]/index.tsx

Co-authored-by: Omar López <[email protected]>

* Update apps/web/pages/v2/event-types/[type]/index.tsx

Co-authored-by: Omar López <[email protected]>

* Change back to undefined as it is working for sean. See if it fails on testapp

* Fixing test builder

Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: Jeroen Reumkens <[email protected]>
Co-authored-by: Hariom Balhara <[email protected]>
Co-authored-by: Omar López <[email protected]>
Co-authored-by: Leo Giovanetti <[email protected]>
This commit is contained in:
22 files changed
+551 -20

No files matched your search

+1 -1
View File
@@ -55,7 +55,7 @@ export async function getBusyTimes(params: {
if (credentials?.length > 0) {
const calendarBusyTimes = await getBusyCalendarTimes(credentials, startTime, endTime, selectedCalendars);
busyTimes.push(...calendarBusyTimes); /*
busyTimes.push(...calendarBusyTimes); /*
// TODO: Disabled until we can filter Zoom events by date. Also this is adding too much latency.
const videoBusyTimes = (await getBusyVideoTimes(credentials)).filter(notEmpty);
console.log("videoBusyTimes", videoBusyTimes);
+61 -2
View File
@@ -2,12 +2,15 @@ import { Prisma } from "@prisma/client";
import { z } from "zod";
import dayjs, { Dayjs } from "@calcom/dayjs";
import { parseBookingLimit } from "@calcom/lib";
import { getWorkingHours } from "@calcom/lib/availability";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { checkLimit } from "@calcom/lib/server";
import { performance } from "@calcom/lib/server/perfObserver";
import prisma, { availabilityUserSelect } from "@calcom/prisma";
import { stringToDayjs } from "@calcom/prisma/zod-utils";
import { BookingLimit, EventBusyDetails } from "@calcom/types/Calendar";
import { getBusyTimes } from "./getBusyTimes";
@@ -29,6 +32,7 @@ const getEventType = (id: number) =>
select: {
id: true,
seatsPerTimeSlot: true,
bookingLimits: true,
timeZone: true,
schedule: {
select: {
@@ -115,8 +119,11 @@ export async function getUserAvailability(
/* 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;
if (!currentSeats && eventType?.seatsPerTimeSlot)
if (!currentSeats && eventType?.seatsPerTimeSlot) {
currentSeats = await getCurrentSeats(eventType.id, dateFrom, dateTo);
}
const bookingLimits = parseBookingLimit(eventType?.bookingLimits);
const { selectedCalendars, ...currentUser } = user;
@@ -129,7 +136,7 @@ export async function getUserAvailability(
selectedCalendars,
});
const bufferedBusyTimes = busyTimes.map((a) => ({
const bufferedBusyTimes: EventBusyDetails[] = busyTimes.map((a) => ({
...a,
start: dayjs(a.start).subtract(currentUser.bufferTime, "minute").toISOString(),
end: dayjs(a.end)
@@ -139,6 +146,58 @@ export async function getUserAvailability(
source: query.withSource ? a.source : undefined,
}));
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";
let total = 0;
// Get all bookings that are within the filter period
ourBookings.forEach((booking) => {
const startDate = dayjs(booking.start).startOf(filter);
// this is parsed above with parseBookingLimit so we know it's safe.
const endDate = dayjs(startDate).endOf(filter);
if (dayjs(booking.start).isBetween(startDate, endDate)) total++;
if (total >= limit)
bufferedBusyTimes.push({ start: startDate.toISOString(), end: endDate.toISOString() });
});
}
}
const schedule = eventType?.schedule
? { ...eventType?.schedule }
: {
+1
View File
@@ -80,6 +80,7 @@ const commons = {
destinationCalendar: null,
team: null,
requiresConfirmation: false,
bookingLimits: null,
hidden: false,
userId: 0,
workflows: [],
+1
View File
@@ -1,3 +1,4 @@
export { default as classNames } from "./classNames";
export { default as isPrismaObj, isPrismaObjOrUndefined } from "./isPrismaObj";
export * from "./isRecurringEvent";
export * from "./isBookingLimits";
+29
View File
@@ -0,0 +1,29 @@
import { bookingLimitsType } from "@calcom/prisma/zod-utils";
import { BookingLimit } from "@calcom/types/Calendar";
export function isBookingLimit(obj: unknown): obj is BookingLimit {
return bookingLimitsType.safeParse(obj).success;
}
export function parseBookingLimit(obj: unknown): BookingLimit | null {
let bookingLimit: BookingLimit | null = null;
if (isBookingLimit(obj)) bookingLimit = obj;
return bookingLimit;
}
export const validateBookingLimitOrder = (input: BookingLimit) => {
const validationOrderKeys = ["PER_DAY", "PER_WEEK", "PER_MONTH", "PER_YEAR"];
// Sort booking limits by validationOrder
const sorted = Object.entries(input)
.sort(([, value], [, valuetwo]) => {
return value - valuetwo;
})
.map(([key]) => key);
const validationOrderWithoutMissing = validationOrderKeys.filter((key) => sorted.includes(key));
const isValid = sorted.every((key, index) => validationOrderWithoutMissing[index] === key);
return isValid;
};
+94
View File
@@ -0,0 +1,94 @@
import dayjs from "@calcom/dayjs";
import prisma from "@calcom/prisma";
import { BookingLimit } from "@calcom/types/Calendar";
import { HttpError } from "../http-error";
import { parseBookingLimit } from "../isBookingLimits";
export async function checkBookingLimits(
bookingLimits: any,
eventStartDate: Date,
eventId: number,
returnBusyTimes?: boolean
) {
const parsedBookingLimits = parseBookingLimit(bookingLimits);
if (parsedBookingLimits) {
const limitCalculations = Object.entries(parsedBookingLimits).map(
async ([key, limitingNumber]) =>
await checkLimit({ key, limitingNumber, eventStartDate, eventId, returnBusyTimes })
);
await Promise.all(limitCalculations)
.then((res) => {
if (returnBusyTimes) {
return res;
}
})
.catch((error) => {
throw new HttpError({ message: error.message, statusCode: 401 });
});
return true;
}
return false;
}
export async function checkLimit({
eventStartDate,
eventId,
key,
limitingNumber,
returnBusyTimes = false,
}: {
eventStartDate: Date;
eventId: number;
key: string;
limitingNumber: number;
returnBusyTimes?: boolean;
}) {
{
const limitKey = key as keyof BookingLimit;
// 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"; // Have to cast here
const startDate = dayjs(eventStartDate).startOf(filter).toDate();
// this is parsed above with parseBookingLimit so we know it's safe.
const endDate = dayjs(startDate).endOf(filter).toDate();
// This allows us to easily add it within dayjs
const bookingsInPeriod = await prisma.booking.count({
where: {
status: "ACCEPTED",
eventType: {
AND: [
{
id: eventId,
bookings: {
some: {
startTime: {
gte: startDate,
},
endTime: {
lte: endDate,
},
},
},
},
],
},
},
});
if (bookingsInPeriod >= limitingNumber) {
// This is used when getting availbility
if (returnBusyTimes) {
return {
start: startDate,
end: endDate,
};
}
throw new HttpError({
message: `Booking limit of ${limitingNumber}/${filter} reached for this eventType`,
statusCode: 403,
});
}
}
}
+2
View File
@@ -1,3 +1,5 @@
export { checkBookingLimits, checkLimit } from "./checkBookingLimits";
export { default as defaultHandler } from "./defaultHandler";
export { default as defaultResponder } from "./defaultResponder";
export { getLuckyUser } from "./getLuckyUser";
+1
View File
@@ -87,6 +87,7 @@ export const buildEventType = (eventType?: Partial<EventType>): EventType => {
seatsPerTimeSlot: null,
schedulingType: null,
scheduleId: null,
bookingLimits: null,
price: 0,
currency: "usd",
slotInterval: null,
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "EventType" ADD COLUMN "bookingLimits" JSONB;
+2
View File
@@ -78,6 +78,8 @@ model EventType {
/// @zod.custom(imports.successRedirectUrl)
successRedirectUrl String?
workflows WorkflowsOnEventTypes[]
/// @zod.custom(imports.bookingLimitsType)
bookingLimits Json?
@@unique([userId, slug])
@@unique([teamId, slug])
+9
View File
@@ -48,6 +48,15 @@ export const recurringEventType = z
})
.nullable();
export const bookingLimitsType = z
.object({
PER_DAY: z.number().optional(),
PER_WEEK: z.number().optional(),
PER_MONTH: z.number().optional(),
PER_YEAR: z.number().optional(),
})
.nullable();
export const eventTypeSlug = z.string().transform((val) => slugify(val.trim()));
export const stringToDate = z.string().transform((a) => new Date(a));
@@ -5,6 +5,7 @@ import { z } from "zod";
import getAppKeysFromSlug from "@calcom/app-store/_utils/getAppKeysFromSlug";
import { DailyLocationType } from "@calcom/app-store/locations";
import { stripeDataSchema } from "@calcom/app-store/stripepayment/lib/server";
import { validateBookingLimitOrder } from "@calcom/lib";
import { _DestinationCalendarModel, _EventTypeCustomInputModel, _EventTypeModel } from "@calcom/prisma/zod";
import { stringOrNumber } from "@calcom/prisma/zod-utils";
import { createEventTypeInput } from "@calcom/prisma/zod/custom/eventtype";
@@ -257,6 +258,7 @@ export const eventTypesRouter = createProtectedRouter()
schedule,
periodType,
locations,
bookingLimits,
destinationCalendar,
customInputs,
recurringEvent,
@@ -296,6 +298,13 @@ export const eventTypesRouter = createProtectedRouter()
data.customInputs = handleCustomInputs(customInputs, id);
}
if (bookingLimits) {
const isValid = validateBookingLimitOrder(bookingLimits);
if (!isValid)
throw new TRPCError({ code: "BAD_REQUEST", message: "Booking limits must be in ascending order." });
data.bookingLimits = bookingLimits;
}
if (schedule) {
data.schedule = {
connect: {
@@ -11,6 +11,7 @@ import logger from "@calcom/lib/logger";
import { performance } from "@calcom/lib/server/perfObserver";
import getTimeSlots from "@calcom/lib/slots";
import prisma, { availabilityUserSelect } from "@calcom/prisma";
import { EventBusyDate } from "@calcom/types/Calendar";
import { TimeRange } from "@calcom/types/schedule";
import { TRPCError } from "@trpc/server";
@@ -53,7 +54,7 @@ const checkIfIsAvailable = ({
currentSeats,
}: {
time: Dayjs;
busy: (TimeRange | { start: string; end: string })[];
busy: (TimeRange | { start: string; end: string } | EventBusyDate)[];
eventLength: number;
beforeBufferTime: number;
currentSeats?: CurrentSeats;
@@ -118,6 +119,7 @@ async function getEventType(ctx: { prisma: typeof prisma }, input: z.infer<typeo
slotInterval: true,
beforeEventBuffer: true,
afterEventBuffer: true,
bookingLimits: true,
schedulingType: true,
periodType: true,
periodStartDate: true,
+2 -2
View File
@@ -1,4 +1,4 @@
export interface BufferedBusyTime {
start: string;
end: string;
start: string | Date;
end: string | Date;
}
+7
View File
@@ -105,6 +105,13 @@ export interface RecurringEvent {
tzid?: string | undefined;
}
export interface BookingLimit {
PER_DAY?: number | undefined;
PER_WEEK?: number | undefined;
PER_MONTH?: number | undefined;
PER_YEAR?: number | undefined;
}
// If modifying this interface, probably should update builders/calendarEvent files
export interface CalendarEvent {
type: string;