Skip to content

fix: duplicate event created in attendee calendar due to incorrect icalUid#23658

Merged
anikdhabal merged 4 commits intocalcom:mainfrom
saurabhraghuvanshii:reassing
Sep 9, 2025
Merged

fix: duplicate event created in attendee calendar due to incorrect icalUid#23658
anikdhabal merged 4 commits intocalcom:mainfrom
saurabhraghuvanshii:reassing

Conversation

@saurabhraghuvanshii
Copy link
Contributor

@saurabhraghuvanshii saurabhraghuvanshii commented Sep 7, 2025

What does this PR do?

duplicate event created in attendee calendar due to incorrect icalUid

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 7, 2025

Walkthrough

Adds propagation of booking iCal UID into CalendarEvent payloads and a fallback for reschedule handling: two reassignment entry points now set iCalUID: booking.iCalUID on the constructed evt, and the reschedule manager uses the original booking iCal UID when calendar update results lack an iCalUID. No other control flow, error handling, or public/exported signatures were changed.

Assessment against linked issues

Objective Addressed Explanation
Ensure old calendar entries are removed when reassigning round-robin events by cleaning up across all of the previous host’s destination calendars (#23446, CAL-6349) Changes only propagate and fallback the iCal UID; they do not modify calendar deletion/cleanup behavior.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
iCal UID propagation and fallback (packages/features/ee/round-robin/*.ts) Focuses on carrying iCalUID through reassignment/reschedule flows; does not alter calendar cleanup or deletion logic.

Possibly related PRs

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.

Pre-merge checks (4 passed, 1 warning)

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Linked Issues Check ⚠️ Warning While the changes correctly propagate and fallback the iCalUID, they do not implement any logic to delete or clean up the previous host’s calendar events as required by issue #23446, so the primary objective of removing old events before reassignment is unmet. Include code to locate and delete old host calendar events using findMany and cleanup routines before creating or updating the new event, in line with the objectives of #23446.
✅ Passed checks (4 passed)
Check name Status Explanation
Out of Scope Changes Check ✅ Passed All modifications are focused on improving iCalUID handling for event updates and reschedules, and no unrelated or extraneous changes outside the scope of calendar reassignment logic have been introduced.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
Title Check ✅ Passed The title clearly summarizes the primary fix by highlighting the incorrect iCalUID issue and its impact on duplicate calendar events, which directly aligns with the changes introduced to propagate the correct UID and prevent duplicates.
Description Check ✅ Passed The description, though brief, directly references the core problem—duplicate attendee events caused by an incorrect iCalUID—and is therefore on-topic and relevant to the changeset.
✨ 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.

@vercel
Copy link

vercel bot commented Sep 7, 2025

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

A member of the Team first needs to authorize it.

@graphite-app graphite-app bot added the community Created by Linear-GitHub Sync label Sep 7, 2025
@graphite-app graphite-app bot requested review from a team September 7, 2025 13:36
@github-actions github-actions bot added Low priority Created by Linear-GitHub Sync teams area: teams, round robin, collective, managed event-types 🐛 bug Something isn't working labels Sep 7, 2025
@dosubot dosubot bot added the bookings area: bookings, availability, timezones, double booking label Sep 7, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

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

⚠️ Outside diff range comments (2)
packages/features/ee/round-robin/roundRobinReassignment.ts (1)

342-353: Avoid Prisma include; rely on top-level organizer email or use select

We already have organizer.email. The extra include of user.email on credentials is unnecessary and violates our “no include, prefer select” rule for Prisma.

Apply:

-  const credentials = await prisma.credential.findMany({
-    where: {
-      userId: organizer.id,
-    },
-    include: {
-      user: {
-        select: {
-          email: true,
-        },
-      },
-    },
-  });
+  const credentials = await prisma.credential.findMany({
+    where: { userId: organizer.id },
+  });

Optionally, further tighten with a select of only the credential fields consumed by enrichUserWithDelegationCredentialsIncludeServiceAccountKey.

packages/features/ee/round-robin/roundRobinManualReassignment.ts (1)

311-314: Drop Prisma include; prefer select or rely on existing organizer context

Including user.email on credentials is unnecessary; you already have organizer/newUser email at the top level. Remove include to comply with our “no include” rule. If you need specific credential fields, add an explicit select instead.

-  const credentials = await prisma.credential.findMany({
-    where: { userId: newUser.id },
-    include: { user: { select: { email: true } } },
-  });
+  const credentials = await prisma.credential.findMany({
+    where: { userId: newUser.id },
+  });
🧹 Nitpick comments (4)
packages/features/ee/round-robin/roundRobinReassignment.ts (2)

470-471: Prefer named export over default export

Project guideline favors named exports for better tree-shaking and refactors.

-export default roundRobinReassignment;
+export { roundRobinReassignment };

298-306: Fetch-all calendars is correct; consider narrowing Prisma selection and confirm manager expects an array

  • Switching to findMany ensures all destination calendars are considered for cleanup; passing an array into the rescheduler matches the intent.
  • Recommendation: follow our Prisma guideline and select only fields needed by the cleanup (rather than returning full rows). If the rescheduler only needs identifiers (e.g., id, externalCalendarId, credentialId, integration), add a select clause to reduce payload and risk surface.

Run to confirm the rescheduler now expects an array and what fields it uses:

#!/bin/bash
# Show handleRescheduleEventManager signature and usages of previousHostDestinationCalendar
rg -nP -C3 '(export\s+)?(async\s+)?(function|const)\s+handleRescheduleEventManager\b' 
rg -nP -C3 'previousHostDestinationCalendar\b' packages | sed -n '1,120p'

Also applies to: 364-365

packages/features/ee/round-robin/roundRobinManualReassignment.ts (2)

570-571: Prefer named export

Switch to named export to follow repo conventions.

-export default roundRobinManualReassignment;
+export { roundRobinManualReassignment };

320-325: Good: fetch all previous host calendars and pass array; narrow selection for Prisma

findMany + passing an array fixes multi-calendar cleanup. To align with our Prisma guideline, select only fields needed by the rescheduler rather than returning full rows.

Verify the rescheduler’s parameter type and accessed fields before adding select:

#!/bin/bash
# Confirm expected type is DestinationCalendar[] and discover used fields
rg -nP -C3 '(export\s+)?(async\s+)?(function|const)\s+handleRescheduleEventManager\b'
rg -nP -C3 'previousHostDestinationCalendar\b' packages | head -n 200

Also applies to: 331-332

📜 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 5375c65 and 5b0b4bb.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (2)
  • packages/features/ee/round-robin/roundRobinManualReassignment.ts (3 hunks)
  • packages/features/ee/round-robin/roundRobinReassignment.ts (4 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/ee/round-robin/roundRobinManualReassignment.ts
  • packages/features/ee/round-robin/roundRobinReassignment.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/ee/round-robin/roundRobinManualReassignment.ts
  • packages/features/ee/round-robin/roundRobinReassignment.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/ee/round-robin/roundRobinManualReassignment.ts
  • packages/features/ee/round-robin/roundRobinReassignment.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: anglerfishlyy
PR: calcom/cal.com#0
File: :0-0
Timestamp: 2025-08-27T16:39:38.192Z
Learning: anglerfishlyy successfully implemented CAL-3076 email invitation feature for Cal.com team event-types in PR #23312. The feature allows inviting people via email directly from assignment flow, with automatic team invitation if email doesn't belong to existing team member. Implementation includes Host type modifications (userId?: number, email?: string, isPending?: boolean), CheckedTeamSelect component updates with CreatableSelect, TRPC schema validation with zod email validation, and integration with existing teamInvite system.
Learnt from: ShashwatPS
PR: calcom/cal.com#23638
File: packages/trpc/server/routers/viewer/calendars/setDestinationReminder.handler.test.ts:198-199
Timestamp: 2025-09-06T11:00:34.348Z
Learning: In calcom/cal.com PR #23638, the maintainer ShashwatPS determined that authorization checks in the setDestinationReminder handler are "not applicable" when CodeRabbit suggested adding user-scoped WHERE clauses to prevent users from modifying other users' destination calendar reminder settings.
Learnt from: CarinaWolli
PR: calcom/cal.com#22296
File: packages/lib/bookings/filterHostsBySameRoundRobinHost.ts:41-42
Timestamp: 2025-07-22T11:42:47.623Z
Learning: The filterHostsBySameRoundRobinHost function in packages/lib/bookings/filterHostsBySameRoundRobinHost.ts has a known limitation where it doesn't work correctly with fixed hosts or round robin groups. This is pre-existing technical debt that was already broken before the round robin groups feature. CarinaWolli has documented this in Linear issue CAL-6134 for future fix.
📚 Learning: 2025-07-22T11:42:47.623Z
Learnt from: CarinaWolli
PR: calcom/cal.com#22296
File: packages/lib/bookings/filterHostsBySameRoundRobinHost.ts:41-42
Timestamp: 2025-07-22T11:42:47.623Z
Learning: The filterHostsBySameRoundRobinHost function in packages/lib/bookings/filterHostsBySameRoundRobinHost.ts has a known limitation where it doesn't work correctly with fixed hosts or round robin groups. This is pre-existing technical debt that was already broken before the round robin groups feature. CarinaWolli has documented this in Linear issue CAL-6134 for future fix.

Applied to files:

  • packages/features/ee/round-robin/roundRobinManualReassignment.ts
  • packages/features/ee/round-robin/roundRobinReassignment.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). (2)
  • GitHub Check: Install dependencies / Yarn install & cache
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (3)
packages/features/ee/round-robin/roundRobinReassignment.ts (2)

268-280: Good guard to prevent null attendee update

Wrapping the attendee update in an existence check avoids a runtime error when the previous RR host isn’t an attendee. Looks correct.


375-375: Intentional omission of cancellationReason is fine

Renaming via destructuring to drop cancellationReason from outbound emails is clear and lint-friendly. LGTM.

packages/features/ee/round-robin/roundRobinManualReassignment.ts (1)

342-342: Clean omission of cancellationReason

The destructuring rename to _cancellationReason cleanly excludes it from outbound emails. Looks good.

@pull-request-size pull-request-size bot added size/XS and removed size/M labels Sep 9, 2025
@anikdhabal anikdhabal changed the title chore: update reassigment to delete old events fix: duplicate event created in attendee calendar due to incorrect icalUid Sep 9, 2025
Copy link
Contributor

@anikdhabal anikdhabal left a comment

Choose a reason for hiding this comment

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

LGTM

@anikdhabal anikdhabal enabled auto-merge (squash) September 9, 2025 10:06
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 (3)
packages/features/ee/round-robin/handleRescheduleEventManager.ts (3)

163-166: Prefer nullish coalescing and include createdEvent; normalize null/undefined for iCalUID

Use ?? instead of || to avoid falling back on empty-string UIDs, also consider createdEvent as a fallback, and avoid assigning null to evt.iCalUID. This keeps types consistent and improves resilience when providers return sparse payloads.

-    evt.iCalUID = Array.isArray(calendarResult?.updatedEvent)
-      ? calendarResult?.updatedEvent[0]?.iCalUID || bookingICalUID
-      : calendarResult?.updatedEvent?.iCalUID || bookingICalUID || undefined;
+    const updatedEvt = calendarResult?.updatedEvent;
+    const createdEvt = calendarResult?.createdEvent;
+    const resolvedICalUID =
+      Array.isArray(updatedEvt) ? updatedEvt[0]?.iCalUID : (updatedEvt?.iCalUID ?? createdEvt?.iCalUID);
+    evt.iCalUID = resolvedICalUID ?? bookingICalUID ?? undefined;

151-160: Derive createdOrUpdatedEvent from the calendar result, not results[0]

results[0] may be a non-calendar app result (e.g., video). Using the calendar result prevents accidental undefined reads and aligns metadata with the actual calendar event.

-    const createdOrUpdatedEvent = Array.isArray(results[0]?.updatedEvent)
-      ? results[0]?.updatedEvent[0]
-      : results[0]?.updatedEvent ?? results[0]?.createdEvent;
+    const calRes = results.find((r) => r.type.includes("_calendar"));
+    const createdOrUpdatedEvent = Array.isArray(calRes?.updatedEvent)
+      ? calRes?.updatedEvent[0]
+      : calRes?.updatedEvent ?? calRes?.createdEvent;

186-195: Avoid passing undefined to Prisma update; include iCalUID conditionally

Prisma generally ignores omitted fields but an explicit undefined can be noisy or rejected by typings. Include iCalUID only when it’s resolved.

-    await prisma.booking.update({
+    const iCalUIDToPersist = evt.iCalUID ?? bookingICalUID;
+    await prisma.booking.update({
       where: {
         id: bookingId,
       },
       data: {
         location: bookingLocation,
-        iCalUID: evt.iCalUID !== bookingICalUID ? evt.iCalUID : bookingICalUID,
+        ...(iCalUIDToPersist !== undefined ? { iCalUID: iCalUIDToPersist } : {}),
         metadata: { ...(typeof bookingMetadata === "object" && bookingMetadata), ...newBookingMetaData },
       },
     });

Would you confirm the Booking.iCalUID column is nullable and Prisma’s generated type marks it optional/null? If not, I can adjust the snippet accordingly.

📜 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 5b0b4bb and b18fe67.

📒 Files selected for processing (3)
  • packages/features/ee/round-robin/handleRescheduleEventManager.ts (1 hunks)
  • packages/features/ee/round-robin/roundRobinManualReassignment.ts (1 hunks)
  • packages/features/ee/round-robin/roundRobinReassignment.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/features/ee/round-robin/roundRobinManualReassignment.ts
  • packages/features/ee/round-robin/roundRobinReassignment.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/ee/round-robin/handleRescheduleEventManager.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/ee/round-robin/handleRescheduleEventManager.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/ee/round-robin/handleRescheduleEventManager.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: anglerfishlyy
PR: calcom/cal.com#0
File: :0-0
Timestamp: 2025-08-27T16:39:38.192Z
Learning: anglerfishlyy successfully implemented CAL-3076 email invitation feature for Cal.com team event-types in PR #23312. The feature allows inviting people via email directly from assignment flow, with automatic team invitation if email doesn't belong to existing team member. Implementation includes Host type modifications (userId?: number, email?: string, isPending?: boolean), CheckedTeamSelect component updates with CreatableSelect, TRPC schema validation with zod email validation, and integration with existing teamInvite system.
⏰ 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). (8)
  • GitHub Check: Production builds / Build Web App
  • GitHub Check: Production builds / Build Docs
  • GitHub Check: Production builds / Build API v2
  • GitHub Check: Production builds / Build Atoms
  • GitHub Check: Production builds / Build API v1
  • GitHub Check: Tests / Unit
  • GitHub Check: Type check / check-types
  • GitHub Check: Linters / lint

@anikdhabal anikdhabal merged commit 411516d into calcom:main Sep 9, 2025
53 of 59 checks passed
@github-actions
Copy link
Contributor

github-actions bot commented Sep 9, 2025

E2E results are ready!

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 ready-for-e2e size/XS teams area: teams, round robin, collective, managed event-types

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants