Skip to content

Conversation

sean-brydon
Copy link
Member

What does this PR do?

Adds a DB seed for PBAC for a org with a few custom roles and the feature flag enabeld

Users with Roles

User Email Password Custom Role
Organization Owner owner@pbac-demo.com pbac-owner-2024! owner_role (default role)
Event Manager events@pbac-demo.com events-2024! Event Manager
Analytics Specialist analytics@pbac-demo.com analytics-2024! Analytics Specialist
Team Coordinator coordinator@pbac-demo.com coordinator-2024! Team Coordinator
Support Agent support@pbac-demo.com support-2024! Support Agent

@sean-brydon sean-brydon requested a review from a team July 23, 2025 14:47
Copy link
Contributor

github-actions bot commented Jul 23, 2025

Hey there and thank you for opening this pull request! 👋🏼

We require pull request titles to follow the Conventional Commits specification and it looks like your proposed title needs to be adjusted.

Details:

No release type found in pull request title "feat:(PBAC) Add db seed ". Add a prefix to indicate what kind of release this pull request corresponds to. For reference, see https://www.conventionalcommits.org/

Available types:
 - feat: A new feature
 - fix: A bug fix
 - docs: Documentation only changes
 - style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
 - refactor: A code change that neither fixes a bug nor adds a feature
 - perf: A code change that improves performance
 - test: Adding missing tests or correcting existing tests
 - build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
 - ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
 - chore: Other changes that don't modify src or test files
 - revert: Reverts a previous commit

@keithwillcode keithwillcode added consumer core area: core, team members only labels Jul 23, 2025
Copy link
Contributor

coderabbitai bot commented Jul 23, 2025

Walkthrough

This update introduces three new TypeScript scripts within the Prisma package: cleanup-pbac.ts, seed-pbac-only.ts, and seed-pbac-organization.ts. The cleanup-pbac.ts script removes the PBAC demo organization and all related data from the database, handling cascading deletions and logging progress. The seed-pbac-organization.ts script provides an exported function to create a PBAC-enabled organization, custom roles, users, teams, and associated event types, ensuring idempotency and detailed logging. The seed-pbac-only.ts script serves as a standalone entry point for seeding only the PBAC organization, invoking the main function and outputting organization details. Additionally, seed.ts is updated to replace direct creation of temporary organization redirects with an upsert operation to prevent duplicates and keep redirect URLs current. The package.json is updated to add a new script command for seeding the PBAC organization.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~45 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/prisma/seed-pbac-organization.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.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/pbac-seed

🪧 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 generate unit tests to generate unit tests for 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.

@graphite-app graphite-app bot requested a review from a team July 23, 2025 14:47
Copy link

vercel bot commented Jul 23, 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 9:45pm
cal-eu ⬜️ Ignored (Inspect) Jul 24, 2025 9:45pm

@dosubot dosubot bot added the ✨ feature New feature or request label Jul 23, 2025
@sean-brydon sean-brydon marked this pull request as draft July 23, 2025 14:49
joeauyeung
joeauyeung previously approved these changes Jul 23, 2025
Copy link

