[CAL-988] Limit total appointment time per day/week/month/year (#7166)

Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Omar López <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-03-10 21:00:19 +01:00
1 parent eb66931366
commit cbc9cd60d5
28 files changed
+664 -228

No files matched your search

@@ -5,4 +5,4 @@ items:
- /api/app-store/routing-forms/3.jpg
---
It would allow a booker to connect with the right person or choose the right event, faster. It would work by taking inputs from the booker and using that data to route to the correct booker/event as configured by Cal user
It would allow a booker to connect with the right person or choose the right event, faster. It would work by taking inputs from the booker and using that data to route to the correct booker/event as configured by Cal user
+167 -66
View File
@@ -3,15 +3,16 @@ import { z } from "zod";
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import { parseBookingLimit } from "@calcom/lib";
import { parseBookingLimit, parseDurationLimit } 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 { checkBookingLimit } from "@calcom/lib/server";
import { performance } from "@calcom/lib/server/perfObserver";
import { getTotalBookingDuration } from "@calcom/lib/server/queries";
import prisma, { availabilityUserSelect } from "@calcom/prisma";
import { EventTypeMetaDataSchema, stringToDayjs } from "@calcom/prisma/zod-utils";
import type { BookingLimit, EventBusyDetails } from "@calcom/types/Calendar";
import type { EventBusyDetails, IntervalLimit } from "@calcom/types/Calendar";
import { getBusyTimes } from "./getBusyTimes";
@@ -24,6 +25,7 @@ const availabilitySchema = z
userId: z.number().optional(),
afterEventBuffer: z.number().optional(),
beforeEventBuffer: z.number().optional(),
duration: z.number().optional(),
withSource: z.boolean().optional(),
})
.refine((data) => !!data.username || !!data.userId, "Either username or userId should be filled in.");
@@ -35,6 +37,7 @@ const getEventType = async (id: number) => {
id: true,
seatsPerTimeSlot: true,
bookingLimits: true,
durationLimits: true,
timeZone: true,
metadata: true,
schedule: {
@@ -105,6 +108,7 @@ export async function getUserAvailability(
eventTypeId?: number;
afterEventBuffer?: number;
beforeEventBuffer?: number;
duration?: number;
},
initialData?: {
user?: User;
@@ -112,7 +116,7 @@ export async function getUserAvailability(
currentSeats?: CurrentSeats;
}
) {
const { username, userId, dateFrom, dateTo, eventTypeId, afterEventBuffer, beforeEventBuffer } =
const { username, userId, dateFrom, dateTo, eventTypeId, afterEventBuffer, beforeEventBuffer, duration } =
availabilitySchema.parse(query);
if (!dateFrom.isValid() || !dateTo.isValid())
@@ -135,8 +139,6 @@ export async function getUserAvailability(
currentSeats = await getCurrentSeats(eventType.id, dateFrom, dateTo);
}
const bookingLimits = parseBookingLimit(eventType?.bookingLimits);
const busyTimes = await getBusyTimes({
credentials: user.credentials,
startTime: dateFrom.toISOString(),
@@ -148,7 +150,7 @@ export async function getUserAvailability(
afterEventBuffer,
});
const bufferedBusyTimes: EventBusyDetails[] = busyTimes.map((a) => ({
let bufferedBusyTimes: EventBusyDetails[] = busyTimes.map((a) => ({
...a,
start: dayjs(a.start).toISOString(),
end: dayjs(a.end).toISOString(),
@@ -156,68 +158,31 @@ export async function getUserAvailability(
source: query.withSource ? a.source : undefined,
}));
const bookings = busyTimes.filter((busyTime) => busyTime.source?.startsWith(`eventType-${eventType?.id}`));
const bookingLimits = parseBookingLimit(eventType?.bookingLimits);
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);
startDate = startDate.add(1, "day");
}
const ourBookings = busyTimes.filter((busyTime) =>
busyTime.source?.startsWith(`eventType-${eventType?.id}`)
const bookingBusyTimes = await getBusyTimesFromBookingLimits(
bookings,
bookingLimits,
dateFrom,
dateTo,
eventType
);
bufferedBusyTimes = bufferedBusyTimes.concat(bookingBusyTimes);
}
// 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].toLowerCase() as "day" | "week" | "month" | "year";
// loop through all dates and check if we have reached the limit
for (const date of dates) {
let total = 0;
const startDate = date.startOf(filter);
// this is parsed above with parseBookingLimit so we know it's safe.
const endDate = date.endOf(filter);
for (const booking of ourBookings) {
const bookingEventTypeId = parseInt(booking.source?.split("-")[1] as string, 10);
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;
}
}
}
}
const durationLimits = parseDurationLimit(eventType?.durationLimits);
if (durationLimits) {
const durationBusyTimes = await getBusyTimesFromDurationLimits(
bookings,
durationLimits,
dateFrom,
dateTo,
duration,
eventType
);
bufferedBusyTimes = bufferedBusyTimes.concat(durationBusyTimes);
}
const userSchedule = user.schedules.filter(
@@ -264,3 +229,139 @@ export async function getUserAvailability(
currentSeats,
};
}
const getDatesBetween = (dateFrom: Dayjs, dateTo: Dayjs, period: "day" | "week" | "month" | "year") => {
const dates = [];
let startDate = dayjs(dateFrom).startOf(period);
const endDate = dayjs(dateTo).endOf(period);
while (startDate.isBefore(endDate)) {
dates.push(startDate);
startDate = startDate.add(1, period);
}
return dates;
};
const getBusyTimesFromBookingLimits = async (
bookings: EventBusyDetails[],
bookingLimits: IntervalLimit,
dateFrom: Dayjs,
dateTo: Dayjs,
eventType: EventType | undefined
) => {
const busyTimes: EventBusyDetails[] = [];
// Apply booking limit filter against our bookings
for (const [key, limit] of Object.entries(bookingLimits)) {
const limitKey = key as keyof IntervalLimit;
if (limitKey === "PER_YEAR") {
const yearlyBusyTime = await checkBookingLimit({
eventStartDate: dateFrom.toDate(),
limitingNumber: limit,
eventId: eventType?.id as number,
key: "PER_YEAR",
returnBusyTimes: true,
});
if (!yearlyBusyTime) break;
busyTimes.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 = key.split("_")[1].toLowerCase() as "day" | "week" | "month" | "year";
const dates = getDatesBetween(dateFrom, dateTo, filter);
// loop through all dates and check if we have reached the limit
for (const date of dates) {
let total = 0;
const startDate = date.startOf(filter);
// this is parsed above with parseBookingLimit so we know it's safe.
const endDate = date.endOf(filter);
for (const booking of bookings) {
const bookingEventTypeId = parseInt(booking.source?.split("-")[1] as string, 10);
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) {
busyTimes.push({ start: startDate.toISOString(), end: endDate.toISOString() });
break;
}
}
}
}
return busyTimes;
};
const getBusyTimesFromDurationLimits = async (
bookings: EventBusyDetails[],
durationLimits: IntervalLimit,
dateFrom: Dayjs,
dateTo: Dayjs,
duration: number | undefined,
eventType: EventType | undefined
) => {
const busyTimes: EventBusyDetails[] = [];
// Start check from larger time periods to smaller time periods, to skip unnecessary checks
for (const [key, limit] of Object.entries(durationLimits).reverse()) {
// Use aggregate sql query if we are checking PER_YEAR
if (key === "PER_YEAR") {
const totalBookingDuration = await getTotalBookingDuration({
eventId: eventType?.id as number,
startDate: dateFrom.startOf("year").toDate(),
endDate: dateFrom.endOf("year").toDate(),
});
if (totalBookingDuration + (duration ?? 0) > limit) {
busyTimes.push({
start: dateFrom.startOf("year").toISOString(),
end: dateFrom.endOf("year").toISOString(),
});
}
continue;
}
const filter = key.split("_")[1].toLowerCase() as "day" | "week" | "month" | "year";
const dates = getDatesBetween(dateFrom, dateTo, filter);
// loop through all dates and check if we have reached the limit
for (const date of dates) {
let total = duration ?? 0;
const startDate = date.startOf(filter);
const endDate = date.endOf(filter);
// add busy time if we have already reached the limit with just the selected duration
if (total > limit) {
busyTimes.push({ start: startDate.toISOString(), end: endDate.toISOString() });
continue;
}
for (const booking of bookings) {
const bookingEventTypeId = parseInt(booking.source?.split("-")[1] as string, 10);
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;
}
// Add current booking duration to total and check against the limit, adding a busy time if condition is met.
total += dayjs(booking.end).diff(dayjs(booking.start), "minute");
if (total > limit) {
busyTimes.push({ start: startDate.toISOString(), end: endDate.toISOString() });
break;
}
}
}
}
return busyTimes;
};
@@ -43,7 +43,7 @@ import { HttpError } from "@calcom/lib/http-error";
import isOutOfBounds, { BookingDateInPastError } from "@calcom/lib/isOutOfBounds";
import logger from "@calcom/lib/logger";
import { handlePayment } from "@calcom/lib/payment/handlePayment";
import { checkBookingLimits, getLuckyUser } from "@calcom/lib/server";
import { checkBookingLimits, checkDurationLimits, getLuckyUser } from "@calcom/lib/server";
import { getTranslation } from "@calcom/lib/server/i18n";
import { slugify } from "@calcom/lib/slugify";
import { updateWebUser as syncServicesUpdateWebUser } from "@calcom/lib/sync/SyncServiceManager";
@@ -222,6 +222,7 @@ const getEventTypesFromDB = async (eventTypeId: number) => {
recurringEvent: true,
seatsShowAttendees: true,
bookingLimits: true,
durationLimits: true,
workflows: {
include: {
workflow: {
@@ -592,6 +593,11 @@ async function handler(
await checkBookingLimits(eventType.bookingLimits, startAsDate, eventType.id);
}
if (eventType && eventType.hasOwnProperty("durationLimits") && eventType?.durationLimits) {
const startAsDate = dayjs(reqBody.start).toDate();
await checkDurationLimits(eventType.durationLimits, startAsDate, eventType.id);
}
if (!eventType.seatsPerTimeSlot) {
const availableUsers = await ensureAvailableUsers(
{
+1
View File
@@ -83,6 +83,7 @@ const commons = {
team: null,
requiresConfirmation: false,
bookingLimits: null,
durationLimits: null,
hidden: false,
userId: 0,
owner: null,
+3 -1
View File
@@ -5,7 +5,7 @@ import type { StripeData } from "@calcom/app-store/stripepayment/lib/server";
import { getEventTypeAppData, getLocationGroupedOptions } from "@calcom/app-store/utils";
import type { LocationObject } from "@calcom/core/location";
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import { parseBookingLimit, parseRecurringEvent } from "@calcom/lib";
import { parseBookingLimit, parseDurationLimit, parseRecurringEvent } from "@calcom/lib";
import getEnabledApps from "@calcom/lib/apps/getEnabledApps";
import { CAL_URL } from "@calcom/lib/constants";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
@@ -99,6 +99,7 @@ export default async function getEventTypeById({
slotInterval: true,
hashedLink: true,
bookingLimits: true,
durationLimits: true,
successRedirectUrl: true,
currency: true,
bookingFields: true,
@@ -234,6 +235,7 @@ export default async function getEventTypeById({
schedule: rawEventType.schedule?.id || rawEventType.users[0]?.defaultScheduleId || null,
recurringEvent: parseRecurringEvent(restEventType.recurringEvent),
bookingLimits: parseBookingLimit(restEventType.bookingLimits),
durationLimits: parseDurationLimit(restEventType.durationLimits),
locations: locations as unknown as LocationObject[],
metadata: parsedMetaData,
customInputs: parsedCustomInputs,
+2
View File
@@ -2,3 +2,5 @@ export { default as classNames } from "./classNames";
export { default as isPrismaObj, isPrismaObjOrUndefined } from "./isPrismaObj";
export * from "./isRecurringEvent";
export * from "./isBookingLimits";
export * from "./isDurationLimits";
export * from "./validateIntervalLimitOrder";
+6 -23
View File
@@ -1,29 +1,12 @@
import { bookingLimitsType } from "@calcom/prisma/zod-utils";
import type { BookingLimit } from "@calcom/types/Calendar";
import { intervalLimitsType } from "@calcom/prisma/zod-utils";
import type { IntervalLimit } from "@calcom/types/Calendar";
export function isBookingLimit(obj: unknown): obj is BookingLimit {
return bookingLimitsType.safeParse(obj).success;
export function isBookingLimit(obj: unknown): obj is IntervalLimit {
return intervalLimitsType.safeParse(obj).success;
}
export function parseBookingLimit(obj: unknown): BookingLimit | null {
let bookingLimit: BookingLimit | null = null;
export function parseBookingLimit(obj: unknown): IntervalLimit | null {
let bookingLimit: IntervalLimit | 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;
};
+12
View File
@@ -0,0 +1,12 @@
import { intervalLimitsType } from "@calcom/prisma/zod-utils";
import type { IntervalLimit } from "@calcom/types/Calendar";
export function isDurationLimit(obj: unknown): obj is IntervalLimit {
return intervalLimitsType.safeParse(obj).success;
}
export function parseDurationLimit(obj: unknown): IntervalLimit | null {
let durationLimit: IntervalLimit | null = null;
if (isDurationLimit(obj)) durationLimit = obj;
return durationLimit;
}
+5 -5
View File
@@ -1,6 +1,6 @@
import dayjs from "@calcom/dayjs";
import prisma from "@calcom/prisma";
import type { BookingLimit } from "@calcom/types/Calendar";
import type { IntervalLimit } from "@calcom/types/Calendar";
import { HttpError } from "../http-error";
import { parseBookingLimit } from "../isBookingLimits";
@@ -15,7 +15,7 @@ export async function checkBookingLimits(
if (parsedBookingLimits) {
const limitCalculations = Object.entries(parsedBookingLimits).map(
async ([key, limitingNumber]) =>
await checkLimit({ key, limitingNumber, eventStartDate, eventId, returnBusyTimes })
await checkBookingLimit({ key, limitingNumber, eventStartDate, eventId, returnBusyTimes })
);
await Promise.all(limitCalculations)
.then((res) => {
@@ -31,7 +31,7 @@ export async function checkBookingLimits(
return false;
}
export async function checkLimit({
export async function checkBookingLimit({
eventStartDate,
eventId,
key,
@@ -45,7 +45,7 @@ export async function checkLimit({
returnBusyTimes?: boolean;
}) {
{
const limitKey = key as keyof BookingLimit;
const limitKey = key as keyof IntervalLimit;
// 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();
@@ -77,7 +77,7 @@ export async function checkLimit({
},
});
if (bookingsInPeriod >= limitingNumber) {
// This is used when getting availbility
// This is used when getting availability
if (returnBusyTimes) {
return {
start: startDate,
@@ -0,0 +1,60 @@
import dayjs from "@calcom/dayjs";
import { HttpError } from "../http-error";
import { parseDurationLimit } from "../isDurationLimits";
import { getTotalBookingDuration } from "./queries";
export async function checkDurationLimits(durationLimits: any, eventStartDate: Date, eventId: number) {
const parsedDurationLimits = parseDurationLimit(durationLimits);
if (!parsedDurationLimits) {
return false;
}
const limitCalculations = Object.entries(parsedDurationLimits).map(
async ([key, limitingNumber]) =>
await checkDurationLimit({ key, limitingNumber, eventStartDate, eventId })
);
await Promise.all(limitCalculations).catch((error) => {
throw new HttpError({ message: error.message, statusCode: 401 });
});
return true;
}
export async function checkDurationLimit({
eventStartDate,
eventId,
key,
limitingNumber,
returnBusyTimes = false,
}: {
eventStartDate: Date;
eventId: number;
key: string;
limitingNumber: number;
returnBusyTimes?: boolean;
}) {
{
// Take PER_DAY and turn it into day and PER_WEEK into week etc.
const filter = key.split("_")[1].toLocaleLowerCase() as "day" | "week" | "month" | "year";
const startDate = dayjs(eventStartDate).startOf(filter).toDate();
const endDate = dayjs(startDate).endOf(filter).toDate();
const totalBookingDuration = await getTotalBookingDuration({ eventId, startDate, endDate });
if (totalBookingDuration >= limitingNumber) {
// This is used when getting availability
if (returnBusyTimes) {
return {
start: startDate,
end: endDate,
};
}
throw new HttpError({
message: `duration_limit_reached`,
statusCode: 403,
});
}
}
}
+2 -1
View File
@@ -1,4 +1,5 @@
export { checkBookingLimits, checkLimit } from "./checkBookingLimits";
export { checkBookingLimits, checkBookingLimit } from "./checkBookingLimits";
export { checkDurationLimits, checkDurationLimit } from "./checkDurationLimits";
export { defaultHandler } from "./defaultHandler";
export { defaultResponder } from "./defaultResponder";
@@ -0,0 +1,23 @@
import prisma from "@calcom/prisma";
export const getTotalBookingDuration = async ({
eventId,
startDate,
endDate,
}: {
eventId: number;
startDate: Date;
endDate: Date;
}) => {
// Aggregates the total booking time for a given event in a given time period
const [totalBookingTime] = (await prisma.$queryRaw`
SELECT SUM(EXTRACT(EPOCH FROM ("endTime" - "startTime")) / 60) as "totalMinutes"
FROM "Booking"
WHERE "status" = 'accepted'
AND "id" = ${eventId}
AND "startTime" >= ${startDate}
AND "endTime" <= ${endDate};
`) as { totalMinutes: number }[];
return totalBookingTime.totalMinutes;
};
+1
View File
@@ -1 +1,2 @@
export * from "./teams";
export * from "./booking";
+1
View File
@@ -92,6 +92,7 @@ export const buildEventType = (eventType?: Partial<EventType>): EventType => {
schedulingType: null,
scheduleId: null,
bookingLimits: null,
durationLimits: null,
price: 0,
currency: "usd",
slotInterval: null,
@@ -0,0 +1,15 @@
import type { IntervalLimit } from "@calcom/types/Calendar";
const validationOrderKeys = ["PER_DAY", "PER_WEEK", "PER_MONTH", "PER_YEAR"];
export const validateIntervalLimitOrder = (input: IntervalLimit) => {
// Sort 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));
return sorted.every((key, index) => validationOrderWithoutMissing[index] === key);
};
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "EventType" ADD COLUMN "durationLimits" JSONB;
+3 -1
View File
@@ -95,8 +95,10 @@ model EventType {
/// @zod.custom(imports.successRedirectUrl)
successRedirectUrl String?
workflows WorkflowsOnEventTypes[]
/// @zod.custom(imports.bookingLimitsType)
/// @zod.custom(imports.intervalLimitsType)
bookingLimits Json?
/// @zod.custom(imports.intervalLimitsType)
durationLimits Json?
@@unique([userId, slug])
@@unique([teamId, slug])
+1 -1
View File
@@ -114,7 +114,7 @@ export const iso8601 = z.string().transform((val, ctx) => {
return d;
});
export const bookingLimitsType = z
export const intervalLimitsType = z
.object({
PER_DAY: z.number().optional(),
PER_WEEK: z.number().optional(),
@@ -9,7 +9,7 @@ import type { LocationObject } from "@calcom/app-store/locations";
import { DailyLocationType } from "@calcom/app-store/locations";
import { stripeDataSchema } from "@calcom/app-store/stripepayment/lib/server";
import getApps, { getAppFromLocationValue, getAppFromSlug } from "@calcom/app-store/utils";
import { validateBookingLimitOrder } from "@calcom/lib";
import { validateIntervalLimitOrder } from "@calcom/lib";
import { CAL_URL } from "@calcom/lib/constants";
import getEventTypeById from "@calcom/lib/getEventTypeById";
import { baseEventTypeSelect, baseUserSelect } from "@calcom/prisma";
@@ -528,6 +528,7 @@ export const eventTypesRouter = router({
periodType,
locations,
bookingLimits,
durationLimits,
destinationCalendar,
customInputs,
recurringEvent,
@@ -582,12 +583,19 @@ export const eventTypesRouter = router({
}
if (bookingLimits) {
const isValid = validateBookingLimitOrder(bookingLimits);
const isValid = validateIntervalLimitOrder(bookingLimits);
if (!isValid)
throw new TRPCError({ code: "BAD_REQUEST", message: "Booking limits must be in ascending order." });
data.bookingLimits = bookingLimits;
}
if (durationLimits) {
const isValid = validateIntervalLimitOrder(durationLimits);
if (!isValid)
throw new TRPCError({ code: "BAD_REQUEST", message: "Duration limits must be in ascending order." });
data.durationLimits = durationLimits;
}
if (schedule) {
// Check that the schedule belongs to the user
const userScheduleQuery = await ctx.prisma.schedule.findFirst({
@@ -769,6 +777,7 @@ export const eventTypesRouter = router({
team,
recurringEvent,
bookingLimits,
durationLimits,
metadata,
workflows,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -794,6 +803,7 @@ export const eventTypesRouter = router({
users: users ? { connect: users.map((user) => ({ id: user.id })) } : undefined,
recurringEvent: recurringEvent || undefined,
bookingLimits: bookingLimits ?? undefined,
durationLimits: durationLimits ?? undefined,
metadata: metadata === null ? Prisma.DbNull : metadata,
bookingFields: eventType.bookingFields === null ? Prisma.DbNull : eventType.bookingFields,
};
@@ -125,6 +125,7 @@ async function getEventType(ctx: { prisma: typeof prisma }, input: z.infer<typeo
beforeEventBuffer: true,
afterEventBuffer: true,
bookingLimits: true,
durationLimits: true,
schedulingType: true,
periodType: true,
periodStartDate: true,
@@ -263,6 +264,7 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
eventTypeId: input.eventTypeId,
afterEventBuffer: eventType.afterEventBuffer,
beforeEventBuffer: eventType.beforeEventBuffer,
duration: input.duration || 0,
},
{ user: currentUser, eventType, currentSeats }
);
+2 -1
View File
@@ -4,6 +4,7 @@ import type { calendar_v3 } from "googleapis";
import type { Time } from "ical.js";
import type { TFunction } from "next-i18next";
import type { Calendar } from "@calcom/features/calendars/weeklyview";
import type { Frequency } from "@calcom/prisma/zod-utils";
import type { Ensure } from "./utils";
@@ -115,7 +116,7 @@ export interface RecurringEvent {
tzid?: string | undefined;
}
export interface BookingLimit {
export interface IntervalLimit {
PER_DAY?: number | undefined;
PER_WEEK?: number | undefined;
PER_MONTH?: number | undefined;