Availabilty consolitadion (#3010)
This commit is contained in:
1 parent
1f1e364a30
commit
22d2bae46b
28 files changed
+553
-519
No files matched your search
@@ -0,0 +1,46 @@
|
||||
import { BookingStatus, Credential, SelectedCalendar } from "@prisma/client";
|
||||
|
||||
import { getBusyCalendarTimes } from "@calcom/core/CalendarManager";
|
||||
import { getBusyVideoTimes } from "@calcom/core/videoClient";
|
||||
import notEmpty from "@calcom/lib/notEmpty";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { EventBusyDate } from "@calcom/types/Calendar";
|
||||
|
||||
export async function getBusyTimes(params: {
|
||||
credentials: Credential[];
|
||||
userId: number;
|
||||
eventTypeId?: number;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
selectedCalendars: SelectedCalendar[];
|
||||
}) {
|
||||
const { credentials, userId, eventTypeId, startTime, endTime, selectedCalendars } = params;
|
||||
const busyTimes: EventBusyDate[] = await prisma.booking
|
||||
.findMany({
|
||||
where: {
|
||||
userId,
|
||||
eventTypeId,
|
||||
startTime: { gte: new Date(startTime) },
|
||||
endTime: { lte: new Date(endTime) },
|
||||
status: {
|
||||
in: [BookingStatus.ACCEPTED],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
},
|
||||
})
|
||||
.then((bookings) => bookings.map(({ startTime, endTime }) => ({ end: endTime, start: startTime })));
|
||||
|
||||
if (credentials) {
|
||||
const calendarBusyTimes = await getBusyCalendarTimes(credentials, startTime, endTime, selectedCalendars);
|
||||
busyTimes.push(...calendarBusyTimes);
|
||||
const videoBusyTimes = (await getBusyVideoTimes(credentials)).filter(notEmpty);
|
||||
busyTimes.push(...videoBusyTimes);
|
||||
}
|
||||
|
||||
return busyTimes;
|
||||
}
|
||||
|
||||
export default getBusyTimes;
|
||||
@@ -0,0 +1,145 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import dayjs from "dayjs";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getWorkingHours } from "@calcom/lib/availability";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma, { availabilityUserSelect } from "@calcom/prisma";
|
||||
import { stringToDayjs } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { getBusyTimes } from "./getBusyTimes";
|
||||
|
||||
const availabilitySchema = z
|
||||
.object({
|
||||
dateFrom: stringToDayjs,
|
||||
dateTo: stringToDayjs,
|
||||
eventTypeId: z.number().optional(),
|
||||
timezone: z.string().optional(),
|
||||
username: z.string().optional(),
|
||||
userId: z.number().optional(),
|
||||
})
|
||||
.refine((data) => !!data.username || !!data.userId, "Either username or userId should be filled in.");
|
||||
|
||||
const getEventType = (id: number) =>
|
||||
prisma.eventType.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
seatsPerTimeSlot: true,
|
||||
timeZone: true,
|
||||
schedule: {
|
||||
select: {
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
availability: {
|
||||
select: {
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
days: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
type EventType = Awaited<ReturnType<typeof getEventType>>;
|
||||
|
||||
const getUser = (where: Prisma.UserWhereUniqueInput) =>
|
||||
prisma.user.findUnique({
|
||||
where,
|
||||
select: availabilityUserSelect,
|
||||
});
|
||||
|
||||
type User = Awaited<ReturnType<typeof getUser>>;
|
||||
|
||||
export async function getUserAvailability(
|
||||
query: ({ username: string } | { userId: number }) & {
|
||||
dateFrom: string;
|
||||
dateTo: string;
|
||||
eventTypeId?: number;
|
||||
timezone?: string;
|
||||
},
|
||||
initialData?: {
|
||||
user?: User;
|
||||
eventType?: EventType;
|
||||
}
|
||||
) {
|
||||
const { username, userId, dateFrom, dateTo, eventTypeId, timezone } = availabilitySchema.parse(query);
|
||||
|
||||
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);
|
||||
|
||||
const { selectedCalendars, ...currentUser } = user;
|
||||
|
||||
const busyTimes = await getBusyTimes({
|
||||
credentials: currentUser.credentials,
|
||||
startTime: dateFrom.toISOString(),
|
||||
endTime: dateTo.toISOString(),
|
||||
eventTypeId,
|
||||
userId: currentUser.id,
|
||||
selectedCalendars,
|
||||
});
|
||||
|
||||
const bufferedBusyTimes = busyTimes.map((a) => ({
|
||||
start: dayjs(a.start).subtract(currentUser.bufferTime, "minute").toISOString(),
|
||||
end: dayjs(a.end).add(currentUser.bufferTime, "minute").toISOString(),
|
||||
}));
|
||||
|
||||
const timeZone = timezone || eventType?.timeZone || currentUser.timeZone;
|
||||
|
||||
const schedule = eventType?.schedule
|
||||
? { ...eventType?.schedule }
|
||||
: {
|
||||
...currentUser.schedules.filter(
|
||||
(schedule) => !currentUser.defaultScheduleId || schedule.id === currentUser.defaultScheduleId
|
||||
)[0],
|
||||
};
|
||||
|
||||
const workingHours = getWorkingHours(
|
||||
{ timeZone },
|
||||
schedule.availability ||
|
||||
(eventType?.availability.length ? eventType.availability : currentUser.availability)
|
||||
);
|
||||
|
||||
/* 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;
|
||||
if (eventType?.seatsPerTimeSlot) {
|
||||
currentSeats = await prisma.booking.findMany({
|
||||
where: {
|
||||
eventTypeId: eventTypeId,
|
||||
startTime: {
|
||||
gte: dateFrom.format(),
|
||||
lte: dateTo.format(),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
uid: true,
|
||||
startTime: true,
|
||||
_count: {
|
||||
select: {
|
||||
attendees: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
busy: bufferedBusyTimes,
|
||||
timeZone,
|
||||
workingHours,
|
||||
currentSeats,
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./CalendarManager";
|
||||
export * from "./EventManager";
|
||||
export { default as getBusyTimes } from "./getBusyTimes";
|
||||
export * from "./videoClient";
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { EventTypeCustomInput } from "@prisma/client";
|
||||
import { PeriodType, SchedulingType, UserPlan } from "@prisma/client";
|
||||
import { PeriodType, Prisma, SchedulingType, UserPlan } from "@prisma/client";
|
||||
|
||||
import { baseUserSelect } from "@calcom/prisma/selects";
|
||||
|
||||
const userSelectData = Prisma.validator<Prisma.UserArgs>()({ select: baseUserSelect });
|
||||
type User = Prisma.UserGetPayload<typeof userSelectData>;
|
||||
|
||||
const availability = [
|
||||
{
|
||||
@@ -81,7 +86,13 @@ const commons = {
|
||||
theme: null,
|
||||
brandColor: "#292929",
|
||||
darkBrandColor: "#fafafa",
|
||||
},
|
||||
availability: [],
|
||||
selectedCalendars: [],
|
||||
startTime: 0,
|
||||
endTime: 0,
|
||||
schedules: [],
|
||||
defaultScheduleId: null,
|
||||
} as User,
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
import { userSelect } from "@calcom/prisma";
|
||||
|
||||
type User = Prisma.UserGetPayload<typeof userSelect>;
|
||||
|
||||
export function getLuckyUsers(
|
||||
users: User[],
|
||||
bookingCounts: {
|
||||
username: string | null;
|
||||
bookingCount: number;
|
||||
}[]
|
||||
) {
|
||||
if (!bookingCounts.length) users.slice(0, 1);
|
||||
|
||||
const [firstMostAvailableUser] = bookingCounts.sort((a, b) => (a.bookingCount > b.bookingCount ? 1 : -1));
|
||||
const luckyUser = users.find((user) => user.username === firstMostAvailableUser?.username);
|
||||
return luckyUser ? [luckyUser] : users;
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
export { getLuckyUsers } from "./getLuckyUsers";
|
||||
export { default as isPrismaObj, isPrismaObjOrUndefined } from "./isPrismaObj";
|
||||
export * from "./isRecurringEvent";
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
type Handlers = {
|
||||
[method in "GET" | "POST" | "PATCH" | "PUT" | "DELETE"]?: Promise<{ default: NextApiHandler }>;
|
||||
};
|
||||
|
||||
/** Allows us to split big API handlers by method and auto catch unsupported methods */
|
||||
const defaultHandler = (handlers: Handlers) => async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const handler = (await handlers[req.method as keyof typeof handlers])?.default;
|
||||
|
||||
if (!handler) return res.status(405).json({ message: "Method not allowed" });
|
||||
|
||||
try {
|
||||
await handler(req, res);
|
||||
return;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return res.status(500).json({ message: "Something went wrong" });
|
||||
}
|
||||
};
|
||||
|
||||
export default defaultHandler;
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { performance } from "perf_hooks";
|
||||
|
||||
import { perfObserver } from ".";
|
||||
import { getServerErrorFromUnkown } from "./getServerErrorFromUnkown";
|
||||
|
||||
type Handle<T> = (req: NextApiRequest, res: NextApiResponse) => Promise<T>;
|
||||
|
||||
perfObserver.observe({ entryTypes: ["measure"], buffered: true });
|
||||
|
||||
/** Allows us to get type inference from API handler responses */
|
||||
function defaultResponder<T>(f: Handle<T>) {
|
||||
return async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
try {
|
||||
performance.mark("Start");
|
||||
const result = await f(req, res);
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
const error = getServerErrorFromUnkown(err);
|
||||
res.statusCode = error.statusCode;
|
||||
res.json({ message: error.message });
|
||||
} finally {
|
||||
performance.mark("End");
|
||||
performance.measure("Measuring endpoint: " + req.url, "Start", "End");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default defaultResponder;
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import Stripe from "stripe";
|
||||
import { ZodError } from "zod";
|
||||
|
||||
import { HttpError } from "../http-error";
|
||||
|
||||
export function getServerErrorFromUnkown(cause: unknown): HttpError {
|
||||
if (cause instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
return new HttpError({ statusCode: 400, message: cause.message, cause });
|
||||
}
|
||||
if (cause instanceof Error) {
|
||||
return new HttpError({ statusCode: 500, message: cause.message, cause });
|
||||
}
|
||||
if (cause instanceof HttpError) {
|
||||
return cause;
|
||||
}
|
||||
if (cause instanceof Stripe.errors.StripeInvalidRequestError) {
|
||||
return new HttpError({ statusCode: 400, message: cause.message, cause });
|
||||
}
|
||||
if (cause instanceof ZodError) {
|
||||
return new HttpError({ statusCode: 400, message: cause.message, cause });
|
||||
}
|
||||
if (typeof cause === "string") {
|
||||
// @ts-expect-error https://github.com/tc39/proposal-error-cause
|
||||
return new Error(cause, { cause });
|
||||
}
|
||||
|
||||
return new HttpError({ statusCode: 500, message: `Unhandled error of type '${typeof cause}'` });
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export { default as defaultHandler } from "./defaultHandler";
|
||||
export { default as defaultResponder } from "./defaultResponder";
|
||||
export { getServerErrorFromUnkown } from "./getServerErrorFromUnkown";
|
||||
export { getTranslation } from "./i18n";
|
||||
export { default as perfObserver } from "./perfObserver";
|
||||
@@ -0,0 +1,20 @@
|
||||
import { PerformanceObserver } from "perf_hooks";
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line no-var
|
||||
var perfObserver: PerformanceObserver | undefined;
|
||||
}
|
||||
|
||||
export const perfObserver =
|
||||
globalThis.perfObserver ||
|
||||
new PerformanceObserver((items) => {
|
||||
items.getEntries().forEach((entry) => {
|
||||
console.log(entry); // fake call to our custom logging solution
|
||||
});
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
globalThis.perfObserver = perfObserver;
|
||||
}
|
||||
|
||||
export default perfObserver;
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from "./booking";
|
||||
export * from "./event-types";
|
||||
export * from "./user";
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
export const availabilityUserSelect = Prisma.validator<Prisma.UserSelect>()({
|
||||
credentials: true,
|
||||
timeZone: true,
|
||||
bufferTime: true,
|
||||
availability: true,
|
||||
id: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
selectedCalendars: true,
|
||||
schedules: {
|
||||
select: {
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
defaultScheduleId: true,
|
||||
});
|
||||
|
||||
export const baseUserSelect = Prisma.validator<Prisma.UserSelect>()({
|
||||
email: true,
|
||||
name: true,
|
||||
username: true,
|
||||
destinationCalendar: true,
|
||||
locale: true,
|
||||
plan: true,
|
||||
avatar: true,
|
||||
hideBranding: true,
|
||||
theme: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
...availabilityUserSelect,
|
||||
});
|
||||
|
||||
export const userSelect = Prisma.validator<Prisma.UserArgs>()({
|
||||
select: {
|
||||
email: true,
|
||||
name: true,
|
||||
username: true,
|
||||
destinationCalendar: true,
|
||||
locale: true,
|
||||
plan: true,
|
||||
avatar: true,
|
||||
hideBranding: true,
|
||||
theme: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
...availabilityUserSelect,
|
||||
},
|
||||
});
|
||||
@@ -56,3 +56,39 @@ export const stringOrNumber = z.union([
|
||||
]);
|
||||
|
||||
export const stringToDayjs = z.string().transform((val) => dayjs(val));
|
||||
|
||||
export const bookingCreateBodySchema = z.object({
|
||||
email: z.string(),
|
||||
end: z.string(),
|
||||
web3Details: z
|
||||
.object({
|
||||
userWallet: z.string(),
|
||||
userSignature: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
eventTypeId: z.number(),
|
||||
eventTypeSlug: z.string(),
|
||||
guests: z.array(z.string()).optional(),
|
||||
location: z.string(),
|
||||
name: z.string(),
|
||||
notes: z.string().optional(),
|
||||
rescheduleUid: z.string().optional(),
|
||||
recurringEventId: z.string().optional(),
|
||||
start: z.string(),
|
||||
timeZone: z.string(),
|
||||
user: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
language: z.string(),
|
||||
bookingUid: z.string().optional(),
|
||||
customInputs: z.array(z.object({ label: z.string(), value: z.union([z.string(), z.boolean()]) })),
|
||||
metadata: z.record(z.string()),
|
||||
hasHashedBookingLink: z.boolean(),
|
||||
hashedLink: z.string().nullish(),
|
||||
});
|
||||
|
||||
export const extendedBookingCreateBody = bookingCreateBodySchema.merge(
|
||||
z.object({
|
||||
noEmail: z.boolean().optional(),
|
||||
recurringCount: z.number().optional(),
|
||||
rescheduleReason: z.string().optional(),
|
||||
})
|
||||
);
|
||||
Reference in new issue
Block a user