graphite-app bot commented Jul 23, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (07/23/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.

@sean-brydon sean-brydon marked this pull request as ready for review July 23, 2025 14:53
@dosubot dosubot bot added the ❗️ migrations contains migration files label Jul 23, 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: 4

🧹 Nitpick comments (2)
packages/prisma/cleanup-pbac.ts (1)

82-89: Make redirect cleanup more specific

The current query for cleaning up redirects might catch unintended records. The from field check only looks for specific usernames without considering the organization context.

     await prisma.tempOrgRedirect.deleteMany({
       where: {
         OR: [
-          { from: { in: ["owner", "events", "analytics", "coordinator", "support"] } },
+          { 
+            from: { in: ["owner", "events", "analytics", "coordinator", "support"] },
+            fromOrgId: 0, // Ensure these are the redirects created by the seed
+          },
           { toUrl: { contains: "pbac-demo-org" } },
         ],
       },
     });
packages/prisma/seed-pbac-only.ts (1)

22-26: Display actual demo passwords for better usability

The current output shows "password" as a placeholder, but users need the actual passwords to log in. Since these are demo credentials as mentioned in the PR objectives, consider showing the actual passwords.

     console.log("\n🔐 Login Credentials:");
     result.users.forEach(({ user, role, customRole }) => {
       const roleText = customRole ? `${role} + ${customRole}` : role;
-      console.log(`  - ${user.name}: ${user.email} / password (${roleText})`);
+      // Map emails to their demo passwords
+      const passwordMap: Record<string, string> = {
+        "owner@pbac-demo.com": "pbac-owner-2024!",
+        "events@pbac-demo.com": "events-2024!",
+        "analytics@pbac-demo.com": "analytics-2024!",
+        "coordinator@pbac-demo.com": "coordinator-2024!",
+        "support@pbac-demo.com": "support-2024!",
+      };
+      const password = passwordMap[user.email] || "unknown";
+      console.log(`  - ${user.name}: ${user.email} / ${password} (${roleText})`);
     });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 098b520 and 7117e3c.

📒 Files selected for processing (4)
  • packages/prisma/cleanup-pbac.ts (1 hunks)
  • packages/prisma/seed-pbac-only.ts (1 hunks)
  • packages/prisma/seed-pbac-organization.ts (1 hunks)
  • packages/prisma/seed.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/prisma/cleanup-pbac.ts
  • packages/prisma/seed-pbac-organization.ts
  • packages/prisma/seed-pbac-only.ts
  • packages/prisma/seed.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-21T13:54:11.770Z
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.770Z
Learning: Applies to backend/**/*.{ts,tsx} : For Prisma queries: Only select data you need.
🧰 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/prisma/cleanup-pbac.ts
  • packages/prisma/seed-pbac-organization.ts
  • packages/prisma/seed-pbac-only.ts
  • packages/prisma/seed.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-21T13:54:11.770Z
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.770Z
Learning: Applies to backend/**/*.{ts,tsx} : For Prisma queries: Only select data you need.
🔇 Additional comments (2)
packages/prisma/seed-pbac-organization.ts (1)

294-296: Security consideration: Hardcoded passwords in source code

The passwords are hardcoded directly in the source code. While this is acceptable for demo/seed data as mentioned in the PR objectives, ensure these credentials are well-documented and users are aware they should change them in any non-demo environment.

Consider adding a comment to highlight these are demo credentials:

+  // Demo credentials - CHANGE THESE IN PRODUCTION
   const owner = await createUser({
     email: "owner@pbac-demo.com",
     username: "pbac-owner",
     name: "Organization Owner",
     password: "pbac-owner-2024!",
   });

Also applies to: 318-319, 341-342, 364-365, 387-388

packages/prisma/seed.ts (1)

346-364: Good improvement: Using upsert to handle duplicate redirects

The change from create to upsert prevents duplicate key errors when re-running the seed script. This makes the seeding process more robust and idempotent.

Copy link
Contributor

@keithwillcode keithwillcode left a comment

Choose a reason for hiding this comment

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

Not planning to put these behind yarn commands like we have for the others?
e.g. "seed-app-store": "ts-node --transpile-only ./seed-app-store.ts"

@keithwillcode keithwillcode removed the ❗️ migrations contains migration files label Jul 23, 2025
Copy link

socket-security bot commented Jul 24, 2025

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedbcryptjs@​2.4.31001001008080
Added@​formkit/​auto-animate@​1.0.0-beta.51001008481100
Addedical.js@​1.5.01001001008370

View full report

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/prisma/package.json (1)

21-22: Add an execution-guard or naming convention to prevent accidental prod execution

The new seed-pbac script parallels other ad-hoc seeders, but unlike the default Prisma seed hook it can be invoked in any environment. Consider adding a guard (e.g., check process.env.NODE_ENV !== 'production') inside seed-pbac-organization.ts or prefixing the script with NODE_ENV=development to avoid seeding PBAC demo data in production by mistake.

-    "seed-pbac": "ts-node --transpile-only ./seed-pbac-organization.ts"
+    "seed-pbac": "NODE_ENV=development ts-node --transpile-only ./seed-pbac-organization.ts"

Alternatively, rename to seed-pbac:dev to signal its intent.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0317008 and ac8c867.

📒 Files selected for processing (2)
  • packages/prisma/package.json (1 hunks)
  • packages/prisma/seed.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/prisma/seed.ts
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-21T13:54:11.770Z
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.770Z
Learning: Applies to backend/**/*.{ts,tsx} : For Prisma queries: Only select data you need.
⏰ 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

@sean-brydon sean-brydon changed the title feat:(PBAC) Add db seed feat: (PBAC) Add db seed Jul 24, 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

♻️ Duplicate comments (3)
packages/prisma/seed-pbac-organization.ts (3)

24-32: Return existing data when organization already exists

When the organization exists, returning empty customRoles and users arrays is misleading. The existing organization likely has roles and users that should be fetched and returned for consistency.


316-323: Existing users returned with incorrect default roles

When existing users are found, they're returned with hardcoded MembershipRole.MEMBER and customRole: null, which may not reflect their actual roles. Consider fetching the actual membership data to return accurate role information.


468-478: Hardcoded role assignment logic needs refactoring

The role assignment uses hardcoded email checks and assigns "owner_role" which wasn't created in createCustomRoles. This logic is fragile and should use dynamic role mapping based on user data structure.

🧹 Nitpick comments (1)
packages/prisma/seed-pbac-organization.ts (1)

617-691: Consider consolidating hardcoded data to reduce duplication

The password mapping and permission definitions are duplicated across the file. Consider creating centralized data structures to define user data and role permissions, then reference them in both creation and utility functions to improve maintainability.

+// Centralized user and role data
+const DEMO_USERS = {
+  owner: { email: "owner@pbac-demo.com", password: "pbac-owner-2024!", role: "owner" },
+  events: { email: "events@pbac-demo.com", password: "events-2024!", role: "Event Manager" },
+  // ... other users
+};
+
+const ROLE_PERMISSIONS = {
+  "Event Manager": [
+    { resource: "eventType", action: "create" },
+    // ... other permissions
+  ],
+  // ... other roles
+};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ac8c867 and 56dbe86.

📒 Files selected for processing (1)
  • packages/prisma/seed-pbac-organization.ts (1 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:

  • packages/prisma/seed-pbac-organization.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-21T13:54:11.770Z
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.770Z
Learning: Applies to backend/**/*.{ts,tsx} : For Prisma queries: Only select data you need.
packages/prisma/seed-pbac-organization.ts (1)

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

🧬 Code Graph Analysis (1)
packages/prisma/seed-pbac-organization.ts (2)
packages/platform/libraries/index.ts (1)
  • MembershipRole (98-98)
apps/web/playwright/fixtures/users.ts (1)
  • hashPassword (26-29)
⏰ 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/prisma/seed-pbac-organization.ts (3)

113-287: Well-structured custom role creation with comprehensive permissions

The function implements proper idempotency checks, creates roles with detailed permission sets, and maintains consistent patterns. The permission mappings are thorough and appropriate for each role type.


527-612: Well-implemented helper functions with proper separation of concerns

The helper functions handle user creation, membership management, and profile creation effectively. Password hashing follows security best practices, and the Prisma operations are correctly structured.


693-706: Proper script execution pattern with clean resource management

The direct execution block follows best practices with proper error handling, resource cleanup via Prisma disconnect, and appropriate exit codes.

@eunjae-lee eunjae-lee merged commit 045ea34 into main Jul 24, 2025
38 checks passed
@eunjae-lee eunjae-lee deleted the feat/pbac-seed branch July 24, 2025 22:05
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
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants