Feature/booking page refactor (#3035)
* Extracted UI related logic on the DatePicker, stripped out all logic * wip * fixed small regression due to merge * Fix alignment of the chevrons * Added isToday dot, added onMonthChange so we can fetch this month slots * Added includedDates to inverse excludedDates * removed trpcState * Improvements to the state * All params are now dynamic * This builds the flat map so not all paths block on every new build * Added requiresConfirmation * Correctly take into account getFilteredTimes to make the calendar function * Rewritten team availability, seems to work * Circumvent i18n flicker by showing the loader instead * 'You can remove this code. Its not being used now' - Hariom * Nailed a persistent little bug, new Date() caused the current day to flicker on and off * TS fixes * Fix some eventType details in AvailableTimes * '5 / 6 Seats Available' instead of '6 / Seats Available' * More type fixes * Removed unrelated merge artifact * Use WEBAPP_URL instead of hardcoded * Next round of TS fixes * I believe this was mistyped * Temporarily disabled rescheduling 'this is when you originally scheduled', so removed dep * Sorting some dead code * This page has a lot of red, not all related to this PR * A PR to your PR (#3067) * Cleanup * Cleanup * Uses zod to parse params * Type fixes * Fixes ISR * E2E fixes * Disabled dynamic bookings until post v1.7 * More test fixes * Fixed border position (transparent border) to prevent dot from jumping - and possibly fix spacing * Disabled style nitpicks * Delete useSlots.ts Removed early design artifact * Unlock DatePicker locale * Adds mini spinner to DatePicker Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: zomars <[email protected]>
This commit is contained in:
21 files changed
+1052
-573
No files matched your search
@@ -31,6 +31,7 @@ import { apiKeysRouter } from "@server/routers/viewer/apiKeys";
|
||||
import { availabilityRouter } from "@server/routers/viewer/availability";
|
||||
import { bookingsRouter } from "@server/routers/viewer/bookings";
|
||||
import { eventTypesRouter } from "@server/routers/viewer/eventTypes";
|
||||
import { slotsRouter } from "@server/routers/viewer/slots";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter, createRouter } from "../createRouter";
|
||||
@@ -950,4 +951,5 @@ export const viewerRouter = createRouter()
|
||||
.merge("availability.", availabilityRouter)
|
||||
.merge("teams.", viewerTeamsRouter)
|
||||
.merge("webhook.", webhookRouter)
|
||||
.merge("apiKeys.", apiKeysRouter);
|
||||
.merge("apiKeys.", apiKeysRouter)
|
||||
.merge("slots.", slotsRouter);
|
||||
@@ -0,0 +1,256 @@
|
||||
import { SchedulingType } from "@prisma/client";
|
||||
import dayjs, { Dayjs } from "dayjs";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { CurrentSeats } from "@calcom/core/getUserAvailability";
|
||||
import { getUserAvailability } from "@calcom/core/getUserAvailability";
|
||||
import { yyyymmdd } from "@calcom/lib/date-fns";
|
||||
import { availabilityUserSelect } from "@calcom/prisma";
|
||||
import { stringToDayjs } from "@calcom/prisma/zod-utils";
|
||||
import { TimeRange, WorkingHours } from "@calcom/types/schedule";
|
||||
|
||||
import getSlots from "@lib/slots";
|
||||
|
||||
import { createRouter } from "@server/createRouter";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
const getScheduleSchema = z
|
||||
.object({
|
||||
// startTime ISOString
|
||||
startTime: stringToDayjs,
|
||||
// endTime ISOString
|
||||
endTime: stringToDayjs,
|
||||
// Event type ID
|
||||
eventTypeId: z.number().optional(),
|
||||
// or list of users (for dynamic events)
|
||||
usernameList: z.array(z.string()).optional(),
|
||||
})
|
||||
.refine(
|
||||
(data) => !!data.eventTypeId || !!data.usernameList,
|
||||
"Either usernameList or eventTypeId should be filled in."
|
||||
);
|
||||
|
||||
export type Slot = {
|
||||
time: string;
|
||||
attendees?: number;
|
||||
bookingUid?: string;
|
||||
users?: string[];
|
||||
};
|
||||
|
||||
const checkForAvailability = ({
|
||||
time,
|
||||
busy,
|
||||
workingHours,
|
||||
eventLength,
|
||||
beforeBufferTime,
|
||||
afterBufferTime,
|
||||
currentSeats,
|
||||
}: {
|
||||
time: Dayjs;
|
||||
busy: (TimeRange | { start: string; end: string })[];
|
||||
workingHours: WorkingHours[];
|
||||
eventLength: number;
|
||||
beforeBufferTime: number;
|
||||
afterBufferTime: number;
|
||||
currentSeats?: CurrentSeats;
|
||||
}) => {
|
||||
if (
|
||||
!workingHours.every((workingHour) => {
|
||||
if (!workingHour.days.includes(time.day())) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
!time.isBetween(
|
||||
time.utc().startOf("day").add(workingHour.startTime, "minutes"),
|
||||
time.utc().startOf("day").add(workingHour.endTime, "minutes"),
|
||||
null,
|
||||
"[)"
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (currentSeats?.some((booking) => booking.startTime.toISOString() === time.toISOString())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const slotEndTime = time.add(eventLength, "minutes");
|
||||
const slotStartTimeWithBeforeBuffer = time.subtract(beforeBufferTime, "minutes");
|
||||
const slotEndTimeWithAfterBuffer = time.add(eventLength + afterBufferTime, "minutes");
|
||||
|
||||
return busy.every((busyTime): boolean => {
|
||||
const startTime = dayjs(busyTime.start);
|
||||
const endTime = dayjs(busyTime.end);
|
||||
// Check if start times are the same
|
||||
if (time.isBetween(startTime, endTime, null, "[)")) {
|
||||
return false;
|
||||
}
|
||||
// Check if slot end time is between start and end time
|
||||
else if (slotEndTime.isBetween(startTime, endTime)) {
|
||||
return false;
|
||||
}
|
||||
// Check if startTime is between slot
|
||||
else if (startTime.isBetween(time, slotEndTime)) {
|
||||
return false;
|
||||
}
|
||||
// Check if timeslot has before buffer time space free
|
||||
else if (
|
||||
slotStartTimeWithBeforeBuffer.isBetween(
|
||||
startTime.subtract(beforeBufferTime, "minutes"),
|
||||
endTime.add(afterBufferTime, "minutes")
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
// Check if timeslot has after buffer time space free
|
||||
else if (
|
||||
slotEndTimeWithAfterBuffer.isBetween(
|
||||
startTime.subtract(beforeBufferTime, "minutes"),
|
||||
endTime.add(afterBufferTime, "minutes")
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
export const slotsRouter = createRouter().query("getSchedule", {
|
||||
input: getScheduleSchema,
|
||||
async resolve({ input, ctx }) {
|
||||
const eventType = await ctx.prisma.eventType.findUnique({
|
||||
where: {
|
||||
id: input.eventTypeId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
minimumBookingNotice: true,
|
||||
length: true,
|
||||
seatsPerTimeSlot: true,
|
||||
timeZone: true,
|
||||
slotInterval: true,
|
||||
beforeEventBuffer: true,
|
||||
afterEventBuffer: true,
|
||||
schedulingType: true,
|
||||
schedule: {
|
||||
select: {
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
},
|
||||
availability: {
|
||||
select: {
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
days: true,
|
||||
},
|
||||
},
|
||||
users: {
|
||||
select: {
|
||||
username: true,
|
||||
...availabilityUserSelect,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!eventType) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const { startTime, endTime } = input;
|
||||
if (!startTime.isValid() || !endTime.isValid()) {
|
||||
throw new TRPCError({ message: "Invalid time range given.", code: "BAD_REQUEST" });
|
||||
}
|
||||
|
||||
let currentSeats: CurrentSeats | undefined = undefined;
|
||||
|
||||
const userSchedules = await Promise.all(
|
||||
eventType.users.map(async (currentUser) => {
|
||||
const {
|
||||
busy,
|
||||
workingHours,
|
||||
currentSeats: _currentSeats,
|
||||
} = await getUserAvailability(
|
||||
{
|
||||
userId: currentUser.id,
|
||||
dateFrom: startTime.format(),
|
||||
dateTo: endTime.format(),
|
||||
eventTypeId: input.eventTypeId,
|
||||
},
|
||||
{ user: currentUser, eventType, currentSeats }
|
||||
);
|
||||
if (!currentSeats && _currentSeats) currentSeats = _currentSeats;
|
||||
|
||||
return {
|
||||
workingHours,
|
||||
busy,
|
||||
};
|
||||
})
|
||||
);
|
||||
const workingHours = userSchedules.flatMap((s) => s.workingHours);
|
||||
console.log("workingHours", workingHours);
|
||||
console.log("currentSeats", currentSeats);
|
||||
|
||||
const slots: Record<string, Slot[]> = {};
|
||||
|
||||
const availabilityCheckProps = {
|
||||
eventLength: eventType.length,
|
||||
beforeBufferTime: eventType.beforeEventBuffer,
|
||||
afterBufferTime: eventType.afterEventBuffer,
|
||||
currentSeats,
|
||||
};
|
||||
|
||||
let time = dayjs(startTime);
|
||||
do {
|
||||
// get slots retrieves the available times for a given day
|
||||
const times = getSlots({
|
||||
inviteeDate: time,
|
||||
eventLength: eventType.length,
|
||||
workingHours,
|
||||
minimumBookingNotice: eventType.minimumBookingNotice,
|
||||
frequency: eventType.slotInterval || eventType.length,
|
||||
});
|
||||
|
||||
// if ROUND_ROBIN - slots stay available on some() - if normal / COLLECTIVE - slots only stay available on every()
|
||||
const filteredTimes =
|
||||
!eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE
|
||||
? times.filter((time) =>
|
||||
userSchedules.every((schedule) =>
|
||||
checkForAvailability({ time, ...schedule, ...availabilityCheckProps })
|
||||
)
|
||||
)
|
||||
: times.filter((time) =>
|
||||
userSchedules.some((schedule) =>
|
||||
checkForAvailability({ time, ...schedule, ...availabilityCheckProps })
|
||||
)
|
||||
);
|
||||
|
||||
slots[yyyymmdd(time.toDate())] = filteredTimes.map((time) => ({
|
||||
time: time.toISOString(),
|
||||
users: eventType.users.map((user) => user.username || ""),
|
||||
// Conditionally add the attendees and booking id to slots object if there is already a booking during that time
|
||||
...(currentSeats?.some((booking) => booking.startTime.toISOString() === time.toISOString()) && {
|
||||
attendees:
|
||||
currentSeats[
|
||||
currentSeats.findIndex((booking) => booking.startTime.toISOString() === time.toISOString())
|
||||
]._count.attendees,
|
||||
bookingUid:
|
||||
currentSeats[
|
||||
currentSeats.findIndex((booking) => booking.startTime.toISOString() === time.toISOString())
|
||||
].uid,
|
||||
}),
|
||||
}));
|
||||
time = time.add(1, "day");
|
||||
} while (time.isBefore(endTime));
|
||||
|
||||
return {
|
||||
slots,
|
||||
};
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user