Skip to content

Comments

fix: booking availability based on limit#23400

Draft
SinghaAnirban005 wants to merge 15 commits intocalcom:mainfrom
SinghaAnirban005:bug/t
Draft

fix: booking availability based on limit#23400
SinghaAnirban005 wants to merge 15 commits intocalcom:mainfrom
SinghaAnirban005:bug/t

Conversation

@SinghaAnirban005
Copy link
Contributor

@SinghaAnirban005 SinghaAnirban005 commented Aug 27, 2025

What does this PR do?

This PR handles weekly booking limits correctly based on the "start of the week" parameter . Ensures the weekStart paramter is respected

Visual Demo (For contributors especially)

Screencast.from.2025-08-31.22-29-22.webm

Mandatory Tasks (DO NOT REMOVE)

  • I have self-reviewed the code (A decent size PR without self-review might be rejected).
  • I have updated the developer docs in /docs if this PR makes changes that would require a documentation change. N/A
  • I confirm automated tests are in place that prove my fix is effective or that my feature works.

How should this be tested?

  • Are there environment variables that should be set?
  • What are the minimal test data to have?
  • What is expected (happy path) to have (input and output)?
  • Any other important info that could help to test that PR

@vercel
Copy link

vercel bot commented Aug 27, 2025

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

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 27, 2025

Walkthrough

User week start (defaulting to "Monday") is read from user data and threaded through availability and interval-limit logic. weekStart is passed into getBusyTimesFromLimits, LimitManager, and getPeriodStartDatesBetween; LimitManager aligns weekly period starts/ends and busy-time keying. getPeriodStartDatesBetween and related helpers now accept an optional weekStart parameter. getUserAvailability API surface added bookingRepo and redisClient, and busy-times selection logic treats PER_WEEK limits specially when deciding whether to reuse initial busy-times.

Possibly related PRs

Pre-merge checks (3 passed, 1 warning, 1 inconclusive)

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title Check ❓ Inconclusive The current title “fix: booking availability based on limit” is related to the changeset but is too generic and does not clearly reflect the main change, which is respecting the weekStart boundary for weekly booking limits, so its phrasing is partially relevant yet not specific enough for quick comprehension. Consider updating the title to explicitly mention weekly limits or the weekStart parameter, for example “fix: respect weekStart in weekly booking limits” so it clearly conveys the primary change.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues Check ✅ Passed The pull request threads the weekStart parameter through user availability, limit management, busy-time computation, period-start date utilities, booking handlers, and the booking limits checks, thereby directly implementing the linked issues’ requirement to enforce weekly booking limits relative to the configured start-of-week boundary.
Out of Scope Changes Check ✅ Passed All code changes, including adding weekStart to database selects, injecting weekStart parameters into service interfaces, and extending utilities and handlers, serve the objective of enforcing weekly booking limits based on the configured start-of-week, and no unrelated functionality was introduced.
Description Check ✅ Passed The description clearly relates to handling weekly booking limits and the weekStart parameter, aligning with the changeset’s focus on respecting the start-of-week boundary for availability calculations.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues Check ✅ Passed The pull request threads the weekStart parameter through user availability, limit management, busy-time computation, period-start date utilities, booking handlers, and the booking limits checks, thereby directly implementing the linked issues’ requirement to enforce weekly booking limits relative to the configured start-of-week boundary.
Out of Scope Changes Check ✅ Passed All code changes, including adding weekStart to database selects, injecting weekStart parameters into service interfaces, and extending utilities and handlers, serve the objective of enforcing weekly booking limits based on the configured start-of-week, and no unrelated functionality was introduced.
Title Check ✅ Passed The title "fix: booking availability based on limit" is concise and directly related to the PR's main purpose of fixing booking availability enforcement for interval limits; it maps to the implemented changes that make weekly limits respect the configured weekStart. While slightly generic, it still communicates the primary intent of the changeset.
Description Check ✅ Passed The PR description clearly states the purpose to respect the weekStart parameter for weekly booking limits, references the related GitHub and Linear issues, and includes a demo and test checklist, so it is directly related to the changes in the diff.
✨ 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

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

@github-actions github-actions bot added bookings area: bookings, availability, timezones, double booking Low priority Created by Linear-GitHub Sync 🐛 bug Something isn't working labels Aug 27, 2025
@SinghaAnirban005 SinghaAnirban005 force-pushed the bug/t branch 2 times, most recently from 92b199d to 8ac3b23 Compare August 30, 2025 18:16
@SinghaAnirban005 SinghaAnirban005 marked this pull request as ready for review August 31, 2025 17:52
@SinghaAnirban005 SinghaAnirban005 requested a review from a team August 31, 2025 17:52
@SinghaAnirban005 SinghaAnirban005 requested a review from a team as a code owner August 31, 2025 17:52
@graphite-app graphite-app bot added the community Created by Linear-GitHub Sync label Aug 31, 2025
@graphite-app graphite-app bot requested a review from a team August 31, 2025 17:52
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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/lib/intervalLimits/limitManager.ts (1)

23-26: Weekly keying uses Day.js default week boundaries, causing missed/duplicate busy spans.

isAlreadyBusy builds keys via startOf("week") and endOf("week") (Day.js default), while addBusyTime stores weekly keys using a custom-aligned start (user weekStart). Keys won’t match when user weekStart ≠ Day.js default, breaking deduplication.

Unify key generation to the user’s weekStart by making createKey instance-based and reusing your alignment helpers:

