Skip to content

feat: assign custom roles#22662

Merged
sean-brydon merged 17 commits intomainfrom
fix/assigning-child-team-custom-roles
Jul 24, 2025
Merged

feat: assign custom roles#22662
sean-brydon merged 17 commits intomainfrom
fix/assigning-child-team-custom-roles

Conversation

@sean-brydon
Copy link
Member

@sean-brydon sean-brydon commented Jul 21, 2025

What does this PR do?

This PR adds the ability for people to assign sub-team roles to members in the team when pbac is enabled.

Visual Demo (For contributors especially)

Image Demo (if applicable):

CleanShot 2025-07-21 at 13 51 31 CleanShot 2025-07-21 at 13 51 39

How to test:

Enable PBAC on a org by adding pbac to the team features for that specific team in DB.
Manually refresh the app to invalidate team features cache.
Visit roles and permissions in settings sidebar fo teams. Create a role with any permissions - youll want to check the role CRUD here.
Goto the team members page - check filters work
Edit a user - move them to the new role you created
impersonate
Ensure you can edit other users
Filter by new role

logout
login to teampro or any other account with pbac disabled
Ensure filters and chaning role works as expected

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 21, 2025

Walkthrough

This set of changes introduces comprehensive support for custom team roles alongside traditional roles within the team management features. The main team members page is refactored to use a new TeamMembersView component, which leverages cached asynchronous functions to fetch roles and organization attributes. The TeamMembersView client component manages the display and invitation of team members, enforcing licensing and role-based permissions. The EditMemberSheet and MemberList components are updated to support both default and custom roles, including dynamic role fetching, conditional UI rendering, and role assignment logic. The PBAC role management system is extended with a new getTeamRoles method, and the role assignment and member listing handlers in the TRPC server are refactored to integrate this abstraction, enhancing permission checks and error handling. The schema for role changes is expanded to accept both enum and string role identifiers, and custom roles are now surfaced in the user and member management UIs.

Estimated code review effort

4 (~90 minutes)

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-playwright".

(The package "eslint-plugin-playwright" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-playwright@latest --save-dev

The plugin "eslint-plugin-playwright" was referenced from the config file in ".eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b680ba6 and b676159.

📒 Files selected for processing (1)
  • packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@keithwillcode keithwillcode added consumer core area: core, team members only labels Jul 21, 2025
@delve-auditor
Copy link

delve-auditor bot commented Jul 21, 2025

No security or compliance issues detected. Reviewed everything up to 3630a01.

Security Overview
  • 🔎 Scanned files: 9 changed file(s)
Detected Code Changes
Change Type Relevant files
Enhancement ► teams/team-members-view.tsx
    Add team members view with role management
► teams/changeMemberRole.handler.ts
    Add custom role support
► teams/EditMemberSheet.tsx
    Update role selection UI
Refactor ► insights/insights-view.tsx
    Remove bookings by hour chart
► insights/components/BookingsByHourChart.tsx
    Remove component
► lib/getTeamMemberEmailFromCrm.ts
    Simplify CRM data handling
► queries.ts
    Remove unused CRM record ID

Reply to this PR with @delve-auditor followed by a description of what change you want and we'll auto-submit a change to this PR to implement it.

@vercel
Copy link

vercel bot commented Jul 21, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
cal ⬜️ Ignored (Inspect) Jul 24, 2025 1:22pm
cal-eu ⬜️ Ignored (Inspect) Jul 24, 2025 1:22pm

@sean-brydon sean-brydon requested a review from eunjae-lee July 21, 2025 14:33
Comment on lines +70 to +80
const facetedTeamValues = {
roles,
teams: [team],
attributes: attributes.map((attribute) => ({
id: attribute.id,
name: attribute.name,
options: Array.from(new Set(attribute.options.map((option) => option.value))).map((value) => ({
value,
})),
})),
};
Copy link
Member Author

Choose a reason for hiding this comment

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

Populate the filters via server side

@sean-brydon sean-brydon marked this pull request as ready for review July 21, 2025 14:37
@graphite-app graphite-app bot requested a review from a team July 21, 2025 14:37
@dosubot dosubot bot added teams area: teams, round robin, collective, managed event-types ✨ feature New feature or request labels Jul 21, 2025
@graphite-app
Copy link

graphite-app bot commented Jul 21, 2025

Graphite Automations

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

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

"Add ready-for-e2e label" took an action on this PR • (07/24/25)

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

♻️ Duplicate comments (1)
apps/web/app/(use-page-wrapper)/settings/(settings-layout)/teams/[id]/members/page.tsx (1)

70-80: Filters are already populated server-side.

The implementation correctly populates filters server-side using cached functions (getCachedTeamRoles and getCachedTeamAttributes). The data is fetched during SSR and passed to the client component.

🧹 Nitpick comments (5)
apps/web/modules/teams/team-members-view.tsx (1)

25-25: Remove unused attributes prop.

The attributes prop is defined in the interface but never used in the component. Consider removing it to avoid confusion.

interface TeamMembersViewProps {
  team: NonNullable<RouterOutputs["viewer"]["teams"]["get"]>;
  facetedTeamValues?: {
    roles: { id: string; name: string }[];
    teams: RouterOutputs["viewer"]["teams"]["get"][];
    attributes: {
      id: string;
      name: string;
      options: {
        value: string;
      }[];
    }[];
  };
-  attributes?: any[];
}
packages/trpc/server/routers/viewer/teams/listMembers.handler.ts (1)

82-85: Consider caching the team lookup.

Since this handler might be called frequently, consider if the team lookup could be optimized by including parentId in the main member query or caching it at a higher level.

apps/web/app/(use-page-wrapper)/settings/(settings-layout)/teams/[id]/members/page.tsx (1)

21-47: Consider logging errors for debugging purposes.

While returning empty arrays on errors provides good fallback behavior, silently swallowing all errors might make debugging difficult. Consider at least logging errors to help with troubleshooting:

 } catch (error) {
+  console.error(`Failed to fetch team roles for team ${teamId}:`, error);
   // PBAC not enabled or error occurred, return empty array
   return [];
 }

Same applies to the getCachedTeamAttributes function.

packages/features/pbac/services/role-management.factory.ts (1)

49-49: Document why userId parameter is unused in PBAC implementation.

The _userId naming indicates this parameter is unused in PBAC implementation, while LegacyRoleManager still uses it. Consider adding a comment explaining this difference to help future maintainers understand the design decision.

packages/features/ee/teams/components/EditMemberSheet.tsx (1)

222-246: Clean implementation of dynamic role selection UI.

The conditional rendering between Select and ToggleGroup is well-handled. Consider adding proper TypeScript types instead of using any for the selectedOption parameter:

