Skip to content

Comments

fix: remove team members from filter segments when removed from team#24168

Closed
naaa760 wants to merge 3 commits intocalcom:mainfrom
naaa760:fix/team-filter-removal
Closed

fix: remove team members from filter segments when removed from team#24168
naaa760 wants to merge 3 commits intocalcom:mainfrom
naaa760:fix/team-filter-removal

Conversation

@naaa760
Copy link
Contributor

@naaa760 naaa760 commented Sep 30, 2025

closes: #24165

  • fixes permission errors when accessing bookings after team members are removed - cleans up filter segments that still reference removed users.

What does this PR do?

  • Removes user IDs from filter segments when team members are removed
  • Prevents "no permissions to fetch bookings" errors for removed team members
  • Updates team-scoped filter segments to exclude removed users

@vercel
Copy link

vercel bot commented Sep 30, 2025

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

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 30, 2025

Walkthrough

Adds a private static method cleanupFilterSegmentsWithRemovedUser(userId, teamId) in packages/lib/server/service/teamService.ts that scans TEAM-scoped filterSegments for a team and removes references to the removed user from activeFilters. Handles two formats: ms (filters out the userId from an array) and ss (removes the single-user filter when it matches). Persists modified segments via prisma.filterSegment.update and logs errors without aborting. The cleanup is invoked after member removals in the regular removal flow, after workflow reminders cleanup, and during team removal post-transaction.

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly describes the primary change of removing team members from filter segments upon team removal, directly reflecting the main functionality introduced in the changeset without extraneous detail.
Linked Issues Check ✅ Passed The changes implement a cleanup method that removes references to removed team members from filter segments and invoke it in all member removal flows, fully addressing the objective defined in linked issue #24165 to avoid fetching bookings for users without permissions.
Out of Scope Changes Check ✅ Passed All modifications are focused on adding and invoking the cleanupFilterSegmentsWithRemovedUser method within teamService.ts, and there are no unrelated or extraneous changes outside the scope of the linked issue objectives.
Description Check ✅ Passed The description directly relates to the changeset by explaining the removal of user IDs from filter segments to prevent permission errors and references the linked issue being closed, matching the code modifications.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e33c1fb and 13cb5c2.

📒 Files selected for processing (1)
  • packages/lib/server/service/teamService.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/lib/server/service/teamService.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

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
🧪 Early access (Sonnet 4.5): enabled

We are currently testing the Sonnet 4.5 model, which is expected to improve code review quality. However, this model may lead to increased noise levels in the review comments. Please disable the early access features if the noise level causes any inconvenience.

Note:

  • Public repositories are always opted into early access features.
  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.

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

@graphite-app graphite-app bot added the community Created by Linear-GitHub Sync label Sep 30, 2025
@graphite-app graphite-app bot requested a review from a team September 30, 2025 10:19
@dosubot dosubot bot added bookings area: bookings, availability, timezones, double booking teams area: teams, round robin, collective, managed event-types 🐛 bug Something isn't working labels Sep 30, 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: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 2ef627b and e33c1fb.

📒 Files selected for processing (1)
  • packages/lib/server/service/teamService.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*Service.ts

📄 CodeRabbit inference engine (.cursor/rules/review.mdc)

Service files must include Service suffix, use PascalCase matching exported class, and avoid generic names (e.g., MembershipService.ts)

Files:

  • packages/lib/server/service/teamService.ts
**/*.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/server/service/teamService.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/server/service/teamService.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/server/service/teamService.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: SinghaAnirban005
PR: calcom/cal.com#23343
File: packages/features/insights/server/trpc-router.ts:1080-1101
Timestamp: 2025-08-26T08:08:23.395Z
Learning: In packages/features/insights/server/trpc-router.ts, when filtering personal event types (userId provided, no teamId, not isAll), the query correctly uses user.id (authenticated user) instead of the input userId parameter for security reasons. This prevents users from accessing other users' personal event types by passing arbitrary user IDs.
🧬 Code graph analysis (1)
packages/lib/server/service/teamService.ts (1)
packages/platform/libraries/index.ts (1)
  • TeamService (139-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). (2)
  • GitHub Check: Install dependencies / Yarn install & cache
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (3)
packages/lib/server/service/teamService.ts (3)

13-13: LGTM!

The type import is properly structured and necessary for the new cleanup method.


244-244: LGTM!

The cleanup is correctly positioned after workflow reminders cleanup and follows the established pattern of post-transaction cleanup operations.


438-497: Verify empty-array pruning and post-transaction cleanup

  • The cleanup logic leaves an empty ms filter when removing the last userId; there’s no backend pruning, only UI silencing. Confirm if empty arrays are acceptable or should be dropped like ss filters.
  • Cleanup runs after the removal transaction (e.g., lines 244, 435). If it fails, filters stay stale. Verify this post-transaction design aligns with requirements.

Comment on lines 434 to 436

await TeamService.cleanupFilterSegmentsWithRemovedUser(membership.userId, teamId);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Remove duplicate cleanup call.

The cleanupFilterSegmentsWithRemovedUser method is called twice for regular team member removals:

  1. Line 435: Inside removeFromTeam
  2. Line 244: In removeMember after calling removeFromTeam (line 239)

This results in redundant database queries and processing. Since removeMember already calls the cleanup method (line 244) after both removeFromOrganization and removeFromTeam, the call at line 435 should be removed.

Apply this diff to remove the duplicate:

-    ]);
-
-    await TeamService.cleanupFilterSegmentsWithRemovedUser(membership.userId, teamId);
+    ]);
   }
📝 Committable suggestion

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

Suggested change
await TeamService.cleanupFilterSegmentsWithRemovedUser(membership.userId, teamId);
}
await prisma.teamMembership.deleteMany({
where: { userId: membership.userId, teamId },
});
}
🤖 Prompt for AI Agents
In packages/lib/server/service/teamService.ts around lines 434 to 436, the call
to TeamService.cleanupFilterSegmentsWithRemovedUser(membership.userId, teamId)
is duplicated (also invoked by removeMember at line 244 after removeFromTeam);
remove the call at line 435 so cleanup is only performed once by removeMember to
avoid redundant work.

@github-actions github-actions bot added consumer High priority Created by Linear-GitHub Sync labels Sep 30, 2025
@github-actions
Copy link
Contributor

This PR is being marked as stale due to inactivity.

@github-actions github-actions bot added the Stale label Oct 15, 2025
@naaa760
Copy link
Contributor Author

naaa760 commented Oct 25, 2025

@kart1ka
Is anyone reviewing this PR?

@github-actions github-actions bot removed the Stale label Oct 26, 2025
@pallava-joshi
Copy link
Contributor

pallava-joshi commented Nov 25, 2025

@cubic-dev-ai leave a review here.

@cubic-dev-ai
Copy link
Contributor

cubic-dev-ai bot commented Nov 25, 2025

@cubic-dev-ai leave a review here.

@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 and implement the suggestions.

@pallava-joshi
Copy link
Contributor

marking this draft until then.

@pallava-joshi pallava-joshi marked this pull request as draft November 25, 2025 13:23
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.

1 issue found across 1 file

Prompt for AI agents (all 1 issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="packages/lib/server/service/teamService.ts">

<violation number="1" location="packages/lib/server/service/teamService.ts:381">
Cleanup only runs for the organization teamId, so child-team filter segments still reference the removed user even though their memberships were deleted. Iterate each child team (or extend cleanup to handle multiple ids) so sub-team segments are cleaned as well.</violation>
</file>

Reply to cubic to teach it or ask questions. Re-run a review with @cubic-dev-ai review this PR


await deleteWorkfowRemindersOfRemovedMember(team, userId, isOrg);

await TeamService.cleanupFilterSegmentsWithRemovedUser(userId, team.id);
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 25, 2025

Choose a reason for hiding this comment

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

Cleanup only runs for the organization teamId, so child-team filter segments still reference the removed user even though their memberships were deleted. Iterate each child team (or extend cleanup to handle multiple ids) so sub-team segments are cleaned as well.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/lib/server/service/teamService.ts, line 381:

<comment>Cleanup only runs for the organization teamId, so child-team filter segments still reference the removed user even though their memberships were deleted. Iterate each child team (or extend cleanup to handle multiple ids) so sub-team segments are cleaned as well.</comment>

<file context>
@@ -377,6 +378,8 @@ export class TeamService {
 
     await deleteWorkfowRemindersOfRemovedMember(team, userId, isOrg);
 
+    await TeamService.cleanupFilterSegmentsWithRemovedUser(userId, team.id);
+
     return { membership };
</file context>
Fix with Cubic

@naaa760 naaa760 force-pushed the fix/team-filter-removal branch from 13cb5c2 to 2eaddaa Compare November 26, 2025 13:40
@pull-request-size pull-request-size bot added size/L and removed size/M labels Nov 26, 2025
@naaa760 naaa760 marked this pull request as ready for review November 26, 2025 13:48
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.

1 issue found across 1 file

Prompt for AI agents (all 1 issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="packages/lib/server/service/teamService.ts">

<violation number="1" location="packages/lib/server/service/teamService.ts:441">
Removing a regular team member now triggers `cleanupFilterSegmentsWithRemovedUser` twice (once in `removeFromTeam`, once in `removeMember`), doubling the database work for each removal with no functional gain.</violation>
</file>

Reply to cubic to teach it or ask questions. Re-run a review with @cubic-dev-ai review this PR

}),
]);

await TeamService.cleanupFilterSegmentsWithRemovedUser(membership.userId, teamId);
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 26, 2025

Choose a reason for hiding this comment

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

Removing a regular team member now triggers cleanupFilterSegmentsWithRemovedUser twice (once in removeFromTeam, once in removeMember), doubling the database work for each removal with no functional gain.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/lib/server/service/teamService.ts, line 441:

<comment>Removing a regular team member now triggers `cleanupFilterSegmentsWithRemovedUser` twice (once in `removeFromTeam`, once in `removeMember`), doubling the database work for each removal with no functional gain.</comment>

<file context>
@@ -428,5 +437,103 @@ export class TeamService {
       }),
     ]);
+
+    await TeamService.cleanupFilterSegmentsWithRemovedUser(membership.userId, teamId);
+  }
+
</file context>

✅ Addressed in b5a83d3

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.

still got merge conflicts, cubic suggestions and failing type checks. lmk if you need any help with anything.

@pallava-joshi pallava-joshi marked this pull request as draft November 26, 2025 15:31
@naaa760 naaa760 marked this pull request as ready for review November 26, 2025 16:42
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.

1 issue found across 1 file

Prompt for AI agents (all 1 issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="packages/lib/server/service/teamService.ts">

<violation number="1" location="packages/lib/server/service/teamService.ts:534">
The catch block references an undefined `teamId`, so any exception in filter cleanup throws again during logging and prevents member removal from completing.</violation>
</file>

Reply to cubic to teach it or ask questions. Re-run a review with @cubic-dev-ai review this PR

}
}
} catch (error) {
log.error(`Failed to cleanup filter segments for removed user ${userId} from team ${teamId}`, error);
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 26, 2025

Choose a reason for hiding this comment

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

The catch block references an undefined teamId, so any exception in filter cleanup throws again during logging and prevents member removal from completing.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/lib/server/service/teamService.ts, line 534:

<comment>The catch block references an undefined `teamId`, so any exception in filter cleanup throws again during logging and prevents member removal from completing.</comment>

<file context>
@@ -429,4 +438,100 @@ export class TeamService {
+        }
+      }
+    } catch (error) {
+      log.error(`Failed to cleanup filter segments for removed user ${userId} from team ${teamId}`, error);
+    }
+  }
</file context>
Suggested change
log.error(`Failed to cleanup filter segments for removed user ${userId} from team ${teamId}`, error);
log.error(`Failed to cleanup filter segments for removed user ${userId} from teams ${uniqueTeamIds.join(",")}`, error);
Fix with Cubic

@pallava-joshi pallava-joshi marked this pull request as draft December 30, 2025 15:15
@pallava-joshi
Copy link
Contributor

closing this PR due to staleness, feel free to reopen if you wish to work on this further. thanks a ton for your contribution :)

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 consumer High priority Created by Linear-GitHub Sync size/L teams area: teams, round robin, collective, managed event-types

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remove team members from filter segment when removed from team

2 participants