-  private static createKey(start: Dayjs, unit: IntervalLimitUnit, timeZone?: string): BusyMapKey {
-    const tzStart = timeZone ? start.tz(timeZone) : start;
-    return `${unit}-${tzStart.startOf(unit).toISOString()}`;
-  }
+  private createKey(start: Dayjs, unit: IntervalLimitUnit, timeZone?: string): BusyMapKey {
+    let tzStart = timeZone ? start.tz(timeZone) : start;
+    if (unit === "week") {
+      tzStart = this.adjustWeekStart(tzStart, timeZone);
+    } else {
+      tzStart = tzStart.startOf(unit);
+    }
+    return `${unit}-${tzStart.toISOString()}`;
+  }
-    if (this.busyMap.has(LimitManager.createKey(start, "year", timeZone))) return true;
+    if (this.busyMap.has(this.createKey(start, "year", timeZone))) return true;
@@
-      ((this.busyMap.has(LimitManager.createKey(start, "month", timeZone)) &&
-        this.busyMap.has(LimitManager.createKey(start.endOf("week"), "month", timeZone))) ||
-        this.busyMap.has(LimitManager.createKey(start, "week", timeZone)))
+      ((this.busyMap.has(this.createKey(start, "month", timeZone)) &&
+        this.busyMap.has(
+          this.createKey(this.getPeriodEnd(this.adjustWeekStart(start, timeZone), "week", timeZone), "month", timeZone)
+        )) ||
+        this.busyMap.has(this.createKey(start, "week", timeZone)))
-    this.busyMap.set(`${unit}-${adjustedStart.toISOString()}`, {
+    this.busyMap.set(this.createKey(adjustedStart, unit, timeZone), {
       start: adjustedStart.toISOString(),
       end: periodEnd.toISOString(),
     });

Also applies to: 56-66, 70-74, 97-100

packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (2)

146-147: Weekly periodEnd should honor user weekStart (not Day.js endOf('week')).

For non-default weekStart, endOf("week") cuts the period short. Compute end via +6 days from aligned start.

-      const periodEnd = periodStart.endOf(unit);
+      const periodEnd =
+        unit === "week" ? periodStart.add(6, "day").endOf("day") : periodStart.endOf(unit);

268-281: Team limits ignore weekStart. Propagate it for consistency.

_getBusyTimesFromTeamLimits builds weekly ranges with defaults (and constructs LimitManager() without weekStart). Pass weekStart through and use it.

Apply these changes (and update callers):

-const _getBusyTimesFromTeamLimits = async (
+const _getBusyTimesFromTeamLimits = async (
   user: { id: number; email: string },
   bookingLimits: IntervalLimit,
   dateFrom: Dayjs,
   dateTo: Dayjs,
   teamId: number,
   includeManagedEvents: boolean,
   timeZone: string,
-  rescheduleUid?: string
+  rescheduleUid?: string,
+  weekStart?: string
 ) => {
@@
-  const limitManager = new LimitManager();
+  const limitManager = new LimitManager(weekStart);
@@
   await getBusyTimesFromBookingLimits({
     bookings: busyTimes,
     bookingLimits,
     dateFrom,
     dateTo,
     limitManager,
     rescheduleUid,
     teamId,
     user,
     includeManagedEvents,
     timeZone,
+    weekStart,
   });

And in getUserAvailability.ts (team path), pass user.weekStart:

busyTimesFromTeamLimits = await getBusyTimesFromTeamLimits(
  user,
  teamBookingLimits,
  dateFrom.tz(finalTimezone),
  dateTo.tz(finalTimezone),
  teamForBookingLimits.id,
  teamForBookingLimits.includeManagedEventsInLimits,
  finalTimezone,
  initialData?.rescheduleUid ?? undefined,
  user.weekStart
);
🧹 Nitpick comments (2)
packages/lib/intervalLimits/limitManager.ts (1)

12-12: Prefer named exports over default.

Converting export default class LimitManager to a named export improves tree-shaking and refactors.

Apply this diff:

-export default class LimitManager {
+export class LimitManager {

And update imports accordingly:

- import LimitManager from "../limitManager";
+ import { LimitManager } from "../limitManager";
packages/lib/getUserAvailability.ts (1)

410-414: Tighten weekly-limit detection.

Key existence can be true even if value is undefined. Use a value check.

-    function hasWeeklyLimits(bookingLimits: BookingLimits) {
-      if (!bookingLimits) return false;
-      return "PER_WEEK" in bookingLimits;
-    }
+    function hasWeeklyLimits(bookingLimits: BookingLimits) {
+      return bookingLimits?.PER_WEEK != null;
+    }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 d44a41c and d531124.

📒 Files selected for processing (5)
  • packages/lib/getUserAvailability.ts (6 hunks)
  • packages/lib/intervalLimits/limitManager.ts (4 hunks)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (6 hunks)
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1 hunks)
  • packages/prisma/selects/user.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:

  • packages/lib/intervalLimits/limitManager.ts
  • packages/prisma/selects/user.ts
  • packages/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.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/lib/intervalLimits/limitManager.ts
  • packages/prisma/selects/user.ts
  • packages/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.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/lib/intervalLimits/limitManager.ts
  • packages/prisma/selects/user.ts
  • packages/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
🧠 Learnings (1)
📚 Learning: 2025-07-28T11:50:23.946Z
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

Applied to files:

  • packages/lib/intervalLimits/limitManager.ts
🧬 Code graph analysis (2)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
packages/lib/sentryWrapper.ts (1)
  • withReporting (107-139)
packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (2)
packages/lib/intervalLimits/limitManager.ts (1)
  • LimitManager (12-120)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
  • getPeriodStartDatesBetween (49-52)
🔇 Additional comments (8)
packages/prisma/selects/user.ts (1)

9-9: Expose weekStart for availability: LGTM

Selecting weekStart here is correct and aligns with the downstream usage. No leakage of sensitive fields.

packages/lib/intervalLimits/limitManager.ts (1)

28-51: Week alignment helpers: LGTM

adjustWeekStart and getPeriodEnd correctly align to user weekStart and produce 7-day windows.

packages/lib/getUserAvailability.ts (4)

159-163: Type for booking limits: LGTM

The BookingLimits helper type is fine for lightweight checks.


325-327: Ensure consistent default weekStart when user value is absent.

You set this.weekStart = user?.weekStart (possibly undefined). LimitManager currently defaults to Sunday, while the period util defaults to Monday. Confirm unified default or always pass an explicit default.

If unifying to Monday, also pass this.weekStart || "Monday" downstream where needed.


423-435: Threading weekStart into limit checks: LGTM

Passing user.weekStart into getBusyTimesFromLimits is correct.


622-626: Forwarding weekStart to period-start utility: LGTM

This keeps weekly windows aligned with user preference.

packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (2)

33-33: Constructing LimitManager with weekStart: LGTM

Instantiating with weekStart keeps internal keys aligned if the class uses it consistently.


111-117: Weekly period starts with weekStart: LGTM

Using getPeriodStartDatesBetween(..., weekStart) here is correct.

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

🧹 Nitpick comments (2)
packages/lib/getUserAvailability.ts (2)

410-414: Prefer hasOwn over "in" for detecting PER_WEEK presence

Avoid prototype-chain surprises; presence should be about own keys, even if value is undefined.

-    function hasWeeklyLimits(bookingLimits: BookingLimits) {
-      if (!bookingLimits) return false;
-      return "PER_WEEK" in bookingLimits;
-    }
+    function hasWeeklyLimits(bookingLimits: BookingLimits) {
+      if (!bookingLimits) return false;
+      return Object.hasOwn(bookingLimits, "PER_WEEK");
+    }

415-419: Guard cache reuse by matching eventType

Ensure initialData.busyTimesFromLimits corresponds to the same eventType to avoid cross-ET contamination.

-    if (
-      initialData?.busyTimesFromLimits &&
-      initialData?.eventTypeForLimits &&
-      !hasWeeklyLimits(bookingLimits)
-    ) {
+    if (
+      initialData?.busyTimesFromLimits &&
+      initialData?.eventTypeForLimits &&
+      (!eventType || initialData.eventTypeForLimits.id === eventType.id) &&
+      !hasWeeklyLimits(bookingLimits)
+    ) {
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 d531124 and c189ab8.

📒 Files selected for processing (5)
  • packages/lib/getUserAvailability.ts (6 hunks)
  • packages/lib/intervalLimits/limitManager.ts (4 hunks)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (6 hunks)
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1 hunks)
  • packages/prisma/selects/user.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/prisma/selects/user.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.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/lib/getUserAvailability.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/lib/getUserAvailability.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/lib/getUserAvailability.ts
🔇 Additional comments (1)
packages/lib/getUserAvailability.ts (1)

423-434: The scripts have been submitted for execution.

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

♻️ Duplicate comments (1)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)

36-44: End-bound misaligned for weeks; uses Day.js locale week, not user weekStart.
This can drop or over-add a weekly period and ignores timeZone for dateTo. Align the loop end with the same weekStart/timeZone logic as the start and normalize weekly increments to startOf("day") to avoid DST drift.

-  while (currentDate.isBefore(dateTo) || currentDate.isSame(dateTo, period)) {
-    dates.push(currentDate);
-
-    if (period === "week") {
-      currentDate = currentDate.add(1, "week");
-    } else {
-      currentDate = currentDate.add(1, period).startOf(period);
-    }
-  }
+  // Normalize end bound with same semantics as the start
+  const tzDateTo = timeZone ? dayjs(dateTo).tz(timeZone) : dayjs(dateTo);
+  const lastStart =
+    period === "week"
+      ? (() => {
+          const weekStartName = weekStart || "Sunday";
+          const weekIdx = weekStartNum(weekStartName);
+          const currentDayIdx = tzDateTo.day();
+          const daysToSubtract = (currentDayIdx - weekIdx + 7) % 7;
+          return tzDateTo.subtract(daysToSubtract, "day").startOf("day");
+        })()
+      : tzDateTo.startOf(period);
+
+  while (currentDate.isBefore(lastStart) || currentDate.isSame(lastStart)) {
+    dates.push(currentDate);
+
+    if (period === "week") {
+      currentDate = currentDate.add(1, "week").startOf("day");
+    } else {
+      currentDate = currentDate.add(1, period).startOf(period);
+    }
+  }
🧹 Nitpick comments (3)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (3)

12-14: Strengthen the weekStart type.
Use a literal union (or a shared exported type) for weekStart to prevent invalid values.

-import { weekStartNum } from "@calcom/lib/weekstart";
+import { weekStartNum, type WeekStartName } from "@calcom/lib/weekstart"
-  timeZone?: string,
-  weekStart?: string
+  timeZone?: string,
+  weekStart?: WeekStartName

15-17: Type the accumulator.
Make the return type explicit on the local array for clarity and stricter TS checking.

-  const dates = [];
+  const dates: Dayjs[] = [];

18-22: Optional: prefer UTC when no timeZone to avoid host TZ/DST surprises.
When timeZone is omitted, using .utc() avoids environment-dependent behavior in loops.

-  if (timeZone) {
-    currentDate = dayjs(dateFrom).tz(timeZone);
-  } else {
-    currentDate = dayjs(dateFrom);
-  }
+  if (timeZone) {
+    currentDate = dayjs(dateFrom).tz(timeZone);
+  } else {
+    currentDate = dayjs(dateFrom).utc();
+  }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 c189ab8 and 1d9f555.

📒 Files selected for processing (1)
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.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:

  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.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/lib/intervalLimits/utils/getPeriodStartDatesBetween.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/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
🧠 Learnings (1)
📚 Learning: 2025-07-28T11:50:23.946Z
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

Applied to files:

  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
🧬 Code graph analysis (1)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
packages/lib/sentryWrapper.ts (1)
  • withReporting (107-139)
🔇 Additional comments (2)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (2)

4-4: LGTM: importing weekStartNum is appropriate.
No issues with this import; it matches usage below.


49-52: LGTM: observability wrapper.
Good use of withReporting with a stable span name.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/lib/getUserAvailability.ts (1)

418-429: Propagate weekStart to team limits as well; team PER_WEEK constraints may be misaligned.
getBusyTimesFromTeamLimits currently lacks weekStart; weekly team limits will compute with default semantics.

Proposed change in call site (and update function signature accordingly in its module):

-      busyTimesFromTeamLimits = await getBusyTimesFromTeamLimits(
+      busyTimesFromTeamLimits = await getBusyTimesFromTeamLimits(
         user,
         teamBookingLimits,
         dateFrom.tz(finalTimezone),
         dateTo.tz(finalTimezone),
         teamForBookingLimits.id,
         teamForBookingLimits.includeManagedEventsInLimits,
-        finalTimezone,
-        initialData?.rescheduleUid ?? undefined
+        finalTimezone,
+        initialData?.rescheduleUid ?? undefined,
+        weekStart
       );
♻️ Duplicate comments (1)
packages/lib/intervalLimits/limitManager.ts (1)

16-18: Default weekStart should be "Sunday" to match product default; "Monday" causes misaligned weekly limits when unset.
Align with cal.com’s default to avoid off-by-one availability. Also update utils to the same default.

-  constructor(weekStart?: string) {
-    this.weekStart = weekStart || "Monday";
-  }
+  constructor(weekStart?: string) {
+    this.weekStart = weekStart || "Sunday";
+  }
🧹 Nitpick comments (3)
packages/lib/intervalLimits/limitManager.ts (1)

12-13: Prefer named export over default for libraries.
Improves tree-shaking and refactors.

-export default class LimitManager {
+export class LimitManager {

(Remember to update imports.)

packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (2)

15-17: Type the accumulator to avoid any[].

-  const dates = [];
+  const dates: Dayjs[] = [];

24-47: Minor DRY/perf: compute weekStartIndex once.

-    const weekStartName = weekStart || "Sunday";
-    const weekStartIndex = weekStartNum(weekStartName);
+    const weekStartName = weekStart || "Sunday";
+    const weekStartIndex = weekStartNum(weekStartName);
...
-  const lastStart =
-    period === "week"
-      ? (() => {
-          const weekStartName = weekStart || "Sunday";
-          const weekStartIndex = weekStartNum(weekStartName);
+  const lastStart =
+    period === "week"
+      ? (() => {
           const currentDayIndex = tzDateTo.day();
           const daysToSubtract = (currentDayIndex - weekStartIndex + 7) % 7;
           return tzDateTo.subtract(daysToSubtract, "day").startOf("day");
         })()
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 bf8c178 and 814df4f.

📒 Files selected for processing (4)
  • packages/lib/getUserAvailability.ts (5 hunks)
  • packages/lib/intervalLimits/limitManager.ts (4 hunks)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (8 hunks)
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.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/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/getUserAvailability.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/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/getUserAvailability.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/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/getUserAvailability.ts
🧠 Learnings (2)
📚 Learning: 2025-08-31T19:20:20.795Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/limitManager.ts:16-18
Timestamp: 2025-08-31T19:20:20.795Z
Learning: cal.com defaults to Sunday as the week start setting, so components should align with this default for consistency.

Applied to files:

  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
📚 Learning: 2025-07-28T11:50:23.946Z
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

Applied to files:

  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
🧬 Code graph analysis (1)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
packages/lib/sentryWrapper.ts (1)
  • withReporting (107-139)
⏰ 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). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (12)
packages/lib/intervalLimits/limitManager.ts (3)

2-2: Import is appropriate for week-start alignment.


28-39: End-of-week computation is fine, but verify DST and month-boundary cases.
Because week-end is computed via add(6 days).endOf("day"), add unit tests for weeks crossing DST and month edges.

Would you like me to add tests covering DST-crossing weeks (America/Los_Angeles) and month boundaries?


41-52: Week-start adjustment looks correct.
Adjusts by user’s weekStart consistently.

packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (4)

4-4: Import is correct to support week-start alignment.


12-14: Signature extension looks good.
Adding timeZone and weekStart is appropriate.


48-56: Loop logic is correct and inclusive of lastStart.


61-64: Wrapper export change is fine.

packages/lib/getUserAvailability.ts (5)

159-160: BookingLimits typing fix LGTM.
Accurately represents optional map or null.


405-409: Weekly-limits check is fine.


410-418: Reuse guard is correct; only reuse when no PER_WEEK limit.


617-621: Wrapper now forwards weekStart; good.
Consider using this consistently in internal callers to avoid accidental Monday defaults.


161-166: DI wiring covers all IUserAvailabilityService dependencies. Confirmed that getUserAvailabilityModule binds oooRepo, bookingRepo, eventTypeRepo, and redisClient, and no manual new UserAvailabilityService calls exist.

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 (2)
packages/lib/getUserAvailability.ts (2)

405-409: Tighten weekly-limit detection to avoid false positives

Use a numeric check so a present-but-zero/undefined PER_WEEK value doesn’t force the slow path unnecessarily.

-    function hasWeeklyLimits(bookingLimits: BookingLimits) {
-      if (!bookingLimits) return false;
-      return "PER_WEEK" in bookingLimits;
-    }
+    function hasWeeklyLimits(bookingLimits: BookingLimits) {
+      if (!bookingLimits) return false;
+      const v = (bookingLimits as Record<string, unknown>)["PER_WEEK"];
+      return typeof v === "number" && v > 0;
+    }

410-415: Avoid reusing initialData when weekly duration limits exist

If duration limits can also be weekly, the reuse path should be gated on both booking and duration weekly limits to ensure weekStart-aware recomputation.

-    if (
-      initialData?.busyTimesFromLimits &&
-      initialData?.eventTypeForLimits &&
-      !hasWeeklyLimits(bookingLimits)
-    ) {
+    // Treat weekly duration limits like weekly booking limits for reuse gating
+    const hasWeeklyDuration =
+      !!durationLimits && "PER_WEEK" in (durationLimits as Record<string, unknown>);
+    if (
+      initialData?.busyTimesFromLimits &&
+      initialData?.eventTypeForLimits &&
+      !hasWeeklyLimits(bookingLimits) &&
+      !hasWeeklyDuration
+    ) {

Also consider verifying the cached eventTypeForLimits?.id matches the current eventType?.id to prevent reuse across different event types. Want a small follow-up diff?

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 814df4f and 9afae29.

📒 Files selected for processing (1)
  • packages/lib/getUserAvailability.ts (5 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/lib/getUserAvailability.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/lib/getUserAvailability.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/lib/getUserAvailability.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.484Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.376Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.
📚 Learning: 2025-08-31T21:11:58.484Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.484Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.

Applied to files:

  • packages/lib/getUserAvailability.ts
📚 Learning: 2025-08-31T21:16:24.376Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.376Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.

Applied to files:

  • packages/lib/getUserAvailability.ts
⏰ 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: Tests / Unit
  • GitHub Check: Type check / check-types
  • GitHub Check: Linters / lint
🔇 Additional comments (4)
packages/lib/getUserAvailability.ts (4)

159-160: LGTM: BookingLimits type fixed as intended

The alias now correctly models a partial map or null, matching prior feedback.


321-321: Explicit Monday fallback for weekStart

Good call making the fallback explicit; aligns with the stated consistency goal.


417-429: Week-start now threaded into getBusyTimesFromLimits

Passing weekStart here addresses the core bug (weekly windows honoring the configured start-of-week). Nice. One follow-up: team limits path below doesn’t take weekStart; ensure team-level weekly limits, if any, are aligned similarly.


618-620: Omit explicit weekStart audit The wrapper’s default fallback of Monday is intentional and consistent across the codebase (see long-term defaults in getPeriodStartDatesBetweenUtil and getUserAvailability), so call sites don’t need an explicit weekStart for weekly periods.

Likely an incorrect or invalid review comment.

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 (1)
packages/lib/getUserAvailability.ts (1)

405-409: hasWeeklyLimits should check value presence, not just key.
Using the in-operator can mis-detect when keys exist but values are undefined.

Apply:

-    function hasWeeklyLimits(bookingLimits: BookingLimits) {
-      if (!bookingLimits) return false;
-      return "PER_WEEK" in bookingLimits;
-    }
+    function hasWeeklyLimits(bookingLimits: BookingLimits) {
+      return bookingLimits?.PER_WEEK != null;
+    }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 9afae29 and 40e1f0b.

📒 Files selected for processing (5)
  • packages/lib/getUserAvailability.ts (5 hunks)
  • packages/lib/intervalLimits/limitManager.ts (4 hunks)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (8 hunks)
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1 hunks)
  • packages/prisma/selects/user.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/prisma/selects/user.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.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/lib/getUserAvailability.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/lib/getUserAvailability.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/lib/getUserAvailability.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.484Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.376Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.
📚 Learning: 2025-08-31T21:11:58.484Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.484Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.

Applied to files:

  • packages/lib/getUserAvailability.ts
📚 Learning: 2025-08-31T21:16:24.376Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.376Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.

Applied to files:

  • packages/lib/getUserAvailability.ts
⏰ 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 (6)
packages/lib/getUserAvailability.ts (6)

159-160: BookingLimits type fixed and precise. LGTM.
Null union moved outside Partial and value type simplified; matches intended shape.


321-321: Explicit Monday fallback for weekStart—good.
Aligns with repo-wide consistency decision.


410-418: Reuse gate for initialData when no PER_WEEK limits—LGTM.
The short-circuit avoids unnecessary recomputation when week alignment is irrelevant.


427-429: Threading rescheduleUid and weekStart into getBusyTimesFromLimits—LGTM.
Ensures correct weekly window alignment and reschedule handling.


618-620: getPeriodStartDatesBetween now forwards weekStart—LGTM.
Interfaces stay clean; alignment delegated to the util.


441-454: Confirm team weekly limits also honor weekStart.
If team limits include PER_WEEK, ensure getBusyTimesFromTeamLimits applies the same week boundary; otherwise results may misalign.

If supported by the cal.com API, pass weekStart through:

-      busyTimesFromTeamLimits = await getBusyTimesFromTeamLimits(
+      busyTimesFromTeamLimits = await getBusyTimesFromTeamLimits(
         user,
         teamBookingLimits,
         dateFrom.tz(finalTimezone),
         dateTo.tz(finalTimezone),
         teamForBookingLimits.id,
         teamForBookingLimits.includeManagedEventsInLimits,
         finalTimezone,
-        initialData?.rescheduleUid ?? undefined
+        initialData?.rescheduleUid ?? undefined,
+        /* weekStart */ user.weekStart ?? "Monday"
       );

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

♻️ Duplicate comments (1)
packages/lib/intervalLimits/limitManager.ts (1)

71-76: Fix: endOf('week') ignores custom weekStart; align with adjustWeekStart.

Using start.endOf("week") relies on locale week semantics and can disagree with the manager’s weekStart. Compute aligned week start/end using adjustWeekStart to ensure consistent keys and containment checks.

-    } else if (
-      unit === "week" &&
-      // weeks can be part of two months
-      ((this.busyMap.has(this.createKey(start, "month", timeZone)) &&
-        this.busyMap.has(this.createKey(start.endOf("week"), "month", timeZone))) ||
-        this.busyMap.has(this.createKey(start, "week", timeZone)))
-    ) {
+    } else if (unit === "week") {
+      // weeks can be part of two months; align week to custom weekStart
+      const alignedStart = this.adjustWeekStart(start, timeZone);
+      const alignedEnd = alignedStart.add(6, "days").endOf("day");
+      if (
+        (this.busyMap.has(this.createKey(alignedStart, "month", timeZone)) &&
+          this.busyMap.has(this.createKey(alignedEnd, "month", timeZone))) ||
+        this.busyMap.has(this.createKey(alignedStart, "week", timeZone))
+      ) {
+        return true;
+      }
+    } else if (
🧹 Nitpick comments (4)
packages/lib/intervalLimits/limitManager.ts (4)

16-18: Confirm default weekStart; consider centralizing the fallback.

Code defaults to "Monday". Retrieved learnings indicate other modules also fallback to Monday, but past discussion suggested "Sunday" as product default. Pick one fallback and centralize it (e.g., exported constant), or ensure callers always pass weekStart.

Possible tweak if Monday is the canonical fallback:

-  constructor(weekStart?: string) {
-    this.weekStart = weekStart || "Monday";
-  }
+  constructor(weekStart?: string) {
+    // TODO: import DEFAULT_WEEK_START from a single source if available
+    this.weekStart = weekStart ?? "Monday";
+  }

Would you like me to scan the repo for other implicit defaults and open a follow-up PR to unify them?


53-60: Week alignment helper is sound; consider reusing in createKey to DRY.

Minor: createKey re-implements the same math. Optionally call adjustWeekStart inside createKey for the week branch.

-    if (unit === "week") {
-      const weekStartIndex = weekStartNum(this.weekStart);
-      const currentDayIndex = tzStart.day();
-      const daysToSubtract = (currentDayIndex - weekStartIndex + 7) % 7;
-      const alignedStart = tzStart.subtract(daysToSubtract, "days").startOf("day");
+    if (unit === "week") {
+      const alignedStart = this.adjustWeekStart(tzStart, undefined);
       return `${unit}-${alignedStart.toISOString()}`;

12-13: Prefer named export over default export.

Project guideline suggests avoiding default exports for library modules to aid tree-shaking and refactors.

-export default class LimitManager {
+export class LimitManager {

This is breaking for import sites. If desired, I can generate a codemod to update imports across the repo.


94-111: AddBusyTime flow is consistent; small micro-optimization optional.

createKey recomputes TZ/alignment even when adjustedStart is already aligned. Not harmful; consider documenting the idempotency for future maintainers.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 40e1f0b and 9bf803f.

📒 Files selected for processing (1)
  • packages/lib/intervalLimits/limitManager.ts (3 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/lib/intervalLimits/limitManager.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/lib/intervalLimits/limitManager.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/lib/intervalLimits/limitManager.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.484Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.376Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.
📚 Learning: 2025-08-31T21:16:24.376Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.376Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.

Applied to files:

  • packages/lib/intervalLimits/limitManager.ts
📚 Learning: 2025-08-31T21:11:58.484Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.484Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.

Applied to files:

  • packages/lib/intervalLimits/limitManager.ts
📚 Learning: 2025-07-28T11:50:23.946Z
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

Applied to files:

  • packages/lib/intervalLimits/limitManager.ts
⏰ 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). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (2)
packages/lib/intervalLimits/limitManager.ts (2)

23-35: Key generation logic for 'week' looks correct and idempotent.

Alignment respects timeZone and weekStart; passing an already adjusted start keeps daysToSubtract at 0. Good.


40-48: Weekly period end calculation aligns with custom weekStart.

Using +6 days from aligned start is correct and avoids locale-dependent endOf('week').

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

♻️ Duplicate comments (1)
packages/lib/intervalLimits/limitManager.ts (1)

71-76: Fix locale-dependent endOf('week') check; align to custom weekStart + timeZone.

Using endOf("week") ignores the configured weekStart and may misclassify weeks across month boundaries. Compute aligned weekly start/end via adjustWeekStart/getPeriodEnd before month-key checks.

-    } else if (
-      unit === "week" &&
-      // weeks can be part of two months
-      ((this.busyMap.has(this.createKey(start, "month", timeZone)) &&
-        this.busyMap.has(this.createKey(start.endOf("week"), "month", timeZone))) ||
-        this.busyMap.has(this.createKey(start, "week", timeZone)))
-    ) {
-      return true;
+    } else if (unit === "week") {
+      const alignedStart = this.adjustWeekStart(start, timeZone);
+      const alignedEnd = this.getPeriodEnd(alignedStart, "week", timeZone);
+      const crossesMonths =
+        this.busyMap.has(this.createKey(alignedStart, "month", timeZone)) &&
+        this.busyMap.has(this.createKey(alignedEnd, "month", timeZone));
+      if (crossesMonths || this.busyMap.has(this.createKey(alignedStart, "week", timeZone))) {
+        return true;
+      }
#!/bin/bash
# Find remaining locale-based week boundaries in interval limits code
rg -nP -C2 --type=ts '\.(startOf|endOf)\(\s*["'\'']week["'\'']\s*\)' packages/lib/intervalLimits
🧹 Nitpick comments (3)
packages/lib/intervalLimits/limitManager.ts (1)

23-35: DRY: reuse adjustWeekStart() inside createKey for weekly keys.

Avoid duplicating the week-alignment logic and ensure identical behavior everywhere.

-  private createKey(start: Dayjs, unit: IntervalLimitUnit, timeZone?: string): BusyMapKey {
-    const tzStart = timeZone ? start.tz(timeZone) : start;
-
-    if (unit === "week") {
-      const weekStartIndex = weekStartNum(this.weekStart);
-      const currentDayIndex = tzStart.day();
-      const daysToSubtract = (currentDayIndex - weekStartIndex + 7) % 7;
-      const alignedStart = tzStart.subtract(daysToSubtract, "days").startOf("day");
-      return `${unit}-${alignedStart.toISOString()}`;
-    } else {
-      return `${unit}-${tzStart.startOf(unit).toISOString()}`;
-    }
-  }
+  private createKey(start: Dayjs, unit: IntervalLimitUnit, timeZone?: string): BusyMapKey {
+    const tzStart = timeZone ? start.tz(timeZone) : start;
+    if (unit === "week") {
+      const alignedStart = this.adjustWeekStart(start, timeZone);
+      return `${unit}-${alignedStart.toISOString()}`;
+    }
+    return `${unit}-${tzStart.startOf(unit).toISOString()}`;
+  }
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)

36-47: Minor: compute weekStartName/index once to avoid duplication.

Small readability/maintenance win.

-  const lastStart =
-    period === "week"
-      ? (() => {
-          const weekStartName = weekStart || "Monday";
-          const weekStartIndex = weekStartNum(weekStartName);
+  const weekStartName = weekStart || "Monday";
+  const weekStartIndex = period === "week" ? weekStartNum(weekStartName) : 0;
+  const lastStart =
+    period === "week"
+      ? (() => {
           const currentDayIndex = tzDateTo.day();
           const daysToSubtract = (currentDayIndex - weekStartIndex + 7) % 7;
           return tzDateTo.subtract(daysToSubtract, "day").startOf("day");
         })()
       : tzDateTo.startOf(period);
packages/lib/getUserAvailability.ts (1)

418-429: Thread weekStart through all weekly limit paths (team limits too?).

You pass weekStart to getBusyTimesFromLimits; confirm whether getBusyTimesFromTeamLimits also supports weekStart. If yes, pass weekStart there as well to avoid misaligned weekly windows for team-level PER_WEEK limits (see Lines 444-454).

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 9bf803f and 0cec474.

📒 Files selected for processing (5)
  • packages/lib/getUserAvailability.ts (5 hunks)
  • packages/lib/intervalLimits/limitManager.ts (3 hunks)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (8 hunks)
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1 hunks)
  • packages/prisma/selects/user.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/prisma/selects/user.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/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.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/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.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/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
🧠 Learnings (5)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.484Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.376Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.
📚 Learning: 2025-08-31T21:11:58.484Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.484Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.

Applied to files:

  • packages/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
📚 Learning: 2025-08-31T21:16:24.376Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.376Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.

Applied to files:

  • packages/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
📚 Learning: 2025-07-28T11:50:23.946Z
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

Applied to files:

  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
📚 Learning: 2025-08-22T16:38:00.225Z
Learnt from: bandhan-majumder
PR: calcom/cal.com#23192
File: packages/lib/server/service/InsightsBookingBaseService.ts:814-816
Timestamp: 2025-08-22T16:38:00.225Z
Learning: In the InsightsBookingBaseService (packages/lib/server/service/InsightsBookingBaseService.ts), when filtering for "accepted" bookings in getMembersStatsWithCount(), using `endTime <= now()` in the SQL condition should be avoided as it conflicts with existing date filtering logic. The components already handle completion filtering by setting `endDate: currentTime` in their query parameters, making additional SQL-level endTime filtering unnecessary and potentially problematic.

Applied to files:

  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
🧬 Code graph analysis (2)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
packages/lib/sentryWrapper.ts (1)
  • withReporting (107-139)
packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (2)
packages/lib/intervalLimits/limitManager.ts (1)
  • LimitManager (12-130)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
  • getPeriodStartDatesBetween (61-64)
⏰ 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). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (13)
packages/lib/intervalLimits/limitManager.ts (2)

16-18: Default fallback to Monday looks consistent (per retrieved learnings).

Using "Monday" as the fallback aligns with getUserAvailability and getPeriodStartDatesBetween decisions noted in learnings. Please ensure callers don't assume "Sunday".


93-111: LGTM: addBusyTime aligns weekly starts and computes week-aware period ends.

Keying and stored ranges now respect weekStart and timeZone.

packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (5)

27-34: Threading weekStart end-to-end is correct.

Instantiating LimitManager with weekStart and forwarding it into booking-limits path looks good.

Also applies to: 47-48


112-119: Good: period enumeration respects weekStart and timeZone.

Passing weekStart into getPeriodStartDatesBetween prevents misaligned windows.


147-147: Correct weekly periodEnd computation.

Using add(6, "day").endOf("day") avoids locale week semantics and matches LimitManager.getPeriodEnd.


173-175: Duration-limits: weekStart-aware start dates.

Consistent with booking-limits path.

Also applies to: 181-181


211-211: Duration-limits: correct weekly periodEnd.

Matches booking-limits and LimitManager behavior.

packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (3)

24-35: Start alignment for weekly periods is correct (Monday fallback per learnings).

TimeZone-aware alignment + Monday fallback matches the chosen convention.


48-56: LGTM: inclusive loop to lastStart with week-aware increment.

Clean and predictable.


61-64: withReporting wrapper application looks fine.

Name provided; will no-op when Sentry env is absent.

packages/lib/getUserAvailability.ts (3)

159-160: Type fix looks correct.

The BookingLimits alias now accurately models a partial map or null.


321-321: Explicit Monday fallback for weekStart — good.

This aligns with the chosen default and avoids undefined propagation.


618-620: Wrapper signature extension is sensible.

Optional weekStart at the end preserves back-compat and makes alignment explicit.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (2)

234-243: Thread weekStart through team-limits path for consistency.

Team limits still instantiate LimitManager without weekStart and don’t pass weekStart to getBusyTimesFromBookingLimits. This can reintroduce misaligned weekly windows when user preference is not Sunday.

Apply:

-const _getBusyTimesFromTeamLimits = async (
+const _getBusyTimesFromTeamLimits = async (
   user: { id: number; email: string },
   bookingLimits: IntervalLimit,
   dateFrom: Dayjs,
   dateTo: Dayjs,
   teamId: number,
   includeManagedEvents: boolean,
-  timeZone: string,
-  rescheduleUid?: string
+  timeZone: string,
+  rescheduleUid?: string,
+  weekStart?: string
 ) => {
@@
-  const limitManager = new LimitManager();
+  const limitManager = new LimitManager(weekStart);
@@
   await getBusyTimesFromBookingLimits({
     bookings: busyTimes,
     bookingLimits,
     dateFrom,
     dateTo,
     limitManager,
     rescheduleUid,
     teamId,
     user,
     includeManagedEvents,
     timeZone,
+    weekStart,
   });

Note: update call sites accordingly.

Also applies to: 269-282


78-163: Replace hardcoded end-of-week with week-aware period end in LimitManager
In packages/lib/intervalLimits/limitManager.ts at line 74, start.endOf("week") still ignores the weekStart override. Change that call to:

this.busyMap.has(
  this.createKey(
    this.getPeriodEnd(start, "week", timeZone),
    "month",
    timeZone
  )
)

so weekly boundaries respect the configured weekStart.

🧹 Nitpick comments (3)
packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (1)

121-121: Pass timeZone into LimitManager checks to avoid key skew.

LimitManager.createKey re-normalizes by timeZone when provided. Passing the same timeZone here removes any chance of mismatched keys if a non-tz Dayjs slips in.

Apply:

-      if (limitManager.isAlreadyBusy(periodStart, unit)) continue;
+      if (limitManager.isAlreadyBusy(periodStart, unit, timeZone || undefined)) continue;
@@
-          if (periodStartDates.every((start) => limitManager.isAlreadyBusy(start, unit))) {
+          if (periodStartDates.every((start) => limitManager.isAlreadyBusy(start, unit, timeZone || undefined))) {
             return;
           }
@@
-          limitManager.addBusyTime(periodStart, unit);
+          limitManager.addBusyTime(periodStart, unit, timeZone || undefined);
@@
-        limitManager.addBusyTime(periodStart, unit);
+        limitManager.addBusyTime(periodStart, unit, timeZone || undefined);

And in duration-limits:

-      if (limitManager.isAlreadyBusy(periodStart, unit)) continue;
+      if (limitManager.isAlreadyBusy(periodStart, unit, timeZone)) continue;
@@
-        limitManager.addBusyTime(periodStart, unit);
+        limitManager.addBusyTime(periodStart, unit, timeZone);
@@
-          if (periodStartDates.every((start) => limitManager.isAlreadyBusy(start, unit))) {
+          if (periodStartDates.every((start) => limitManager.isAlreadyBusy(start, unit, timeZone))) {
             return;
           }
@@
-          limitManager.addBusyTime(periodStart, unit);
+          limitManager.addBusyTime(periodStart, unit, timeZone);

Also applies to: 139-141, 157-159, 184-185, 190-191, 203-206, 221-223

packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (2)

18-22: Nit: small micro-allocations in the weekly loop.

Cache weekStartIndex once to avoid recomputing it for lastStart; minor but cheap.

-  if (period === "week") {
-    const weekStartName = weekStart || "Monday";
-    const weekStartIndex = weekStartNum(weekStartName);
+  if (period === "week") {
+    const weekStartName = weekStart || "Monday";
+    const weekStartIndex = weekStartNum(weekStartName);
@@
-  const lastStart =
-    period === "week"
-      ? (() => {
-          const weekStartName = weekStart || "Monday";
-          const weekStartIndex = weekStartNum(weekStartName);
+  const lastStart =
+    period === "week"
+      ? (() => {
           const currentDayIndex = tzDateTo.day();
           const daysToSubtract = (currentDayIndex - weekStartIndex + 7) % 7;
           return tzDateTo.subtract(daysToSubtract, "day").startOf("day");
         })()
       : tzDateTo.startOf(period);

Also applies to: 36-47, 51-55


48-56: Add DST-crossing tests for weekly ranges.

Ensure loops spanning DST transitions still yield midnight-aligned starts in the target timeZone.

I can add tests for a zone like America/New_York with dateFrom/dateTo around March/November transitions.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 0cec474 and c375053.

📒 Files selected for processing (5)
  • packages/lib/getUserAvailability.ts (5 hunks)
  • packages/lib/intervalLimits/limitManager.ts (3 hunks)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (8 hunks)
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1 hunks)
  • packages/prisma/selects/user.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/prisma/selects/user.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/getUserAvailability.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/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.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/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.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/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.
📚 Learning: 2025-08-31T21:16:24.415Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.

Applied to files:

  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
📚 Learning: 2025-08-31T21:11:58.503Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.

Applied to files:

  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
📚 Learning: 2025-07-28T11:50:23.946Z
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

Applied to files:

  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
🧬 Code graph analysis (2)
packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (2)
packages/lib/intervalLimits/limitManager.ts (1)
  • LimitManager (12-130)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
  • getPeriodStartDatesBetween (61-64)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
packages/lib/sentryWrapper.ts (1)
  • withReporting (107-139)
🔇 Additional comments (7)
packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (5)

27-34: Good: weekStart plumbed into the top-level and LimitManager.

Threading weekStart through the entry point and constructing LimitManager with it is the right call. This is necessary for consistent weekly windows.


112-119: Correct: weekly-aware period starts now respect weekStart and timeZone.

Passing weekStart into getPeriodStartDatesBetween fixes the original bug vector.


147-147: Fix: week periodEnd no longer uses locale week semantics.

Using periodStart.add(6, "day").endOf("day") avoids endOf("week") mismatches.


173-176: Consistent weekly boundary handling in duration-limits path.

Mirrors the booking-limits fix; keeps start/end aligned to weekStart.

Also applies to: 181-181, 211-211


78-163: Check duration-limit inequality matches product semantics.

Code uses > for both initial selectedDuration and running sum comparisons. If “limit” is intended as an inclusive cap (at most X minutes), this is correct; if it’s exclusive (< X), it should be >=. Please confirm.

Would you like me to add unit tests covering both branches (== and >) for week/month/year to lock intent?

Also applies to: 165-227

packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (2)

24-34: Week boundaries now correctly honor weekStart at both ends.

Start and end alignment logic is consistent and timeZone-aware; this addresses the root cause.

Also applies to: 36-47, 48-56


8-15: API surface change looks good; default fallback “Monday” matches repo convention.

Signature additions (timeZone, weekStart) and withReporting wrapper remain clean.

Also applies to: 61-64

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

♻️ Duplicate comments (1)
packages/features/bookings/lib/handleNewBooking.ts (1)

711-716: Ensure default choice matches LimitManager/check*Limits defaults.

If you adopt Monday elsewhere, switch the fallback to "Monday" here. Inconsistent fallbacks will shift weekly windows and reintroduce the bug this PR fixes.

#!/bin/bash
rg -nP 'weekStartNum\([^)]*\?\? +"(?i:sunday|monday)"' --type=ts --type=tsx -C2
🧹 Nitpick comments (10)
packages/lib/intervalLimits/limitManager.ts (4)

23-35: Deduplicate week alignment logic.

createKey re-implements the alignment done in adjustWeekStart. Use adjustWeekStart for the weekly branch to keep a single source of truth.

Apply:

-    if (unit === "week") {
-      const weekStartIndex = weekStartNum(this.weekStart);
-      const currentDayIndex = tzStart.day();
-      const daysToSubtract = (currentDayIndex - weekStartIndex + 7) % 7;
-      const alignedStart = tzStart.subtract(daysToSubtract, "days").startOf("day");
-      return `${unit}-${alignedStart.toISOString()}`;
-    } else {
+    if (unit === "week") {
+      const alignedStart = this.adjustWeekStart(tzStart, timeZone);
+      return `${unit}-${alignedStart.toISOString()}`;
+    } else {
       return `${unit}-${tzStart.startOf(unit).toISOString()}`;
     }

53-60: Tiny perf/readability nit: inline local vars.

You can inline currentDayIndex to shorten the function; behavior unchanged.

-    const currentDayIndex = tzStart.day();
-
-    const daysToSubtract = (currentDayIndex - weekStartIndex + 7) % 7;
+    const daysToSubtract = (tzStart.day() - weekStartIndex + 7) % 7;

65-87: Week spanning two months logic is sound; consider short-circuit on month busy.

If alignedStart and alignedEnd are in the same month, the double-month check reduces to a single month check. Minor micro-opt: early-return if weekStartMonth === weekEndMonth.

-      // Check if week spans two months and both months are busy
-      const weekStartMonth = this.createKey(alignedStart, "month", timeZone);
-      const weekEndMonth = this.createKey(alignedEnd, "month", timeZone);
+      const weekStartMonth = this.createKey(alignedStart, "month", timeZone);
+      const weekEndMonth = this.createKey(alignedEnd, "month", timeZone);
+      if (weekStartMonth === weekEndMonth && this.busyMap.has(weekStartMonth)) {
+        return true;
+      }

12-12: Prefer named exports over default exports.

Default exports hinder tree-shaking and refactors. Consider export class LimitManager {} and update imports.

packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts (1)

15-16: Strongly type weekStartDay as a day index (0-6).

Prevents accidental out-of-range values and clarifies intent.

-type InputProps = {
+type DayIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6;
+type InputProps = {
   eventType: EventType;
   reqBodyStart: string;
   reqBodyRescheduleUid?: string;
-  weekStartDay?: number;
+  weekStartDay?: DayIndex;
 };
packages/features/bookings/lib/handleNewBooking.ts (2)

711-716: Derive weekStart from the primary/organizer user and add a safe fallback.

Using users[0] can be wrong for team events; prefer the event owner/organizer or the user matching eventType.userId. Also guard against undefined weekStart.

-    weekStartDay: weekStartNum(eventType.users[0].weekStart),
+    weekStartDay: weekStartNum(
+      (eventType.users.find((u) => u.id === eventType.userId) ?? eventType.users[0])?.weekStart ?? "Sunday"
+    ),

1-1: Prefer named exports over default exports.

Consider export function handler(...) and update imports. Low priority, follow-up acceptable.

packages/lib/intervalLimits/server/checkBookingLimits.ts (3)

82-88: Normalize weekStartDay input and guard against invalid values

Clamp to [0–6] and fall back to Monday if undefined/NaN to avoid edge-case regressions.

-    // Custom week calculation based on user's week start day
+    // Custom week calculation based on user's week start day
+    const normalizeWeekStart = (val: number | undefined): WeekStartDay => {
+      const n = Number(val);
+      return Number.isFinite(n) ? (((n % 7) + 7) % 7) as WeekStartDay : 1;
+    };

93-102: Use normalized week start and reduce duplication risk

Compute a normalized index once; also consider extracting these helpers to a shared util already used by getPeriodStartDatesBetween/LimitManager to keep week-boundary logic consistent.

-    let startDate: Date;
-    let endDate: Date;
+    let startDate: Date;
+    let endDate: Date;

     if (unit === "week") {
-      startDate = getCustomWeekStart(eventDateInOrganizerTz, weekStartDay).toDate();
-      endDate = getCustomWeekEnd(eventDateInOrganizerTz, weekStartDay).toDate();
+      const ws = normalizeWeekStart(weekStartDay);
+      startDate = getCustomWeekStart(eventDateInOrganizerTz, ws).toDate();
+      endDate = getCustomWeekEnd(eventDateInOrganizerTz, ws).toDate();
     } else {
       startDate = dayjs(eventDateInOrganizerTz).startOf(unit).toDate();
       endDate = dayjs(eventDateInOrganizerTz).endOf(unit).toDate();
     }

24-26: Constrain weekStartDay to valid values 0–6
Define

type WeekStartDay = 0 | 1 | 2 | 3 | 4 | 5 | 6;

and replace every weekStartDay?: number parameter in packages/lib/intervalLimits/server/checkBookingLimits.ts with weekStartDay?: WeekStartDay. Then update all callers (e.g. in features/bookings/lib/handleNewBooking.ts and checkBookingAndDurationLimits.ts) to pass a WeekStartDay (for example, casting weekStartNum(...) as WeekStartDay).

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 c375053 and 14ee144.

📒 Files selected for processing (5)
  • packages/features/bookings/lib/handleNewBooking.ts (2 hunks)
  • packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts (3 hunks)
  • packages/lib/getUserAvailability.ts (5 hunks)
  • packages/lib/intervalLimits/limitManager.ts (2 hunks)
  • packages/lib/intervalLimits/server/checkBookingLimits.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/lib/getUserAvailability.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/features/bookings/lib/handleNewBooking.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.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/handleNewBooking.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.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/features/bookings/lib/handleNewBooking.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.ts
🧠 Learnings (5)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.
📚 Learning: 2025-08-31T21:11:58.503Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.

Applied to files:

  • packages/features/bookings/lib/handleNewBooking.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.ts
📚 Learning: 2025-08-31T21:16:24.415Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.

Applied to files:

  • packages/features/bookings/lib/handleNewBooking.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.ts
📚 Learning: 2025-07-28T11:50:23.946Z
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

Applied to files:

  • packages/lib/intervalLimits/limitManager.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/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts
🧬 Code graph analysis (1)
packages/lib/intervalLimits/limitManager.ts (1)
packages/types/Calendar.d.ts (1)
  • IntervalLimitUnit (138-138)
⏰ 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). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (5)
packages/lib/intervalLimits/limitManager.ts (2)

40-48: LGTM: period end for weeks now respects custom week alignment.

The 6-day span with endOf("day") matches the aligned start; DST is handled by dayjs-timezone.


97-115: LGTM: addBusyTime now aligns starts and computes period ends consistently.

Key generation and stored ranges look coherent with isAlreadyBusy.

packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts (2)

30-35: LGTM: threading weekStartDay through the internal method.


47-50: Use nullish coalescing for weekStartDay default
In the call to checkBookingLimits, replace weekStartDay || 0 with weekStartDay ?? 0 so that a valid 0 (Sunday) isn’t treated as falsy. The undefined argument correctly aligns with the includeManagedEvents parameter.

-          eventType.schedule?.timeZone,
-          undefined,
-          weekStartDay || 0
+          eventType.schedule?.timeZone,
+          undefined,
+          weekStartDay ?? 0
packages/features/bookings/lib/handleNewBooking.ts (1)

82-82: LGTM: importing weekStartNum where used.

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

🧹 Nitpick comments (1)
packages/lib/defaultEvents.ts (1)

215-215: Prefer named export over default export

Repo guideline favors named exports for better tree-shaking and refactors. Consider removing the default export.

Apply:

-export default defaultEvents;

Then update consumers: import { defaultEvents } from "@calcom/lib/defaultEvents";

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 c9f91fd and 4644a0a.

📒 Files selected for processing (1)
  • packages/lib/defaultEvents.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:

  • packages/lib/defaultEvents.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/lib/defaultEvents.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/lib/defaultEvents.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.
📚 Learning: 2025-08-31T21:11:58.503Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.

Applied to files:

  • packages/lib/defaultEvents.ts
📚 Learning: 2025-08-31T21:16:24.415Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.

Applied to files:

  • packages/lib/defaultEvents.ts
⏰ 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: Type check / check-types
  • GitHub Check: Tests / Unit
  • GitHub Check: Linters / lint

@SinghaAnirban005
Copy link
Contributor Author

@kart1ka PTAL !!

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)
packages/lib/intervalLimits/limitManager.ts (5)

14-18: Strongly type weekStart + confirm default alignment across callers

  • Prefer a constrained type (e.g., WeekStartName) over string to prevent invalid inputs.
  • Defaulting to "Monday" matches the retrieved learnings for getUserAvailability and getPeriodStartDatesBetween; please verify all call sites share the same fallback to avoid divergent behavior when user.weekStart is undefined.

We used your retrieved learnings for this recommendation.

Apply:

-import { weekStartNum } from "@calcom/lib/weekstart";
+import { weekStartNum } from "@calcom/lib/weekstart";
+import type { WeekStartName } from "@calcom/lib/weekstart";

-  private weekStart: string;
+  private weekStart: WeekStartName;

-  constructor(weekStart?: string) {
+  constructor(weekStart?: WeekStartName) {
     this.weekStart = weekStart || "Monday";
   }

23-35: Deduplicate weekly alignment logic by reusing adjustWeekStart

createKey re-implements the same alignment done in adjustWeekStart. Centralize to avoid drift.

-    if (unit === "week") {
-      const weekStartIndex = weekStartNum(this.weekStart);
-      const currentDayIndex = tzStart.day();
-      const daysToSubtract = (currentDayIndex - weekStartIndex + 7) % 7;
-      const alignedStart = tzStart.subtract(daysToSubtract, "days").startOf("day");
-      return `${unit}-${alignedStart.toISOString()}`;
-    } else {
-      return `${unit}-${tzStart.startOf(unit).toISOString()}`;
-    }
+    if (unit === "week") {
+      const alignedStart = this.adjustWeekStart(start, timeZone);
+      return `${unit}-${alignedStart.toISOString()}`;
+    }
+    return `${unit}-${tzStart.startOf(unit).toISOString()}`;

37-48: Harden getPeriodEnd for weekly: align internally

Defensive alignment helps if future call sites forget to pass an already-aligned start.

-    if (unit === "week") {
-      return tzStart.add(6, "days").endOf("day");
-    } else {
-      return tzStart.endOf(unit);
-    }
+    if (unit === "week") {
+      const aligned = this.adjustWeekStart(start, timeZone);
+      return aligned.add(6, "day").endOf("day");
+    }
+    return tzStart.endOf(unit);

65-92: isAlreadyBusy: good coverage; add minor consistency checks

  • Logic for cross-month weekly windows is solid. Consider computing keys once to avoid repeated tz/alignment work.
  • Ensure all callers pass the same timeZone consistently; mixed TZs would create different keys for the same instant.

Optional micro-refactor:

-      const weekStartMonth = this.createKey(alignedStart, "month", timeZone);
-      const weekEndMonth = this.createKey(alignedEnd, "month", timeZone);
+      const monthKeyStart = this.createKey(alignedStart, "month", timeZone);
+      const monthKeyEnd = this.createKey(alignedEnd, "month", timeZone);
...
-        (this.busyMap.has(weekStartMonth) && this.busyMap.has(weekEndMonth)) ||
+        (this.busyMap.has(monthKeyStart) && this.busyMap.has(monthKeyEnd)) ||

97-115: addBusyTime: correct normalization + storage; add small cleanup

  • Flow is correct. Minor: getPeriodEnd re-applies tz() even when adjustedStart is already TZ’d; harmless but avoidable.
-    const periodEnd = this.getPeriodEnd(adjustedStart, unit, timeZone);
+    const periodEnd = this.getPeriodEnd(adjustedStart, unit, undefined);

Also consider asserting that managers merged via mergeBusyTimes share the same weekStart/timeZone policy to avoid mixed-key semantics.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 aff74fa and 5616e09.

📒 Files selected for processing (9)
  • packages/features/bookings/lib/handleNewBooking.ts (2 hunks)
  • packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts (3 hunks)
  • packages/lib/defaultEvents.ts (1 hunks)
  • packages/lib/getUserAvailability.ts (5 hunks)
  • packages/lib/intervalLimits/limitManager.ts (2 hunks)
  • packages/lib/intervalLimits/server/checkBookingLimits.ts (4 hunks)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (8 hunks)
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1 hunks)
  • packages/prisma/selects/user.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/lib/defaultEvents.ts
  • packages/prisma/selects/user.ts
  • packages/features/bookings/lib/handleNewBooking.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/getUserAvailability.ts
  • packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.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/lib/intervalLimits/limitManager.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/lib/intervalLimits/limitManager.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/lib/intervalLimits/limitManager.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.
📚 Learning: 2025-08-31T21:16:24.415Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.

Applied to files:

  • packages/lib/intervalLimits/limitManager.ts
📚 Learning: 2025-08-31T21:11:58.503Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.

Applied to files:

  • packages/lib/intervalLimits/limitManager.ts
📚 Learning: 2025-07-28T11:50:23.946Z
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

Applied to files:

  • packages/lib/intervalLimits/limitManager.ts
⏰ 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: Tests / Unit
  • GitHub Check: Type check / check-types
  • GitHub Check: Linters / lint
🔇 Additional comments (2)
packages/lib/intervalLimits/limitManager.ts (2)

2-2: LGTM: bringing in weekStartNum

Import is correct and scoped. No issues.


50-60: LGTM: week-start adjustment logic

Clear and correct alignment to custom weekStart with TZ awareness.

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 (4)
packages/features/bookings/lib/handleNewBooking.ts (2)

720-733: Derive weekStart from stable owner/host, not array[0]

Using the first user/host is order-sensitive. Prefer event owner; then any host with weekStart; then fallback.

Apply:

-  const getWeekStartFromEventType = (eventType: EventType): string => {
-    // For individual user events
-    if (eventType.users && eventType.users.length > 0 && eventType.users[0].weekStart) {
-      return eventType.users[0].weekStart;
-    }
-    // For team events
-    if (eventType.hosts && eventType.hosts.length > 0 && eventType.hosts[0].user?.weekStart) {
-      return eventType.hosts[0].user.weekStart;
-    }
-    return "Monday";
-  };
+  const getWeekStartFromEventType = (eventType: EventType): string => {
+    // Prefer the event owner (stable)
+    const owner = eventType.users?.find((u) => u.id === eventType.userId);
+    if (owner?.weekStart) return owner.weekStart;
+    // For team events, pick the first host that actually has weekStart set
+    const hostWithWeekStart = eventType.hosts?.find((h) => h.user?.weekStart)?.user;
+    if (hostWithWeekStart?.weekStart) return hostWithWeekStart.weekStart;
+    // Fallback: any user with weekStart
+    const anyUserWithWeekStart = eventType.users?.find((u) => !!u.weekStart);
+    if (anyUserWithWeekStart?.weekStart) return anyUserWithWeekStart.weekStart;
+    return "Monday";
+  };

2536-2536: Prefer named export over default

This is a library module; named exports ease refactors and tree-shaking.

-export default handler;
+export { handler };
packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (2)

112-119: Pass timeZone to LimitManager checks to avoid subtle tz/DST drift

isAlreadyBusy/addBusyTime accept timeZone; pass it for consistency with tz-aligned period starts.

-      if (limitManager.isAlreadyBusy(periodStart, unit)) continue;
+      if (limitManager.isAlreadyBusy(periodStart, unit, timeZone || undefined)) continue;
@@
-          limitManager.addBusyTime(periodStart, unit);
+          limitManager.addBusyTime(periodStart, unit, timeZone || undefined);
@@
-          limitManager.addBusyTime(periodStart, unit);
+          limitManager.addBusyTime(periodStart, unit, timeZone || undefined);

Also applies to: 147-159


181-182: Do the same tz pass-through in duration-limits path

Minor consistency fix; prevents edge cases around local vs tz math.

-    const periodStartDates = getPeriodStartDatesBetween(dateFrom, dateTo, unit, timeZone, weekStart);
+    const periodStartDates = getPeriodStartDatesBetween(dateFrom, dateTo, unit, timeZone, weekStart);
@@
-      if (limitManager.isAlreadyBusy(periodStart, unit)) continue;
+      if (limitManager.isAlreadyBusy(periodStart, unit, timeZone)) continue;
@@
-        limitManager.addBusyTime(periodStart, unit);
+        limitManager.addBusyTime(periodStart, unit, timeZone);
@@
-        if (totalDuration > limit) {
-          limitManager.addBusyTime(periodStart, unit);
+        if (totalDuration > limit) {
+          limitManager.addBusyTime(periodStart, unit, timeZone);

Also applies to: 210-214, 219-221

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 5616e09 and 003a8a9.

📒 Files selected for processing (3)
  • packages/features/bookings/lib/handleNewBooking.ts (3 hunks)
  • packages/lib/getUserAvailability.ts (6 hunks)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (11 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/features/bookings/lib/handleNewBooking.ts
  • packages/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.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/handleNewBooking.ts
  • packages/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.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/features/bookings/lib/handleNewBooking.ts
  • packages/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
🧠 Learnings (6)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.
📚 Learning: 2025-08-31T21:11:58.503Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.

Applied to files:

  • packages/features/bookings/lib/handleNewBooking.ts
  • packages/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
📚 Learning: 2025-08-31T21:16:24.415Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.

Applied to files:

  • packages/features/bookings/lib/handleNewBooking.ts
  • packages/lib/getUserAvailability.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
📚 Learning: 2025-08-21T13:44:06.805Z
Learnt from: supalarry
PR: calcom/cal.com#23217
File: apps/api/v2/src/ee/event-types/event-types_2024_06_14/services/output-event-types.service.ts:93-94
Timestamp: 2025-08-21T13:44:06.805Z
Learning: In apps/api/v2/src/ee/event-types/event-types_2024_06_14/event-types.repository.ts, repository functions that use explicit Prisma select clauses (like getEventTypeWithSeats) are used for specific purposes and don't need to include all EventType fields like bookingRequiresAuthentication. These methods don't feed into the general OutputEventTypesService_2024_06_14 flow.

Applied to files:

  • packages/features/bookings/lib/handleNewBooking.ts
📚 Learning: 2025-08-22T16:38:00.225Z
Learnt from: bandhan-majumder
PR: calcom/cal.com#23192
File: packages/lib/server/service/InsightsBookingBaseService.ts:814-816
Timestamp: 2025-08-22T16:38:00.225Z
Learning: In the InsightsBookingBaseService (packages/lib/server/service/InsightsBookingBaseService.ts), when filtering for "accepted" bookings in getMembersStatsWithCount(), using `endTime <= now()` in the SQL condition should be avoided as it conflicts with existing date filtering logic. The components already handle completion filtering by setting `endDate: currentTime` in their query parameters, making additional SQL-level endTime filtering unnecessary and potentially problematic.

Applied to files:

  • packages/lib/getUserAvailability.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/lib/getUserAvailability.ts
🧬 Code graph analysis (2)
packages/features/bookings/lib/handleNewBooking.ts (2)
packages/lib/getUserAvailability.ts (1)
  • EventType (62-62)
packages/lib/di/containers/BookingLimits.ts (1)
  • getCheckBookingAndDurationLimitsService (25-29)
packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (1)
packages/lib/intervalLimits/limitManager.ts (1)
  • LimitManager (12-134)
⏰ 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). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (10)
packages/features/bookings/lib/handleNewBooking.ts (2)

71-71: Week-start threading imports — LGTM

Type import and weekStartNum usage are appropriate for passing a normalized week-start to limits.

Also applies to: 84-84


739-740: Defaults and mappings align: weekStartNum("Monday") returns 1, and checkBookingLimits/checkBookingAndDurationLimits both default to weekStartDay = 1. handleNewBooking always passes a defined value (fallback “Monday” → 1), so no inconsistencies—no changes needed.

packages/lib/getUserAvailability.ts (6)

159-160: BookingLimits alias — LGTM

Type accurately captures a partial limits map or null.


321-322: Explicit Monday fallback — LGTM

Matches the agreed repo-wide default and avoids undefined downstream.


405-412: Weekly-limit cache gating — LGTM

Recomputation when either booking or duration limits include weekly units is correct.

Also applies to: 413-417


420-431: Threading weekStart into limits — LGTM

Passing weekStart into getBusyTimesFromLimits ensures aligned weekly windows.


443-457: Team-limits weekStart propagation — LGTM

Team limits now honor configured week boundaries.


620-623: Expose weekStart in period util wrapper — LGTM

Signature aligns with underlying util and callers.

packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (2)

18-34: End-to-end weekStart threading — LGTM

Accepting weekStart and constructing LimitManager(weekStart) aligns boundaries across both booking and duration paths.

Also applies to: 47-49, 55-67


242-244: Team-limits weekStart propagation — LGTM

Team-limit manager and booking-limits call now respect weekStart.

Also applies to: 270-271, 283-284

@SinghaAnirban005 SinghaAnirban005 force-pushed the bug/t branch 2 times, most recently from e022c77 to ae98ac7 Compare September 6, 2025 08:18
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 (4)
packages/lib/intervalLimits/server/checkBookingLimits.ts (2)

24-26: Narrow weekStartDay to 0–6 and sanitize before use.

Prevents bad inputs and keeps semantics consistent with Day.js’ 0–6. Also avoids silent coercion when callers pass unexpected values.

Apply:

@@
-    includeManagedEvents?: boolean,
-    weekStartDay?: number
+    includeManagedEvents?: boolean,
+    weekStartDay?: WeekStartDay
@@
+type WeekStartDay = 0 | 1 | 2 | 3 | 4 | 5 | 6;
@@
-    includeManagedEvents = false,
-    weekStartDay = 1,
+    includeManagedEvents = false,
+    weekStartDay = 1,
@@
-    weekStartDay?: number;
+    weekStartDay?: WeekStartDay;
@@
-    if (unit === "week") {
-      startDate = getCustomWeekStart(eventDateInOrganizerTz, weekStartDay).toDate();
-      endDate = getCustomWeekEnd(eventDateInOrganizerTz, weekStartDay).toDate();
+    if (unit === "week") {
+      const safeWeekStartDay = (((weekStartDay ?? 1) % 7) + 7) % 7 as WeekStartDay;
+      startDate = getCustomWeekStart(eventDateInOrganizerTz, safeWeekStartDay).toDate();
+      endDate = getCustomWeekEnd(eventDateInOrganizerTz, safeWeekStartDay).toDate();

Also applies to: 40-41, 63-75, 96-102


82-92: Consider deduplicating week-boundary logic.

This custom-week logic now exists here and in getPeriodStartDatesBetween; extracting a shared helper (e.g., alignToWeekStart(date, weekStartIdx)) would reduce drift.

packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)

16-17: Hoist weekStart computation to avoid duplicate work.

Minor DRY/readability win.

@@
-  let currentDate: Dayjs;
+  let currentDate: Dayjs;
+  const weekName = weekStart || "Monday";
+  const weekIndex = weekStartNum(weekName);
@@
-    const weekStartName = weekStart || "Monday";
-    const weekStartIndex = weekStartNum(weekStartName);
-
-    const currentDayIndex = currentDate.day();
-    const daysToSubtract = (currentDayIndex - weekStartIndex + 7) % 7;
+    const currentDayIndex = currentDate.day();
+    const daysToSubtract = (currentDayIndex - weekIndex + 7) % 7;
     currentDate = currentDate.subtract(daysToSubtract, "day").startOf("day");
@@
-          const weekStartName = weekStart || "Monday";
-          const weekStartIndex = weekStartNum(weekStartName);
-          const currentDayIndex = tzDateTo.day();
-          const daysToSubtract = (currentDayIndex - weekStartIndex + 7) % 7;
+          const currentDayIndex = tzDateTo.day();
+          const daysToSubtract = (currentDayIndex - weekIndex + 7) % 7;
           return tzDateTo.subtract(daysToSubtract, "day").startOf("day");

Also applies to: 26-28, 40-46

packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (1)

147-147: DST-safe weekly period end.

Using +6 days endOf("day") can drift around DST transitions. Prefer start + 1 week - 1 ms.

-      const periodEnd = unit === "week" ? periodStart.add(6, "day").endOf("day") : periodStart.endOf(unit);
+      const periodEnd =
+        unit === "week"
+          ? periodStart.add(1, "week").subtract(1, "millisecond")
+          : periodStart.endOf(unit);

Apply at both occurrences.

Also applies to: 211-211

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • 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 e022c77 and ae98ac7.

📒 Files selected for processing (9)
  • packages/features/bookings/lib/handleNewBooking.ts (2 hunks)
  • packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts (3 hunks)
  • packages/lib/defaultEvents.ts (1 hunks)
  • packages/lib/getUserAvailability.ts (6 hunks)
  • packages/lib/intervalLimits/limitManager.ts (2 hunks)
  • packages/lib/intervalLimits/server/checkBookingLimits.ts (4 hunks)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (11 hunks)
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1 hunks)
  • packages/prisma/selects/user.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/lib/defaultEvents.ts
  • packages/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits.ts
  • packages/features/bookings/lib/handleNewBooking.ts
  • packages/lib/intervalLimits/limitManager.ts
  • packages/prisma/selects/user.ts
  • packages/lib/getUserAvailability.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/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.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/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.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/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.
📚 Learning: 2025-08-31T21:16:24.415Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts:36-47
Timestamp: 2025-08-31T21:16:24.415Z
Learning: In packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts, the user has decided to keep "Monday" as the fallback default for weekStart parameter to maintain consistency across the cal.com codebase.

Applied to files:

  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
📚 Learning: 2025-08-31T21:11:58.503Z
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23400
File: packages/lib/getUserAvailability.ts:321-322
Timestamp: 2025-08-31T21:11:58.503Z
Learning: In the getUserAvailability function in packages/lib/getUserAvailability.ts, weekStart should default to "Monday" when user?.weekStart is undefined for consistency across the codebase.

Applied to files:

  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/intervalLimits/server/checkBookingLimits.ts
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
📚 Learning: 2025-07-28T11:50:23.946Z
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

Applied to files:

  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
🧬 Code graph analysis (2)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
packages/lib/sentryWrapper.ts (1)
  • withReporting (107-139)
packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (2)
packages/lib/intervalLimits/limitManager.ts (1)
  • LimitManager (12-134)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
  • getPeriodStartDatesBetween (61-64)
⏰ 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
🔇 Additional comments (5)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (2)

24-47: Weekly alignment with Monday fallback — LGTM.

Matches repo convention and fixes the off-by-week bug when weekStart ≠ locale start.


48-56: Confirm inclusivity of the last period.

Loop is inclusive of lastStart; please ensure tests cover cases where dateTo lands mid-week and exactly on a boundary.

packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (3)

27-48: End-to-end weekStart threading — LGTM.

weekStart now flows through the main, booking, and duration paths; LimitManager instantiated with the same context.

Also applies to: 66-67


112-118: Correct: period starts now use week-aware utility.


242-244: Team limits path weekStart — LGTM.

Signature, LimitManager construction, and downstream call all respect weekStart.

Also applies to: 270-270, 283-284

@SinghaAnirban005
Copy link
Contributor Author

@kart1ka I have resolve all type errors and coderabbit suggestions
Kindly review
Thank You

SinghaAnirban005 and others added 15 commits September 9, 2025 23:41
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <anirbansingha20@gmail.com>
Signed-off-by: Anirban Singha <143536290+SinghaAnirban005@users.noreply.github.com>
Signed-off-by: Anirban Singha <143536290+SinghaAnirban005@users.noreply.github.com>
@github-actions
Copy link
Contributor

This PR is being marked as stale due to inactivity.

@github-actions github-actions bot added Stale and removed Stale labels Sep 24, 2025
@pallava-joshi
Copy link
Contributor

@cubic-dev-ai leave a review.

@cubic-dev-ai
Copy link
Contributor

cubic-dev-ai bot commented Dec 4, 2025

@cubic-dev-ai leave a review.

@pallava-joshi I've started the AI code review. It'll take a few minutes to complete.

Copy link
Contributor

@pallava-joshi pallava-joshi left a comment

Choose a reason for hiding this comment

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

can you please resolve the merge conflicts. marking it draft until then.

@pallava-joshi pallava-joshi marked this pull request as draft December 4, 2025 18:28
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.

No issues found across 9 files

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 Low priority Created by Linear-GitHub Sync size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Issues with limit booking frequency and the day start of the week

2 participants