- onChange={(selectedOption: any) => {
+ onChange={(selectedOption: { value: string; label: string } | null) => {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bb4260c and 221d3a2.

📒 Files selected for processing (9)
  • apps/web/app/(use-page-wrapper)/settings/(settings-layout)/teams/[id]/members/page.tsx (2 hunks)
  • apps/web/modules/teams/team-members-view.tsx (1 hunks)
  • packages/features/ee/teams/components/EditMemberSheet.tsx (8 hunks)
  • packages/features/ee/teams/components/MemberList.tsx (6 hunks)
  • packages/features/pbac/services/role-management.factory.ts (4 hunks)
  • packages/features/users/components/UserTable/EditSheet/EditUserForm.tsx (3 hunks)
  • packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts (5 hunks)
  • packages/trpc/server/routers/viewer/teams/changeMemberRole.schema.ts (1 hunks)
  • packages/trpc/server/routers/viewer/teams/listMembers.handler.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

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

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • apps/web/modules/teams/team-members-view.tsx
  • packages/trpc/server/routers/viewer/teams/listMembers.handler.ts
  • packages/features/users/components/UserTable/EditSheet/EditUserForm.tsx
  • packages/trpc/server/routers/viewer/teams/changeMemberRole.schema.ts
  • apps/web/app/(use-page-wrapper)/settings/(settings-layout)/teams/[id]/members/page.tsx
  • packages/features/ee/teams/components/EditMemberSheet.tsx
  • packages/features/ee/teams/components/MemberList.tsx
  • packages/features/pbac/services/role-management.factory.ts
  • packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts
🧠 Learnings (3)
packages/trpc/server/routers/viewer/teams/listMembers.handler.ts (3)

Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-21T13:54:11.732Z
Learning: Applies to backend/**/*.{ts,tsx} : For Prisma queries: Only select data you need.

Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-21T13:54:11.732Z
Learning: Applies to backend/**/*.{ts,tsx} : For Prisma queries: Select selects only the fields you specify explicitly.

Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-21T13:54:11.732Z
Learning: Applies to backend/**/*.{ts,tsx} : For Prisma queries: Never use Includes - use select.

packages/features/ee/teams/components/EditMemberSheet.tsx (1)

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

packages/features/ee/teams/components/MemberList.tsx (1)

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

🧬 Code Graph Analysis (3)
packages/trpc/server/routers/viewer/teams/changeMemberRole.schema.ts (1)
packages/platform/libraries/index.ts (1)
  • MembershipRole (98-98)
packages/features/ee/teams/components/MemberList.tsx (1)
packages/features/data-table/lib/utils.ts (1)
  • convertFacetedValuesToMap (150-154)
packages/features/pbac/services/role-management.factory.ts (3)
packages/platform/libraries/index.ts (1)
  • MembershipRole (98-98)
packages/features/pbac/lib/constants.ts (1)
  • DEFAULT_ROLE_IDS (7-11)
packages/features/pbac/domain/errors/role-management.error.ts (1)
  • RoleManagementError (1-6)
🪛 Biome (1.9.4)
packages/features/ee/teams/components/MemberList.tsx

[error] 669-672: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🪛 GitHub Check: Tests / Unit
packages/features/pbac/services/role-management.factory.ts

[failure] 62-62: packages/features/pbac/services/tests/role-management.factory.test.ts > RoleManagementFactory > PBACRoleManager > assignRole > should assign default role correctly
RoleManagementError: You do not have access to this role
❯ PBACRoleManager.assignRole packages/features/pbac/services/role-management.factory.ts:62:15
❯ packages/features/pbac/services/tests/role-management.factory.test.ts:132:9

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { code: 'INVALID_ROLE' }

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Security Check
🔇 Additional comments (16)
packages/trpc/server/routers/viewer/teams/changeMemberRole.schema.ts (1)

8-8: LGTM! Schema properly supports custom roles.

The union type correctly allows both traditional MembershipRole enum values and string identifiers for custom roles, aligning with the PBAC feature requirements.

apps/web/modules/teams/team-members-view.tsx (1)

28-64: Well-structured component with proper permission handling.

The component correctly:

  • Enforces license requirements
  • Checks user permissions before displaying member data
  • Handles private team visibility appropriately
  • Manages modal state cleanly
packages/features/users/components/UserTable/EditSheet/EditUserForm.tsx (1)

110-124: Verify the custom role filtering logic.

The current implementation shows only custom roles when teamRoles exists. This means standard roles (MEMBER, ADMIN, OWNER) won't be available in the dropdown when custom roles are present. Is this the intended behavior?

Please confirm if hiding standard roles when custom roles exist is the expected behavior. If users should be able to select both standard and custom roles, consider this approach:

const membershipOptions = useMemo<MembershipOption[]>(() => {
  const options: MembershipOption[] = [];
  
  // Always add standard roles
  options.push(
    {
      value: MembershipRole.MEMBER,
      label: t("member"),
    },
    {
      value: MembershipRole.ADMIN,
      label: t("admin"),
    }
  );
  
  if (isOwner) {
    options.push({
      value: MembershipRole.OWNER,
      label: t("owner"),
    });
  }
  
  // Add custom roles if they exist
  if (teamRoles?.length > 0) {
    teamRoles.forEach((role) => {
      options.push({
        value: role.id,
        label: role.name,
        isCustomRole: true,
      });
    });
  }
  
  return options;
}, [t, isOwner, teamRoles]);
packages/trpc/server/routers/viewer/teams/listMembers.handler.ts (1)

81-102: Well-implemented PBAC integration with proper error handling.

The implementation correctly:

  • Fetches the organization context through team's parentId
  • Uses RoleManagementFactory to check PBAC status
  • Gracefully handles cases where PBAC is not enabled
  • Builds an efficient lookup dictionary for custom roles
packages/features/ee/teams/components/MemberList.tsx (1)

379-402: Excellent implementation of custom role display.

The role cell correctly:

  • Displays custom role names when available
  • Falls back to traditional role names
  • Uses the appropriate identifier for filtering
  • Maintains backward compatibility
packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts (5)

1-44: LGTM! Well-structured PBAC integration.

The implementation correctly:

  • Fetches team information to determine the organizational hierarchy
  • Handles the NOT_FOUND case appropriately
  • Creates a role manager instance for the correct organization
  • Properly transforms permission check errors into TRPC errors

45-56: Consider the implications of dual permission checks.

The code performs PBAC permission checks first (lines 36-44) and then traditional permission checks for enum roles. This could create scenarios where:

  • PBAC grants permission but traditional checks deny it
  • Different error messages for the same operation depending on role type

Consider either:

  1. Skipping traditional checks when PBAC is enabled
  2. Documenting this behavior clearly
  3. Ensuring both systems are aligned in their permission model

68-71: Good addition of null check for target membership.

This prevents potential runtime errors and provides clear feedback when attempting to change roles for non-existent members.


86-97: Security consideration: Admin self-elevation via custom roles.

The current logic prevents admins from elevating themselves to traditional OWNER role, but this restriction doesn't apply to custom roles. If custom roles can have owner-equivalent permissions, admins could bypass this restriction.

Consider whether custom roles should also be subject to self-elevation restrictions based on their permission levels rather than just their type.


99-121: LGTM! Clean role assignment implementation.

The code properly delegates to the role manager and handles errors appropriately. Note that the userId parameter passed to assignRole appears to be unused in the PBAC implementation (based on the parameter being renamed to _userId in PBACRoleManager).

apps/web/app/(use-page-wrapper)/settings/(settings-layout)/teams/[id]/members/page.tsx (1)

49-69: Well-structured data fetching with proper error handling.

The implementation correctly:

  • Handles async params (Next.js 15 pattern)
  • Validates team existence before proceeding
  • Efficiently fetches data in parallel
  • Properly determines the organization ID
packages/features/pbac/services/role-management.factory.ts (1)

21-22: Clean implementation of getTeamRoles method.

The method is well-designed with:

  • Consistent interface across both managers
  • Appropriate delegation in PBAC implementation
  • Sensible defaults in legacy implementation
  • Consistent return type structure

Also applies to: 79-86, 129-136

packages/features/ee/teams/components/EditMemberSheet.tsx (4)

27-28: Good schema evolution for role flexibility.

The union type properly supports both traditional enum roles and custom string role IDs, maintaining backward compatibility while enabling new functionality.


50-50: Well-implemented custom roles integration.

The implementation correctly:

  • Initializes state with custom role ID when available
  • Configures the query to avoid retries when PBAC is disabled
  • Only enables the query when teamId is present

Also applies to: 64-71


72-101: Consider the implications of exclusive role display.

The current implementation shows either custom roles OR traditional roles, but never both. This means:

  • Organizations with custom roles lose access to traditional role options in the UI
  • There's no gradual migration path from traditional to custom roles

Is this intentional? Consider whether organizations might want to use both traditional and custom roles during a transition period.


105-105: Consistent handling of role data throughout the component.

The implementation properly:

  • Initializes form values with custom role support
  • Maintains type consistency by casting to string
  • Combines loading states to ensure data is ready before rendering

Also applies to: 132-132, 178-178

Comment on lines +669 to +672
const allRoles = facetedTeamValues.roles.map((role) => ({
label: role.name,
value: role.id,
}));
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

Fix switch declaration scope issue.

Variables declared in switch cases without block scope can be accessed by other cases, which can lead to bugs.

case "role":
+  {
    // Include both traditional roles and PBAC custom roles
    const allRoles = facetedTeamValues.roles.map((role) => ({
      label: role.name,
      value: role.id,
    }));

    return convertFacetedValuesToMap(allRoles);
+  }
🧰 Tools
🪛 Biome (1.9.4)

[error] 669-672: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🤖 Prompt for AI Agents
In packages/features/ee/teams/components/MemberList.tsx around lines 669 to 672,
the variables declared inside the switch cases lack block scope, which can cause
them to be accessed by other cases unintentionally. To fix this, wrap the code
inside each switch case in curly braces {} to create a block scope, ensuring
variables are scoped only within their respective cases.

@sean-brydon sean-brydon force-pushed the fix/assigning-child-team-custom-roles branch from 042bf61 to 221d3a2 Compare July 21, 2025 15:09
Copy link
Contributor

@eunjae-lee eunjae-lee left a comment

Choose a reason for hiding this comment

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

I tested it and it's working well!

I see some type errors and NITs from CodeRabbit.
I'll revisit this !

- Add missing onSettingsOpen prop to MemberInvitationModalWithoutMembers
- Update updateRoleInCache function to handle both MembershipRole enum and custom role strings
- Fix cache update logic to properly handle mixed role types without breaking type safety
- Ensure proper type handling for both traditional and custom roles in EditMemberSheet

Co-Authored-By: sean@cal.com <Sean@brydon.io>
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: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3630a01 and f4b7eb2.

📒 Files selected for processing (3)
  • apps/web/modules/teams/team-members-view.tsx (1 hunks)
  • packages/features/ee/teams/components/EditMemberSheet.tsx (8 hunks)
  • packages/features/ee/teams/components/MemberChangeRoleModal.tsx (2 hunks)
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

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

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • packages/features/ee/teams/components/MemberChangeRoleModal.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/web/modules/teams/team-members-view.tsx
  • packages/features/ee/teams/components/EditMemberSheet.tsx
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

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

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • packages/features/ee/teams/components/MemberChangeRoleModal.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (1)
packages/features/ee/teams/components/MemberChangeRoleModal.tsx (1)

27-27: LGTM: Type expansion supports custom roles.

The expansion of the role parameter type from MembershipRole to MembershipRole | string correctly enables support for both traditional enum roles and custom role IDs (strings), aligning with the PBAC feature requirements.

- Fix assignRole method to properly check if role is a default MembershipRole enum key
- Use DEFAULT_ROLE_IDS mapping to get the correct role ID for default roles
- Resolves unit test failure in role-management.factory.test.ts

Co-Authored-By: sean@cal.com <Sean@brydon.io>
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

🔭 Outside diff range comments (1)
packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts (1)

84-95: Prevent ADMIN users from self-elevating to custom PBAC roles

The current guard in changeMemberRole.handler.ts only blocks self-elevation when input.role is one of the default MembershipRole enum values. Custom role IDs (strings) bypass this check, allowing an ADMIN to assign themselves arbitrarily powerful PBAC roles.

Please add a complementary check for custom roles—e.g. before calling roleManager.assignRole(...), insert:

   if (
     myMembership?.role === MembershipRole.ADMIN &&
     input.memberId === ctx.user.id &&
     typeof input.role === "string" &&
-    Object.values(MembershipRole).includes(input.role as MembershipRole) &&
-    input.role !== MembershipRole.MEMBER
+    (
+      // default enums except MEMBER
+      (Object.values(MembershipRole).includes(input.role as MembershipRole) && input.role !== MembershipRole.MEMBER)
+      // OR any custom role string
+      || !Object.values(MembershipRole).includes(input.role as MembershipRole)
+    )
   ) {
     throw new TRPCError({
       code: "FORBIDDEN",
       message: "You can not change yourself to a higher role.",
     });
   }

This ensures ADMINs cannot elevate themselves to neither higher default roles nor custom PBAC roles.

♻️ Duplicate comments (1)
packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts (1)

1-3: LGTM: Repository pattern implementation addresses previous feedback.

The introduction of TeamRepository and RoleManagementFactory improves the architecture by implementing the repository pattern as suggested in the previous review comment.

🧹 Nitpick comments (2)
packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts (2)

34-41: Enhance error handling specificity.

The generic error handling could be improved to provide more specific error messages based on the type of permission failure.

Consider enhancing the error handling:

  try {
    await roleManager.checkPermissionToChangeRole(ctx.user.id, organizationId);
  } catch (error) {
+   const errorMessage = error instanceof Error ? error.message : "Unauthorized";
+   // Log the specific error for debugging while keeping user message generic
+   console.error('Permission check failed:', error);
    throw new TRPCError({
      code: "UNAUTHORIZED",
-     message: error instanceof Error ? error.message : "Unauthorized",
+     message: errorMessage,
    });
  }

97-106: Improve error context for role assignment failures.

The generic "Failed to assign role" message could be more helpful for debugging and user understanding.

Consider providing more context in the error message:

  try {
    await roleManager.assignRole(input.memberId, input.teamId, input.role, targetMembership.id);
  } catch (error) {
+   const errorMessage = error instanceof Error ? error.message : "Failed to assign role";
+   // Log the full error for debugging
+   console.error('Role assignment failed:', { 
+     memberId: input.memberId, 
+     teamId: input.teamId, 
+     role: input.role, 
+     error 
+   });
    throw new TRPCError({
      code: "BAD_REQUEST",
-     message: error instanceof Error ? error.message : "Failed to assign role",
+     message: errorMessage,
    });
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5ce0e89 and b680ba6.

📒 Files selected for processing (5)
  • packages/features/ee/teams/components/EditMemberSheet.tsx (8 hunks)
  • packages/features/ee/teams/components/MemberChangeRoleModal.tsx (2 hunks)
  • packages/features/pbac/services/role-management.factory.ts (4 hunks)
  • packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts (5 hunks)
  • packages/trpc/server/routers/viewer/teams/listMembers.handler.ts (3 hunks)
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

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

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/features/ee/teams/components/MemberChangeRoleModal.tsx
  • packages/trpc/server/routers/viewer/teams/listMembers.handler.ts
  • packages/features/ee/teams/components/EditMemberSheet.tsx
  • packages/features/pbac/services/role-management.factory.ts
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

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

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (3)
packages/trpc/server/routers/viewer/teams/changeMemberRole.handler.ts (3)

66-68: LGTM: Improved error handling for missing membership.

The explicit check for target membership with a specific error message improves the user experience compared to potential null reference errors later.


108-118: I couldn’t find any separate “Role” model or relation in your Prisma schema—your Membership model already defines a scalar role field (and Prisma returns all scalar fields by default). Including the role column explicitly isn’t necessary, and there’s no extra table to join. You can safely ignore this suggestion.

Likely an incorrect or invalid review comment.


20-31: Team repository error handling and organization ID logic are correctly implemented

TeamRepository.findById returns null when no matching team exists, which the handler immediately converts to a NOT_FOUND error. The expression team.parentId || input.teamId accurately yields the organization’s ID for nested teams and the team’s own ID for organization or standalone teams. Since we only call createRoleManager with a validated ID, no further checks are necessary.

…-team-custom-roles' into fix/assigning-child-team-custom-roles
@sean-brydon sean-brydon enabled auto-merge (squash) July 24, 2025 13:21
@joeauyeung joeauyeung dismissed their stale review July 24, 2025 15:00

Eunjae approved this PR after changes

@sean-brydon sean-brydon merged commit 29e1dcb into main Jul 24, 2025
60 of 61 checks passed
@sean-brydon sean-brydon deleted the fix/assigning-child-team-custom-roles branch July 24, 2025 15:42
zomars pushed a commit that referenced this pull request Jul 25, 2025
Co-authored-by: sean@cal.com <Sean@brydon.io>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

consumer core area: core, team members only ✨ feature New feature or request ready-for-e2e teams area: teams, round robin, collective, managed event-types

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants