Skip to content

Conversation

@sujal12344
Copy link

@sujal12344 sujal12344 commented Sep 28, 2025

What does this PR do?

This PR fixes the issue where rescheduling a booking did not respect the availability of the user who originally booked the meeting.
Now, when a host reschedules, the system correctly checks both participants’ availability before confirming the new time.

Visual Demo (For contributors especially)

Before (current behavior)

When rescheduling, only the invitee’s (user_B) availability is considered. The availability of the host (user_A) is ignored.

User A availability (before)
User A availability

User B availability (before)
User B availability

Reschedule ignoring host availability
Only user_B availability is respected — host availability is ignored


After (fixed behavior)

When rescheduling, both the host (user_A) and invitee (user_B) availabilities are checked, and only common available times are shown.

User A availability (after)
User A availability

User B availability (after)
User B availability

Reschedule respecting both users
Both availabilities are respected when rescheduling


Mandatory Tasks (DO NOT REMOVE)

  • I have self-reviewed the code (A decent size PR without self-review might be rejected).
  • I confirm automated tests are in place that prove my fix is effective or that my feature works.

How should this be tested?

  1. Clone and set up project (pnpm install && pnpm dev).
  2. Create two Cal.com users (user_A & user_B) with overlapping.
  3. Have user_A book a meeting with user_B.
  4. As host (user_A), attempt to reschedule the meeting:
    • Before fix: Able to pick times outside host’s availability.
    • After fix: Only times that match both users’ availability are allowed.
  5. Verify that normal booking flows are unaffected.

Checklist

  • I have read the contributing guide
  • My code follows the style guidelines of this project
  • I have commented my code, particularly in hard-to-understand areas
  • I have checked that my changes generate no new warnings

@sujal12344 sujal12344 requested a review from a team as a code owner September 28, 2025 21:15
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 28, 2025

Walkthrough

Adds server-side logic to derive a current session user (from rescheduleUid/email or from the request session via a dynamic session middleware import). If a distinct session user is found, the code obtains that user’s availability and intersects it with each organizer’s availability (respecting oooExcludedDateRanges) using the date-ranges intersection utility; if the session user has no availability the aggregated availability becomes empty. Adds end-to-end tests for organizer vs session-user intersection and organizer-only availability (fixed time, Asia/Kolkata).

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly summarizes the primary change by indicating a fix to the rescheduling flow so that availability is respected and it directly references the relevant issue, making it specific and concise.
Linked Issues Check ✅ Passed The implementation adds logic to look up the guest by email or session context, retrieves their availability, and intersects it with the host’s slots exactly as specified in issue #16378/CAL-4531, and end-to-end tests validate this behavior.
Out of Scope Changes Check ✅ Passed All modifications are confined to the availability intersection workflow and its tests, with no unrelated code alterations detected outside the scope of rescheduling availability logic.
Description Check ✅ Passed The description provides a clear overview of the problem and solution, references the fixed issues, includes before/after visuals, testing instructions, and confirms that relevant tests are in place, demonstrating it is directly related to the changeset.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • 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

Comment @coderabbitai help to get the list of available commands and usage tips.

@vercel
Copy link

vercel bot commented Sep 28, 2025

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

A member of the Team first needs to authorize it.

@CLAassistant
Copy link

CLAassistant commented Sep 28, 2025

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ sujal12344
❌ aayush-dev-tsx
You have signed the CLA already but the status is still pending? Let us recheck it.

@github-actions github-actions bot added $200 bookings area: bookings, availability, timezones, double booking Medium priority Created by Linear-GitHub Sync ✨ feature New feature or request 💎 Bounty A bounty on Algora.io 🧹 Improvements Improvements to existing features. Mostly UX/UI labels Sep 28, 2025
@graphite-app graphite-app bot added the community Created by Linear-GitHub Sync label Sep 28, 2025
@graphite-app graphite-app bot requested a review from a team September 28, 2025 21:15
@dosubot dosubot bot added the 🐛 bug Something isn't working label Sep 28, 2025
@dosubot dosubot bot added this to the v5.8 milestone Sep 28, 2025
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: 3

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a48a1bd and 0b1878f.

📒 Files selected for processing (2)
  • apps/web/test/lib/availability-intersection.test.ts (1 hunks)
  • packages/trpc/server/routers/viewer/slots/util.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.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/trpc/server/routers/viewer/slots/util.ts
  • apps/web/test/lib/availability-intersection.test.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/trpc/server/routers/viewer/slots/util.ts
  • apps/web/test/lib/availability-intersection.test.ts
**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

Flag default exports and encourage named exports. Named exports provide better tree-shaking, easier refactoring, and clearer imports. Exempt main components like pages, layouts, and components that serve as the primary export of a module.

Files:

  • packages/trpc/server/routers/viewer/slots/util.ts
  • apps/web/test/lib/availability-intersection.test.ts
🧠 Learnings (1)
📚 Learning: 2025-09-23T08:00:07.619Z
Learnt from: hariombalhara
PR: calcom/cal.com#23918
File: packages/features/schedules/lib/use-schedule/useTimesForSchedule.test.ts:16-23
Timestamp: 2025-09-23T08:00:07.619Z
Learning: In calcom/cal.com test files, particularly packages/features/schedules/lib/use-schedule/useTimesForSchedule.test.ts, the TIMEZONE_OFFSETS mapping is intentionally limited to only UTC variants and Asia/Kolkata. This is by design and should not be flagged as incomplete in future reviews (confirmed by maintainer hariombalhara).

Applied to files:

  • apps/web/test/lib/availability-intersection.test.ts
🧬 Code graph analysis (2)
packages/trpc/server/routers/viewer/slots/util.ts (3)
packages/trpc/server/middlewares/sessionMiddleware.ts (2)
  • getSession (90-94)
  • getUserFromSession (19-86)
packages/lib/date-ranges.ts (1)
  • intersect (354-416)
packages/lib/getAggregatedAvailability.ts (1)
  • getAggregatedAvailability (25-74)
apps/web/test/lib/availability-intersection.test.ts (2)
packages/lib/di/containers/AvailableSlots.ts (1)
  • getAvailableSlotsService (49-51)
apps/web/test/utils/bookingScenario/bookingScenario.ts (4)
  • getOrganizer (1520-1579)
  • TestData (1239-1511)
  • getScenarioData (1581-1667)
  • createBookingScenario (978-1009)
⏰ Context from checks skipped due to timeout of 180000ms. 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

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d4181e3 and d24625e.

📒 Files selected for processing (2)
  • apps/web/test/lib/availability-intersection.test.ts (1 hunks)
  • packages/trpc/server/routers/viewer/slots/util.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/test/lib/availability-intersection.test.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.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/trpc/server/routers/viewer/slots/util.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/trpc/server/routers/viewer/slots/util.ts
**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

Flag default exports and encourage named exports. Named exports provide better tree-shaking, easier refactoring, and clearer imports. Exempt main components like pages, layouts, and components that serve as the primary export of a module.

Files:

  • packages/trpc/server/routers/viewer/slots/util.ts
🧠 Learnings (2)
📚 Learning: 2025-09-12T11:23:34.158Z
Learnt from: hariombalhara
PR: calcom/cal.com#23736
File: packages/features/bookings/lib/reschedule/determineReschedulePreventionRedirect.ts:73-84
Timestamp: 2025-09-12T11:23:34.158Z
Learning: In the Cal.com codebase, the forceRescheduleForCancelledBooking flag historically affects both CANCELLED and REJECTED booking statuses, despite its name suggesting it should only affect cancelled bookings. This behavior existed before PR #23736 and was preserved during the refactoring.

Applied to files:

  • packages/trpc/server/routers/viewer/slots/util.ts
📚 Learning: 2025-09-03T09:52:51.182Z
Learnt from: hariombalhara
PR: calcom/cal.com#23541
File: packages/features/bookings/lib/di/modules/RegularBookingServiceModule.ts:22-28
Timestamp: 2025-09-03T09:52:51.182Z
Learning: The IBookingServiceDependencies interface in packages/features/bookings/lib/handleNewBooking.ts contains 6 properties: cacheService, checkBookingAndDurationLimitsService, prismaClient, bookingRepository, featuresRepository, and checkBookingLimitsService. This interface is used by RegularBookingService and matches the depsMap structure in RegularBookingServiceModule.

Applied to files:

  • packages/trpc/server/routers/viewer/slots/util.ts
🧬 Code graph analysis (1)
packages/trpc/server/routers/viewer/slots/util.ts (3)
packages/trpc/server/middlewares/sessionMiddleware.ts (2)
  • getSession (90-94)
  • getUserFromSession (19-86)
