Skip to content

Comments

fix: Prevent double bookings with recurring booking links#22803

Closed
naaa760 wants to merge 3 commits intocalcom:mainfrom
naaa760:fix/prevent-duplicate-recurring-bookings
Closed

fix: Prevent double bookings with recurring booking links#22803
naaa760 wants to merge 3 commits intocalcom:mainfrom
naaa760:fix/prevent-duplicate-recurring-bookings

Conversation

@naaa760
Copy link
Contributor

@naaa760 naaa760 commented Jul 30, 2025

What does this PR do?

  • This PR fixes a critical bug where users could create duplicate (double) bookings for the same time slot when using recurring booking links. The issue occurred due to race conditions in the booking system where multiple users could book the same slot simultaneously, bypassing the availability checks.

#CLOSES: #22801

  • Fixes double booking issue with recurring booking links
  • Prevents overlapping bookings at the database level
  • Adds comprehensive conflict checking for both regular and recurring bookings

Visual Demo

Before the Fix:

  • Users could create multiple bookings for the same time slot
  • Calendar showed overlapping events
  • No conflict warnings were triggered
  • Recurring booking links allowed double bookings

After the Fix:

  • Database-level overlap checking prevents double bookings
  • Users receive clear error messages when attempting to book occupied slots
  • Recurring booking links respect the same conflict prevention logic
  • Calendar shows accurate availability

How should this be tested?

Environment Setup:

  • Set up a Cal.com instance with recurring booking links enabled
  • Create an event type with limited availability

Test Steps:

  1. Test Regular Booking Conflict:

    • Book a time slot through the regular booking flow
    • Attempt to book the same slot again
    • Verify that the second booking is rejected with an appropriate error
  2. Test Recurring Booking Conflict:

    • Create a recurring booking link
    • Book a time slot using the recurring link
    • Attempt to book the same slot using the same recurring link
    • Verify that the second booking is rejected
  3. Test Race Condition:

    • Have multiple users attempt to book the same slot simultaneously
    • Verify that only one booking succeeds and others are rejected

Expected Behavior:

  • First booking should succeed
  • Subsequent booking attempts for the same slot should fail with "Time slot is no longer available" error
  • Database should contain only one booking per time slot

Files Modified

  1. packages/features/bookings/lib/handleNewBooking/createBooking.ts
  2. packages/features/bookings/lib/handleNewRecurringBooking.ts

naaa760 added 2 commits July 30, 2025 10:44
…base transaction

Added imports for HttpError and ErrorCode
Added imports for HttpError, ErrorCode, prisma, and BookingStatus
@naaa760 naaa760 requested a review from a team as a code owner July 30, 2025 05:20
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 30, 2025

Walkthrough

The changes introduce explicit overlap checks for both single and recurring bookings. In createBooking.ts, a new function checks if the requested booking time conflicts with any existing accepted or pending bookings of the same event type, throwing a conflict error if overlaps are found. This check is integrated into the booking creation flow. Similarly, in handleNewRecurringBooking.ts, a helper function iterates over all recurring booking dates and performs the same overlap check for each, ensuring no time slot is double-booked. No other logic or control flow outside these additions was modified.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Assessment against linked issues

Objective Addressed Explanation
Prevent duplicate/double bookings for the same slot via recurring booking links (#22801)
Overlap check for single bookings to block double-booking (#22801)
Return error/conflict when a user attempts to book an already-booked slot (#22801)
Ensure recurring booking logic matches single booking logic for overlap prevention (#22801)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@graphite-app graphite-app bot requested a review from a team July 30, 2025 05:20
@graphite-app graphite-app bot added the community Created by Linear-GitHub Sync label Jul 30, 2025
@vercel
Copy link

vercel bot commented Jul 30, 2025

@naaa760 is attempting to deploy a commit to the cal Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions github-actions bot added bookings area: bookings, availability, timezones, double booking 🐛 bug Something isn't working labels Jul 30, 2025
@graphite-app
Copy link

graphite-app bot commented Jul 30, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (07/30/25)

1 reviewer was added to this PR based on Keith Williams's automation.

"Add community label" took an action on this PR • (07/30/25)

1 label was added to this PR based on Keith Williams's automation.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c8bea5b and 75c1b29.

📒 Files selected for processing (2)
  • packages/features/bookings/lib/handleNewBooking/createBooking.ts (3 hunks)
  • packages/features/bookings/lib/handleNewRecurringBooking.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

**/*.ts: For Prisma queries, only select data you need; never use include, always use select
Ensure the credential.key field is never returned from tRPC endpoints or APIs

Files:

  • packages/features/bookings/lib/handleNewRecurringBooking.ts
  • packages/features/bookings/lib/handleNewBooking/createBooking.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js .utc() in hot paths like loops

Files:

  • packages/features/bookings/lib/handleNewRecurringBooking.ts
  • packages/features/bookings/lib/handleNewBooking/createBooking.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: CarinaWolli
PR: calcom/cal.com#22296
File: packages/lib/bookings/filterHostsBySameRoundRobinHost.ts:41-42
Timestamp: 2025-07-22T11:42:47.623Z
Learning: The filterHostsBySameRoundRobinHost function in packages/lib/bookings/filterHostsBySameRoundRobinHost.ts has a known limitation where it doesn't work correctly with fixed hosts or round robin groups. This is pre-existing technical debt that was already broken before the round robin groups feature. CarinaWolli has documented this in Linear issue CAL-6134 for future fix.
Learnt from: alishaz-polymath
PR: calcom/cal.com#22304
File: packages/prisma/schema.prisma:1068-1071
Timestamp: 2025-07-16T05:10:22.891Z
Learning: In PR #22304 for Cal.com private link expiration features, the `maxUsageCount` field was intentionally set to default to 1 (non-nullable) as a breaking change, making all existing private links single-use after migration. This was a deliberate design decision by alishaz-polymath.
Learnt from: vijayraghav-io
PR: calcom/cal.com#21072
File: packages/prisma/schema.prisma:891-891
Timestamp: 2025-07-18T08:47:01.264Z
Learning: The Outlook Calendar integration in Cal.com intentionally reuses subscription IDs across multiple event types for efficiency. The `upsertSelectedCalendarsForEventTypeIds` method creates separate SelectedCalendar records for each eventTypeId, all sharing the same outlookSubscriptionId. This subscription sharing pattern means that unique constraints like `@@unique([outlookSubscriptionId, eventTypeId])` should not be applied as they would prevent this intended functionality.
Learnt from: eunjae-lee
PR: calcom/cal.com#22702
File: packages/lib/server/service/insightsBooking.ts:120-124
Timestamp: 2025-07-24T08:39:06.185Z
Learning: In the InsightsBookingService (packages/lib/server/service/insightsBooking.ts), the constructor stores null for invalid options or filters but this is handled safely through null checks in buildFilterConditions() and buildAuthorizationConditions() methods. The service uses defensive programming to return safe fallback conditions (null or NOTHING_CONDITION) rather than throwing errors on invalid inputs.
Learnt from: vijayraghav-io
PR: calcom/cal.com#21072
File: packages/app-store/office365calendar/api/webhook.ts:120-123
Timestamp: 2025-07-18T17:57:16.395Z
Learning: The office365calendar webhook handler in packages/app-store/office365calendar/api/webhook.ts is specifically designed for Office365 calendar integration, not as a generic webhook handler. Therefore, it's safe to assume that fetchAvailabilityAndSetCache method will be implemented in the Office365CalendarService, making explicit validation checks unnecessary.
packages/features/bookings/lib/handleNewRecurringBooking.ts (3)

Learnt from: CarinaWolli
PR: #22296
File: packages/lib/bookings/filterHostsBySameRoundRobinHost.ts:41-42
Timestamp: 2025-07-22T11:42:47.623Z
Learning: The filterHostsBySameRoundRobinHost function in packages/lib/bookings/filterHostsBySameRoundRobinHost.ts has a known limitation where it doesn't work correctly with fixed hosts or round robin groups. This is pre-existing technical debt that was already broken before the round robin groups feature. CarinaWolli has documented this in Linear issue CAL-6134 for future fix.

Learnt from: vijayraghav-io
PR: #21072
File: packages/app-store/office365calendar/api/webhook.ts:120-123
Timestamp: 2025-07-18T17:57:16.395Z
Learning: The office365calendar webhook handler in packages/app-store/office365calendar/api/webhook.ts is specifically designed for Office365 calendar integration, not as a generic webhook handler. Therefore, it's safe to assume that fetchAvailabilityAndSetCache method will be implemented in the Office365CalendarService, making explicit validation checks unnecessary.

Learnt from: vijayraghav-io
PR: #21072
File: packages/prisma/schema.prisma:891-891
Timestamp: 2025-07-18T08:47:01.264Z
Learning: The Outlook Calendar integration in Cal.com intentionally reuses subscription IDs across multiple event types for efficiency. The upsertSelectedCalendarsForEventTypeIds method creates separate SelectedCalendar records for each eventTypeId, all sharing the same outlookSubscriptionId. This subscription sharing pattern means that unique constraints like @@unique([outlookSubscriptionId, eventTypeId]) should not be applied as they would prevent this intended functionality.

packages/features/bookings/lib/handleNewBooking/createBooking.ts (5)

Learnt from: eunjae-lee
PR: #22702
File: packages/lib/server/service/insightsBooking.ts:120-124
Timestamp: 2025-07-24T08:39:06.185Z
Learning: In the InsightsBookingService (packages/lib/server/service/insightsBooking.ts), the constructor stores null for invalid options or filters but this is handled safely through null checks in buildFilterConditions() and buildAuthorizationConditions() methods. The service uses defensive programming to return safe fallback conditions (null or NOTHING_CONDITION) rather than throwing errors on invalid inputs.

Learnt from: CarinaWolli
PR: #22296
File: packages/lib/bookings/filterHostsBySameRoundRobinHost.ts:41-42
Timestamp: 2025-07-22T11:42:47.623Z
Learning: The filterHostsBySameRoundRobinHost function in packages/lib/bookings/filterHostsBySameRoundRobinHost.ts has a known limitation where it doesn't work correctly with fixed hosts or round robin groups. This is pre-existing technical debt that was already broken before the round robin groups feature. CarinaWolli has documented this in Linear issue CAL-6134 for future fix.

Learnt from: vijayraghav-io
PR: #21072
File: packages/app-store/office365calendar/api/webhook.ts:120-123
Timestamp: 2025-07-18T17:57:16.395Z
Learning: The office365calendar webhook handler in packages/app-store/office365calendar/api/webhook.ts is specifically designed for Office365 calendar integration, not as a generic webhook handler. Therefore, it's safe to assume that fetchAvailabilityAndSetCache method will be implemented in the Office365CalendarService, making explicit validation checks unnecessary.

Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-28T11:50:23.946Z
Learning: Applies to **/*.{ts,tsx} : Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js .utc() in hot paths like loops

Learnt from: eunjae-lee
PR: #22106
File: packages/features/insights/components/FailedBookingsByField.tsx:65-71
Timestamp: 2025-07-15T12:59:34.389Z
Learning: In the FailedBookingsByField component (packages/features/insights/components/FailedBookingsByField.tsx), although routingFormId is typed as optional in useInsightsParameters, the system automatically enforces a routing form filter, so routingFormId is always present in practice. This means the data always contains only one entry, making the single-entry destructuring approach safe.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Install dependencies / Yarn install & cache
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (4)
packages/features/bookings/lib/handleNewBooking/createBooking.ts (2)

9-10: LGTM!

The new imports for HttpError and ErrorCode are correctly added and necessary for the overlap checking functionality.


77-138: LGTM! Comprehensive overlap detection with proper error handling.

The function correctly implements all four overlap scenarios:

  • New booking starts during existing booking
  • New booking ends during existing booking
  • New booking completely contains existing booking
  • New booking is completely contained within existing booking

The logic properly excludes rescheduled bookings and uses appropriate Prisma select to fetch only required fields, following the coding guidelines.

packages/features/bookings/lib/handleNewRecurringBooking.ts (2)

5-8: LGTM!

The new imports are consistent with the single booking implementation and necessary for the overlap checking functionality.


124-129: LGTM! Proper integration of overlap checking.

The overlap check is correctly placed before processing any recurring bookings, ensuring conflicts are detected early. Using firstBooking data for eventTypeId and rescheduleUid is appropriate since all recurring bookings share the same event type and reschedule context.

Comment on lines +241 to +247
// Check for overlapping bookings before creating the new booking
await checkForOverlappingBookings({
eventTypeId: newBookingData.eventTypeId!,
startTime: newBookingData.startTime,
endTime: newBookingData.endTime,
rescheduleUid: originalRescheduledBooking?.uid,
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

LGTM! Proper integration into the transaction flow.

The overlap check is correctly placed at the beginning of the transaction before any database modifications. The parameters are properly extracted from the booking data.

Verify that eventTypeId is always non-null at this point to ensure the non-null assertion is safe:


🏁 Script executed:

#!/bin/bash
# Description: Check if eventTypeId can be null in buildNewBookingData function
# Expected: eventTypeId should always be set when this function is called

ast-grep --pattern $'function buildNewBookingData($$$) {
  $$$
  eventType: eventTypeRel,
  $$$
}'

Length of output: 99


🏁 Script executed:

#!/bin/bash
set -e

echo "🔍 Locating newBookingData definition in createBooking.ts"
rg -n -C5 "newBookingData" packages/features/bookings/lib/handleNewBooking/createBooking.ts

echo ""
echo "🔍 Searching for the NewBookingData type/interface declaration in the repo"
rg -n -C3 "NewBookingData" -g "*.ts"

Length of output: 6345


🏁 Script executed:

#!/bin/bash
# Extract buildNewBookingData including eventTypeId assignments
sed -n '280,360p' packages/features/bookings/lib/handleNewBooking/createBooking.ts

Length of output: 2792


Ensure the correct eventTypeId is used for overlap checking

The current call uses newBookingData.eventTypeId!, but buildNewBookingData never assigns an eventTypeId property—so it will always be undefined at runtime. Please update the overlap check to use the actual eventType.id from the function parameters (or explicitly add eventTypeId to newBookingData).

Suggested change:

--- a/packages/features/bookings/lib/handleNewBooking/createBooking.ts
+++ b/packages/features/bookings/lib/handleNewBooking/createBooking.ts
@@ 241,247c241,245
-    await checkForOverlappingBookings({
-      eventTypeId: newBookingData.eventTypeId!,
+    await checkForOverlappingBookings({
+      eventTypeId: eventType.id,
       startTime: newBookingData.startTime,
       endTime: newBookingData.endTime,
       rescheduleUid: originalRescheduledBooking?.uid,

• File: packages/features/bookings/lib/handleNewBooking/createBooking.ts
• Lines: 241–247

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Check for overlapping bookings before creating the new booking
await checkForOverlappingBookings({
eventTypeId: newBookingData.eventTypeId!,
startTime: newBookingData.startTime,
endTime: newBookingData.endTime,
rescheduleUid: originalRescheduledBooking?.uid,
});
// Check for overlapping bookings before creating the new booking
await checkForOverlappingBookings({
eventTypeId: eventType.id,
startTime: newBookingData.startTime,
endTime: newBookingData.endTime,
rescheduleUid: originalRescheduledBooking?.uid,
});
🤖 Prompt for AI Agents
In packages/features/bookings/lib/handleNewBooking/createBooking.ts around lines
241 to 247, the overlap check uses newBookingData.eventTypeId which is never set
and thus undefined. Fix this by replacing newBookingData.eventTypeId with the
correct eventType.id parameter value when calling checkForOverlappingBookings,
ensuring the actual event type ID is used for the overlap check.

Comment on lines +28 to +94
/**
* Check for overlapping bookings across all recurring dates
*/
async function checkForOverlappingRecurringBookings({
eventTypeId,
recurringDates,
rescheduleUid,
}: {
eventTypeId: number;
recurringDates: { start: string | undefined; end: string | undefined }[];
rescheduleUid?: string;
}) {
for (const date of recurringDates) {
if (!date.start || !date.end) continue;

const startTime = new Date(date.start);
const endTime = new Date(date.end);

const overlappingBookings = await prisma.booking.findFirst({
where: {
eventTypeId,
status: {
in: [BookingStatus.ACCEPTED, BookingStatus.PENDING],
},
// Check for overlapping time ranges
OR: [
// New booking starts during an existing booking
{
startTime: { lte: startTime },
endTime: { gt: startTime },
},
// New booking ends during an existing booking
{
startTime: { lt: endTime },
endTime: { gte: endTime },
},
// New booking completely contains an existing booking
{
startTime: { gte: startTime },
endTime: { lte: endTime },
},
// New booking is completely contained within an existing booking
{
startTime: { lte: startTime },
endTime: { gte: endTime },
},
],
// Exclude the booking being rescheduled
...(rescheduleUid && { uid: { not: rescheduleUid } }),
},
select: {
id: true,
uid: true,
startTime: true,
endTime: true,
status: true,
},
});

if (overlappingBookings) {
throw new HttpError({
statusCode: 409,
message: ErrorCode.BookingConflict,
});
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Optimize database queries for better performance.

While the logic is correct, the current implementation makes a separate database query for each recurring date, which could be inefficient for bookings with many recurrences.

Consider optimizing with a single query that checks all dates at once:

-async function checkForOverlappingRecurringBookings({
-  eventTypeId,
-  recurringDates,
-  rescheduleUid,
-}: {
-  eventTypeId: number;
-  recurringDates: { start: string | undefined; end: string | undefined }[];
-  rescheduleUid?: string;
-}) {
-  for (const date of recurringDates) {
-    if (!date.start || !date.end) continue;
-
-    const startTime = new Date(date.start);
-    const endTime = new Date(date.end);
-
-    const overlappingBookings = await prisma.booking.findFirst({
-      where: {
-        eventTypeId,
-        status: {
-          in: [BookingStatus.ACCEPTED, BookingStatus.PENDING],
-        },
-        // Check for overlapping time ranges
-        OR: [
-          // ... overlap conditions
-        ],
-        // Exclude the booking being rescheduled
-        ...(rescheduleUid && { uid: { not: rescheduleUid } }),
-      },
-      select: {
-        id: true,
-        uid: true,
-        startTime: true,
-        endTime: true,
-        status: true,
-      },
-    });
-
-    if (overlappingBookings) {
-      throw new HttpError({
-        statusCode: 409,
-        message: ErrorCode.BookingConflict,
-      });
-    }
-  }
-}
+async function checkForOverlappingRecurringBookings({
+  eventTypeId,
+  recurringDates,
+  rescheduleUid,
+}: {
+  eventTypeId: number;
+  recurringDates: { start: string | undefined; end: string | undefined }[];
+  rescheduleUid?: string;
+}) {
+  const validDates = recurringDates
+    .filter(date => date.start && date.end)
+    .map(date => ({
+      startTime: new Date(date.start!),
+      endTime: new Date(date.end!)
+    }));
+
+  if (validDates.length === 0) return;
+
+  const dateConditions = validDates.flatMap(({ startTime, endTime }) => [
+    { startTime: { lte: startTime }, endTime: { gt: startTime } },
+    { startTime: { lt: endTime }, endTime: { gte: endTime } },
+    { startTime: { gte: startTime }, endTime: { lte: endTime } },
+    { startTime: { lte: startTime }, endTime: { gte: endTime } },
+  ]);
+
+  const overlappingBookings = await prisma.booking.findFirst({
+    where: {
+      eventTypeId,
+      status: {
+        in: [BookingStatus.ACCEPTED, BookingStatus.PENDING],
+      },
+      OR: dateConditions,
+      ...(rescheduleUid && { uid: { not: rescheduleUid } }),
+    },
+    select: {
+      id: true,
+      uid: true,
+      startTime: true,
+      endTime: true,
+      status: true,
+    },
+  });
+
+  if (overlappingBookings) {
+    throw new HttpError({
+      statusCode: 409,
+      message: ErrorCode.BookingConflict,
+    });
+  }
+}
🤖 Prompt for AI Agents
In packages/features/bookings/lib/handleNewRecurringBooking.ts between lines 28
and 94, the function currently performs a separate database query for each
recurring date to check for overlapping bookings, which is inefficient. Refactor
the code to consolidate all recurring date checks into a single Prisma query by
constructing a combined OR condition that includes all date ranges at once. This
will reduce the number of database calls and improve performance for bookings
with many recurrences.

Copy link
Contributor

@Devanshusharma2005 Devanshusharma2005 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@naaa760 can you please address the type-checks and unit tests failing.
Please add a loom also to show the changes.
Marking it draft until then .
Feel free to rfr.

@Devanshusharma2005 Devanshusharma2005 marked this pull request as draft July 30, 2025 06:18
@naaa760 naaa760 closed this by deleting the head repository Aug 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bookings area: bookings, availability, timezones, double booking 🐛 bug Something isn't working community Created by Linear-GitHub Sync

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Duplicate double bookings using recurring booking links

2 participants