fix: disregarding already booked spots or blocked calendar times (#2029)
* fix: double booking * fix: update double-booking error response code * fix: update double-booking error response code * test: add test * fix: check availability before creating booking * Update apps/web/playwright/booking-pages.test.ts * Update yarn.lock * Restored missing fix Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> Co-authored-by: Omar López <[email protected]>
This commit is contained in:
4 files changed
+177
-85
No files matched your search
@@ -540,7 +540,9 @@ const BookingPage = (props: BookingPageProps) => {
|
||||
</div>
|
||||
</Form>
|
||||
{mutation.isError && (
|
||||
<div className="mt-2 border-l-4 border-yellow-400 bg-yellow-50 p-4">
|
||||
<div
|
||||
data-testid="booking-fail"
|
||||
className="mt-2 border-l-4 border-yellow-400 bg-yellow-50 p-4">
|
||||
<div className="flex">
|
||||
<div className="flex-shrink-0">
|
||||
<ExclamationIcon className="h-5 w-5 text-yellow-400" aria-hidden="true" />
|
||||
|
||||
@@ -21,6 +21,7 @@ import { getErrorFromUnknown } from "@lib/errors";
|
||||
import { getEventName } from "@lib/event";
|
||||
import EventManager, { EventResult, PartialReference } from "@lib/events/EventManager";
|
||||
import { getBusyCalendarTimes } from "@lib/integrations/calendar/CalendarManager";
|
||||
import { EventBusyDate } from "@lib/integrations/calendar/constants/types";
|
||||
import { CalendarEvent, AdditionInformation } from "@lib/integrations/calendar/interfaces/Calendar";
|
||||
import { BufferedBusyTime } from "@lib/integrations/calendar/interfaces/Office365Calendar";
|
||||
import logger from "@lib/logger";
|
||||
@@ -408,27 +409,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
});
|
||||
}
|
||||
|
||||
type Booking = Prisma.PromiseReturnType<typeof createBooking>;
|
||||
let booking: Booking | null = null;
|
||||
try {
|
||||
booking = await createBooking();
|
||||
evt.uid = booking.uid;
|
||||
} catch (_err) {
|
||||
const err = getErrorFromUnknown(_err);
|
||||
log.error(`Booking ${eventTypeId} failed`, "Error when saving booking to db", err.message);
|
||||
if (err.code === "P2002") {
|
||||
res.status(409).json({ message: "booking.conflict" });
|
||||
return;
|
||||
}
|
||||
res.status(500).end();
|
||||
return;
|
||||
}
|
||||
|
||||
let results: EventResult[] = [];
|
||||
let referencesToCreate: PartialReference[] = [];
|
||||
let user: User | null = null;
|
||||
|
||||
/** Let's start cheking for availability */
|
||||
/** Let's start checking for availability */
|
||||
for (const currentUser of users) {
|
||||
if (!currentUser) {
|
||||
console.error(`currentUser not found`);
|
||||
@@ -443,68 +428,94 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
});
|
||||
|
||||
const credentials = currentUser.credentials;
|
||||
const calendarBusyTimes: EventBusyDate[] = await prisma.booking
|
||||
.findMany({
|
||||
where: {
|
||||
userId: currentUser.id,
|
||||
eventTypeId: eventTypeId,
|
||||
},
|
||||
})
|
||||
.then((bookings) => bookings.map((booking) => ({ end: booking.endTime, start: booking.startTime })));
|
||||
|
||||
if (credentials) {
|
||||
const calendarBusyTimes = await getBusyCalendarTimes(
|
||||
credentials,
|
||||
reqBody.start,
|
||||
reqBody.end,
|
||||
selectedCalendars
|
||||
await getBusyCalendarTimes(credentials, reqBody.start, reqBody.end, selectedCalendars).then(
|
||||
(busyTimes) => calendarBusyTimes.push(...busyTimes)
|
||||
);
|
||||
|
||||
const videoBusyTimes = (await getBusyVideoTimes(credentials)).filter(notEmpty);
|
||||
calendarBusyTimes.push(...videoBusyTimes);
|
||||
console.log("calendarBusyTimes==>>>", calendarBusyTimes);
|
||||
|
||||
const bufferedBusyTimes: BufferedBusyTimes = calendarBusyTimes.map((a) => ({
|
||||
start: dayjs(a.start).subtract(currentUser.bufferTime, "minute").toString(),
|
||||
end: dayjs(a.end).add(currentUser.bufferTime, "minute").toString(),
|
||||
}));
|
||||
|
||||
let isAvailableToBeBooked = true;
|
||||
try {
|
||||
isAvailableToBeBooked = isAvailable(bufferedBusyTimes, reqBody.start, eventType.length);
|
||||
} catch {
|
||||
log.debug({
|
||||
message: "Unable set isAvailableToBeBooked. Using true. ",
|
||||
});
|
||||
}
|
||||
|
||||
if (!isAvailableToBeBooked) {
|
||||
const error = {
|
||||
errorCode: "BookingUserUnAvailable",
|
||||
message: `${currentUser.name} is unavailable at this time.`,
|
||||
};
|
||||
|
||||
log.debug(`Booking ${currentUser.name} failed`, error);
|
||||
}
|
||||
|
||||
let timeOutOfBounds = false;
|
||||
|
||||
try {
|
||||
timeOutOfBounds = isOutOfBounds(reqBody.start, {
|
||||
periodType: eventType.periodType,
|
||||
periodDays: eventType.periodDays,
|
||||
periodEndDate: eventType.periodEndDate,
|
||||
periodStartDate: eventType.periodStartDate,
|
||||
periodCountCalendarDays: eventType.periodCountCalendarDays,
|
||||
timeZone: currentUser.timeZone,
|
||||
});
|
||||
} catch {
|
||||
log.debug({
|
||||
message: "Unable set timeOutOfBounds. Using false. ",
|
||||
});
|
||||
}
|
||||
|
||||
if (timeOutOfBounds) {
|
||||
const error = {
|
||||
errorCode: "BookingUserUnAvailable",
|
||||
message: `${currentUser.name} is unavailable at this time.`,
|
||||
};
|
||||
|
||||
log.debug(`Booking ${currentUser.name} failed`, error);
|
||||
res.status(400).json(error);
|
||||
}
|
||||
}
|
||||
|
||||
console.log("calendarBusyTimes==>>>", calendarBusyTimes);
|
||||
|
||||
const bufferedBusyTimes: BufferedBusyTimes = calendarBusyTimes.map((a) => ({
|
||||
start: dayjs(a.start).subtract(currentUser.bufferTime, "minute").toString(),
|
||||
end: dayjs(a.end).add(currentUser.bufferTime, "minute").toString(),
|
||||
}));
|
||||
|
||||
let isAvailableToBeBooked = true;
|
||||
try {
|
||||
isAvailableToBeBooked = isAvailable(bufferedBusyTimes, reqBody.start, eventType.length);
|
||||
} catch {
|
||||
log.debug({
|
||||
message: "Unable set isAvailableToBeBooked. Using true. ",
|
||||
});
|
||||
}
|
||||
|
||||
if (!isAvailableToBeBooked) {
|
||||
const error = {
|
||||
errorCode: "BookingUserUnAvailable",
|
||||
message: `${currentUser.name} is unavailable at this time.`,
|
||||
};
|
||||
|
||||
log.debug(`Booking ${currentUser.name} failed`, error);
|
||||
res.status(409).json(error);
|
||||
return;
|
||||
}
|
||||
|
||||
let timeOutOfBounds = false;
|
||||
|
||||
try {
|
||||
timeOutOfBounds = isOutOfBounds(reqBody.start, {
|
||||
periodType: eventType.periodType,
|
||||
periodDays: eventType.periodDays,
|
||||
periodEndDate: eventType.periodEndDate,
|
||||
periodStartDate: eventType.periodStartDate,
|
||||
periodCountCalendarDays: eventType.periodCountCalendarDays,
|
||||
timeZone: currentUser.timeZone,
|
||||
});
|
||||
} catch {
|
||||
log.debug({
|
||||
message: "Unable set timeOutOfBounds. Using false. ",
|
||||
});
|
||||
}
|
||||
|
||||
if (timeOutOfBounds) {
|
||||
const error = {
|
||||
errorCode: "BookingUserUnAvailable",
|
||||
message: `${currentUser.name} is unavailable at this time.`,
|
||||
};
|
||||
|
||||
log.debug(`Booking ${currentUser.name} failed`, error);
|
||||
res.status(400).json(error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
type Booking = Prisma.PromiseReturnType<typeof createBooking>;
|
||||
let booking: Booking | null = null;
|
||||
try {
|
||||
booking = await createBooking();
|
||||
evt.uid = booking.uid;
|
||||
} catch (_err) {
|
||||
const err = getErrorFromUnknown(_err);
|
||||
log.error(`Booking ${eventTypeId} failed`, "Error when saving booking to db", err.message);
|
||||
if (err.code === "P2002") {
|
||||
res.status(409).json({ message: "booking.conflict" });
|
||||
return;
|
||||
}
|
||||
res.status(500).end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!user) throw Error("Can't continue, user not found.");
|
||||
|
||||
@@ -1,16 +1,80 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import prisma from "@lib/prisma";
|
||||
|
||||
import { todo } from "./lib/testUtils";
|
||||
|
||||
const deleteBookingsByEmail = async (email: string) =>
|
||||
prisma.booking.deleteMany({
|
||||
where: {
|
||||
user: {
|
||||
email,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
test.describe("free user", () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto("/free");
|
||||
});
|
||||
|
||||
test.afterEach(async () => {
|
||||
// delete test bookings
|
||||
await deleteBookingsByEmail("[email protected]");
|
||||
});
|
||||
|
||||
test("only one visible event", async ({ page }) => {
|
||||
await expect(page.locator(`[href="/free/30min"]`)).toBeVisible();
|
||||
await expect(page.locator(`[href="/free/60min"]`)).not.toBeVisible();
|
||||
});
|
||||
|
||||
test("cannot book same slot multiple times", async ({ page }) => {
|
||||
// Click first event type
|
||||
await page.click('[data-testid="event-type-link"]');
|
||||
// Click [data-testid="incrementMonth"]
|
||||
await page.click('[data-testid="incrementMonth"]');
|
||||
// Click [data-testid="day"]
|
||||
await page.click('[data-testid="day"][data-disabled="false"]');
|
||||
// Click [data-testid="time"]
|
||||
await page.click('[data-testid="time"]');
|
||||
|
||||
// Navigate to book page
|
||||
await page.waitForNavigation({
|
||||
url(url) {
|
||||
return url.pathname.endsWith("/book");
|
||||
},
|
||||
});
|
||||
|
||||
// save booking url
|
||||
const bookingUrl: string = page.url();
|
||||
|
||||
const bookTimeSlot = async () => {
|
||||
// --- fill form
|
||||
await page.fill('[name="name"]', "Test Testson");
|
||||
await page.fill('[name="email"]', "[email protected]");
|
||||
await page.press('[name="email"]', "Enter");
|
||||
};
|
||||
|
||||
// book same time spot twice
|
||||
await bookTimeSlot();
|
||||
|
||||
// Make sure we're navigated to the success page
|
||||
await page.waitForNavigation({
|
||||
url(url) {
|
||||
return url.pathname.endsWith("/success");
|
||||
},
|
||||
});
|
||||
|
||||
// return to same time spot booking page
|
||||
await page.goto(bookingUrl);
|
||||
|
||||
// book same time spot again
|
||||
await bookTimeSlot();
|
||||
|
||||
// check for error message
|
||||
await expect(page.locator("[data-testid=booking-fail]")).toBeVisible();
|
||||
});
|
||||
|
||||
todo("`/free/30min` is bookable");
|
||||
|
||||
todo("`/free/60min` is not bookable");
|
||||
@@ -21,6 +85,11 @@ test.describe("pro user", () => {
|
||||
await page.goto("/pro");
|
||||
});
|
||||
|
||||
test.afterEach(async () => {
|
||||
// delete test bookings
|
||||
await deleteBookingsByEmail("[email protected]");
|
||||
});
|
||||
|
||||
test("pro user's page has at least 2 visible events", async ({ page }) => {
|
||||
const $eventTypes = await page.$$("[data-testid=event-types] > *");
|
||||
expect($eventTypes.length).toBeGreaterThanOrEqual(2);
|
||||
|
||||
Reference in new issue
Block a user