packages/lib/date-ranges.ts (1)
  • intersect (354-416)
packages/lib/getAggregatedAvailability.ts (1)
  • getAggregatedAvailability (25-74)
🔇 Additional comments (2)
packages/trpc/server/routers/viewer/slots/util.ts (2)

11-11: LGTM: import for dynamic event defaults

Importing getDefaultEvent here is appropriate for the dynamic event path.


976-996: Don’t rely on input.email; derive the booker from rescheduleUid

Using input.email to identify the user whose availability should be intersected is fragile and can still select the host when they’re rescheduling, causing the original bug to persist. Resolve the invitee/booker directly from the booking referenced by input.rescheduleUid (grab attendees; pick the Cal.com user among them if any). If no Cal.com user exists, skip intersection as before.

Minimal change: move “who to intersect with” resolution to later (right before intersection) and derive from booking. Example replacement for this block (compute only a placeholder here and resolve after hosts/availability are known):

-    // Extract current session user from context or from reschedule/booking context
-    let currentSessionUser: { id: number; email: string } | null = null;
-
-    // First, try to get user from reschedule context (for reschedule scenarios)
-    if (input.rescheduleUid && input.email) {
-      ...
-    }
+    // Placeholder; we’ll resolve the intersect user later (post host availability)
+    let intersectUser: { id: number; email: string } | null = null;

Then, inside the intersection section (see separate comment), resolve intersectUser via bookingRepo using input.rescheduleUid and only fall back to input.email if needed. This ensures we truly intersect with the invitee when the host is rescheduling.

@sujal12344
Copy link
Author

@pumfleet @anikdhabal Could you please take a look when you get a chance?

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: 0

🧹 Nitpick comments (5)
apps/web/test/lib/availability-intersection.test.ts (5)

17-17: Remove commented-out code.

The commented-out console.log should be removed to keep the codebase clean.

Apply this diff:

 describe("User Availability Intersection Tests", () => {
   const availableSlotsService = getAvailableSlotsService();
-  // console.log({availableSlotsService})
   setupAndTeardown();

140-153: Consider using dayjs timezone plugin instead of manual offset.

The code manually adds 5.5 hours to convert UTC to IST. While this works for tests with fixed system time, using the dayjs timezone plugin would be more robust and clearer. This would also eliminate the repeated conversion logic.

Example refactor (requires timezone plugin):

import timezone from '@calcom/dayjs/plugin/timezone';
import utc from '@calcom/dayjs/plugin/utc';

dayjs.extend(utc);
dayjs.extend(timezone);

// Then use:
const slotTime = dayjs.utc(slot.time).tz("Asia/Kolkata");
const slotHour = slotTime.hour();

Or create a helper function for the current approach:

const toIST = (utcTime: string) => dayjs(utcTime).utc().add(5.5, "hours");

// Usage:
const slotTime = toIST(slot.time);
const slotHour = slotTime.hour();

154-161: Remove or uncomment diagnostic code.

The commented-out console.log contains useful diagnostic information. Either remove it entirely if not needed, or uncomment it if it's valuable for debugging test failures.


166-170: Consider removing console.log statements.

Active console.log statements in tests can create noise in test output. Consider removing them or converting to proper test logging if needed for debugging.


258-258: Consider removing console.log statement.

Similar to the first test, this console.log can create noise in test output.

Apply this diff:

   expect(morningSlots.length).toBeGreaterThan(0);
   expect(afternoonSlots.length).toBeGreaterThan(0);
-
-  console.log("Full organizer availability slots:", slotsForDate.length);
 });
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d24625e and 8d234a7.

📒 Files selected for processing (1)
  • apps/web/test/lib/availability-intersection.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.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:

  • apps/web/test/lib/availability-intersection.test.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:

  • apps/web/test/lib/availability-intersection.test.ts
**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

Flag default exports and encourage named exports. Named exports provide better tree-shaking, easier refactoring, and clearer imports. Exempt main components like pages, layouts, and components that serve as the primary export of a module.

Files:

  • apps/web/test/lib/availability-intersection.test.ts
🧠 Learnings (2)
📚 Learning: 2025-09-12T11:23:34.158Z
Learnt from: hariombalhara
PR: calcom/cal.com#23736
File: packages/features/bookings/lib/reschedule/determineReschedulePreventionRedirect.ts:73-84
Timestamp: 2025-09-12T11:23:34.158Z
Learning: The test file packages/features/bookings/lib/reschedule/determineReschedulePreventionRedirect.test.ts explicitly documents on line 236 that the current behavior of forceRescheduleForCancelledBooking affecting both CANCELLED and REJECTED bookings is known to be incorrect, but is preserved as "Current Behavior" for backward compatibility. The test comment states the expected behavior should be that REJECTED bookings redirect to booking details even when forceRescheduleForCancelledBooking=true.

Applied to files:

  • apps/web/test/lib/availability-intersection.test.ts
📚 Learning: 2025-09-23T08:00:07.619Z
Learnt from: hariombalhara
PR: calcom/cal.com#23918
File: packages/features/schedules/lib/use-schedule/useTimesForSchedule.test.ts:16-23
Timestamp: 2025-09-23T08:00:07.619Z
Learning: In calcom/cal.com test files, particularly packages/features/schedules/lib/use-schedule/useTimesForSchedule.test.ts, the TIMEZONE_OFFSETS mapping is intentionally limited to only UTC variants and Asia/Kolkata. This is by design and should not be flagged as incomplete in future reviews (confirmed by maintainer hariombalhara).

Applied to files:

  • apps/web/test/lib/availability-intersection.test.ts
🧬 Code graph analysis (1)
apps/web/test/lib/availability-intersection.test.ts (2)
packages/features/di/containers/AvailableSlots.ts (1)
  • getAvailableSlotsService (49-51)
apps/web/test/utils/bookingScenario/bookingScenario.ts (4)
  • getOrganizer (1539-1598)
  • TestData (1258-1530)
  • getScenarioData (1600-1688)
  • createBookingScenario (997-1028)
⏰ Context from checks skipped due to timeout of 180000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Linters / lint
  • GitHub Check: Tests / Unit
  • GitHub Check: Type check / check-types
🔇 Additional comments (2)
apps/web/test/lib/availability-intersection.test.ts (2)

163-164: Assertions correctly validate intersection behavior.

The test properly asserts that intersection slots exist and no slots fall outside the intersection window. This validates that the availability intersection logic works as expected when both organizer and session user are present.


234-256: Test properly validates organizer-only availability.

The test correctly asserts that when no session user context exists, the full organizer availability (10 AM - 2 PM IST) is shown. The test also validates that slots exist throughout both the morning and afternoon windows, ensuring comprehensive coverage of the availability range.

@CarinaWolli CarinaWolli modified the milestones: v5.8, v5.9 Oct 16, 2025
@dosubot dosubot bot modified the milestone: v5.9 Oct 16, 2025
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

2 issues found across 2 files

Prompt for AI agents (all 2 issues)

Understand the root cause of the following 2 issues and fix them.


<file name="packages/trpc/server/routers/viewer/slots/util.ts">

<violation number="1" location="packages/trpc/server/routers/viewer/slots/util.ts:994">
Rule violated: **Avoid Logging Sensitive Information**

This debug log writes the user&#39;s email address to application logs, violating the &quot;Avoid Logging Sensitive Information&quot; rule. Strip the email from the log payload to keep PII out of logs.</violation>

<violation number="2" location="packages/trpc/server/routers/viewer/slots/util.ts:1010">
Rule violated: **Avoid Logging Sensitive Information**

This debug log records the session user&#39;s email address, breaching the &quot;Avoid Logging Sensitive Information&quot; rule. Remove the email field (or otherwise redact it) before logging to avoid leaking PII.</violation>
</file>

Since this is your first cubic review, here's how it works:

  • cubic automatically reviews your code and comments on bugs and improvements
  • Teach cubic by replying to its comments. cubic learns from your replies and gets better over time
  • Ask questions if you need clarification on any suggestion

React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.

@CarinaWolli CarinaWolli modified the milestones: v5.9, v6.0 Nov 17, 2025
@CarinaWolli CarinaWolli modified the milestones: v6.0, v6.1 Dec 16, 2025
@CarinaWolli CarinaWolli modified the milestones: v6.1, v6.2 Jan 16, 2026
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 💎 Bounty A bounty on Algora.io 🐛 bug Something isn't working community Created by Linear-GitHub Sync ✨ feature New feature or request 🧹 Improvements Improvements to existing features. Mostly UX/UI Medium priority Created by Linear-GitHub Sync size/L $200

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[CAL-4531] Take into account guest's availability when rescheduling

4 participants