Skip to content

Scheduling infrastructure for absolutely everyone.

fix: Prevent duplicate bookings with idempotency key (#13865)

Alex van Andeld85e0b51e46a
diff --git a/apps/web/playwright/booking-pages.e2e.ts b/apps/web/playwright/booking-pages.e2e.ts
index abb2e15c908..80c72fa48b9 100644
--- a/apps/web/playwright/booking-pages.e2e.ts
+++ b/apps/web/playwright/booking-pages.e2e.ts
@@ -175,6 +175,35 @@ testBothFutureAndLegacyRoutes.describe("pro user", () => {
await expect(page.locator('[data-testid="empty-screen"]')).toBeVisible();
});
+ test("can book an unconfirmed event multiple times", async ({ page, users }) => {
+ await page.locator('[data-testid="event-type-link"]:has-text("Opt in")').click();
+ await selectFirstAvailableTimeSlotNextMonth(page);
+
+ const pageUrl = page.url();
+
+ await bookTimeSlot(page);
+ await expect(page.locator("[data-testid=success-page]")).toBeVisible();
+
+ // go back to the booking page to re-book.
+ await page.goto(pageUrl);
+ await bookTimeSlot(page, { email: "[email protected]" });
+ await expect(page.locator("[data-testid=success-page]")).toBeVisible();
+ });
+
+ test("cannot book an unconfirmed event multiple times with the same email", async ({ page, users }) => {
+ await page.locator('[data-testid="event-type-link"]:has-text("Opt in")').click();
+ await selectFirstAvailableTimeSlotNextMonth(page);
+
+ const pageUrl = page.url();
+
+ await bookTimeSlot(page);
+ // go back to the booking page to re-book.
+ await page.goto(pageUrl);
+
+ await bookTimeSlot(page);
+ await expect(page.getByText("Could not book the meeting.")).toBeVisible();
+ });
+
test("can book with multiple guests", async ({ page, users }) => {
const additionalGuests = ["[email protected]", "[email protected]"];
diff --git a/packages/features/bookings/lib/handleNewBooking.ts b/packages/features/bookings/lib/handleNewBooking.ts
index 81faa804c25..a19eecfb7b4 100644
--- a/packages/features/bookings/lib/handleNewBooking.ts
+++ b/packages/features/bookings/lib/handleNewBooking.ts
@@ -1627,6 +1627,19 @@ async function handler(
})
);
+ // update original rescheduled booking (no seats event)
+ if (!eventType.seatsPerTimeSlot && originalRescheduledBooking?.uid) {
+ await prisma.booking.update({
+ where: {
+ id: originalRescheduledBooking.id,
+ },
+ data: {
+ rescheduled: true,
+ status: BookingStatus.CANCELLED,
+ },
+ });
+ }
+
try {
booking = await createBooking({
originalRescheduledBooking,
@@ -1694,7 +1707,7 @@ async function handler(
err.message
);
if (err.code === "P2002") {
- throw new HttpError({ statusCode: 409, message: "booking.conflict" });
+ throw new HttpError({ statusCode: 409, message: "booking_conflict" });
}
throw err;
}
@@ -1720,20 +1733,7 @@ async function handler(
evt = addVideoCallDataToEvent(originalRescheduledBooking.references, evt);
- //update original rescheduled booking (no seats event)
- if (!eventType.seatsPerTimeSlot) {
- await prisma.booking.update({
- where: {
- id: originalRescheduledBooking.id,
- },
- data: {
- rescheduled: true,
- status: BookingStatus.CANCELLED,
- },
- });
- }
-
- const newDesinationCalendar = evt.destinationCalendar;
+ const newDestinationCalendar = evt.destinationCalendar;
evt.destinationCalendar = originalRescheduledBooking?.destinationCalendar
? [originalRescheduledBooking?.destinationCalendar]
@@ -1752,7 +1752,7 @@ async function handler(
originalRescheduledBooking.uid,
undefined,
changedOrganizer,
- newDesinationCalendar
+ newDestinationCalendar
);
// This gets overridden when updating the event - to check if notes have been hidden or not. We just reset this back
diff --git a/packages/lib/test/builder.ts b/packages/lib/test/builder.ts
index ee412e9f48c..6865cc3881b 100644
--- a/packages/lib/test/builder.ts
+++ b/packages/lib/test/builder.ts
@@ -38,6 +38,7 @@ export const buildBooking = (booking?: Partial<Booking>): Booking => {
uid,
userId: null,
eventTypeId: null,
+ idempotencyKey: null,
userPrimaryEmail: null,
title: faker.lorem.sentence(),
description: faker.lorem.paragraph(),
diff --git a/packages/prisma/extensions/booking-idempotency-key.ts b/packages/prisma/extensions/booking-idempotency-key.ts
new file mode 100644
index 00000000000..f108df14d26
--- /dev/null
+++ b/packages/prisma/extensions/booking-idempotency-key.ts
@@ -0,0 +1,38 @@
+import { Prisma } from "@prisma/client";
+import { v5 as uuidv5 } from "uuid";
+
+import { BookingStatus } from "@calcom/prisma/enums";
+
+export function bookingIdempotencyKeyExtension() {
+ return Prisma.defineExtension({
+ query: {
+ booking: {
+ async create({ args, query }) {
+ const uniqueEmailJoinInput: string[] = [];
+ if (args.data.attendees?.create && !Array.isArray(args.data.attendees?.create)) {
+ uniqueEmailJoinInput.push(args.data.attendees?.create.email);
+ }
+ if (args.data.attendees?.createMany && Array.isArray(args.data.attendees?.createMany.data)) {
+ uniqueEmailJoinInput.push(...args.data.attendees?.createMany.data.map((record) => record.email));
+ }
+ const idempotencyKey = uuidv5(
+ `${
+ args.data.eventType?.connect?.id
+ }.${args.data.startTime.valueOf()}.${args.data.endTime.valueOf()}.${uniqueEmailJoinInput.join(
+ ","
+ )}`,
+ uuidv5.URL
+ );
+ args.data.idempotencyKey = idempotencyKey;
+ return query(args);
+ },
+ async update({ args, query }) {
+ if (args.data.status === BookingStatus.CANCELLED || args.data.status === BookingStatus.REJECTED) {
+ args.data.idempotencyKey = null;
+ }
+ return query(args);
+ },
+ },
+ },
+ });
+}
diff --git a/packages/prisma/index.ts b/packages/prisma/index.ts
index 86c28c19e68..88722eff4e0 100644
--- a/packages/prisma/index.ts
+++ b/packages/prisma/index.ts
@@ -2,6 +2,7 @@ import type { Prisma } from "@prisma/client";
import { PrismaClient as PrismaClientWithoutExtension } from "@prisma/client";
import { withAccelerate } from "@prisma/extension-accelerate";
+import { bookingIdempotencyKeyExtension } from "./extensions/booking-idempotency-key";
import { excludePendingPaymentsExtension } from "./extensions/exclude-pending-payment-teams";
import { bookingReferenceMiddleware } from "./middleware";
@@ -21,6 +22,7 @@ const prismaWithoutClientExtensions =
export const customPrisma = (options?: Prisma.PrismaClientOptions) =>
new PrismaClientWithoutExtension({ ...prismaOptions, ...options })
.$extends(excludePendingPaymentsExtension())
+ .$extends(bookingIdempotencyKeyExtension())
.$extends(withAccelerate());
// If any changed on middleware server restart is required
@@ -31,6 +33,7 @@ bookingReferenceMiddleware(prismaWithoutClientExtensions);
// Specifically we get errors like `Type 'string | Date | null | undefined' is not assignable to type 'Exact<string | Date | null | undefined, string | Date | null | undefined>'`
const prismaWithClientExtensions = prismaWithoutClientExtensions
.$extends(excludePendingPaymentsExtension())
+ .$extends(bookingIdempotencyKeyExtension())
.$extends(withAccelerate());
export const prisma = globalForPrisma.prismaWithClientExtensions || prismaWithClientExtensions;
diff --git a/packages/prisma/migrations/20240226125946_add_idempotency_key/migration.sql b/packages/prisma/migrations/20240226125946_add_idempotency_key/migration.sql
new file mode 100644
index 00000000000..e6138ef333b
--- /dev/null
+++ b/packages/prisma/migrations/20240226125946_add_idempotency_key/migration.sql
@@ -0,0 +1,11 @@
+/*
+ Warnings:
+
+ - A unique constraint covering the columns `[idempotencyKey]` on the table `Booking` will be added. If there are existing duplicate values, this will fail.
+
+*/
+-- AlterTable
+ALTER TABLE "Booking" ADD COLUMN "idempotencyKey" TEXT;
+
+-- CreateIndex
+CREATE UNIQUE INDEX "Booking_idempotencyKey_key" ON "Booking"("idempotencyKey");
diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma
index 368258a027e..b05d0188d30 100644
--- a/packages/prisma/schema.prisma
+++ b/packages/prisma/schema.prisma
@@ -462,6 +462,8 @@ enum BookingStatus {
model Booking {
id Int @id @default(autoincrement())
uid String @unique
+ // (optional) UID based on slot start/end time & email against duplicates
+ idempotencyKey String? @unique
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int?
// User's email at the time of booking