Skip to content

fix: don't use unpublished org in any credit context#22600

Merged
anikdhabal merged 5 commits intocalcom:mainfrom
anikdhabal:unpublished_org_for_credit
Jul 18, 2025
Merged

fix: don't use unpublished org in any credit context#22600
anikdhabal merged 5 commits intocalcom:mainfrom
anikdhabal:unpublished_org_for_credit

Conversation

@anikdhabal
Copy link
Copy Markdown
Contributor

What does this PR do?

  • Fixes #XXXX (GitHub issue number)
  • Fixes CAL-XXXX (Linear issue number - should be visible at the bottom of the GitHub issue description)

Visual Demo (For contributors especially)

A visual demonstration is strongly recommended, for both the original and new change (video / image - any one).

Video Demo (if applicable):

  • Show screen recordings of the issue or feature.
  • Demonstrate how to reproduce the issue, the behavior before and after the change.

Image Demo (if applicable):

  • Add side-by-side screenshots of the original and updated change.
  • Highlight any significant change(s).

Mandatory Tasks (DO NOT REMOVE)

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

How should this be tested?

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

Checklist

  • I haven't read the contributing guide
  • My code doesn't follow the style guidelines of this project
  • I haven't commented my code, particularly in hard-to-understand areas
  • I haven't checked if my changes generate no new warnings

@anikdhabal anikdhabal requested a review from CarinaWolli July 17, 2025 17:01
@vercel
Copy link
Copy Markdown

vercel bot commented Jul 17, 2025

@anikdhabal 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
Copy Markdown
Contributor

coderabbitai bot commented Jul 17, 2025

Walkthrough

The changes rename the existing method findAllAcceptedMemberships in the MembershipRepository class to findAllAcceptedPublishedTeamMemberships and update it to filter memberships by userId, accepted status, and require the associated team to have a non-null slug. The CreditService class modifies its protected method _getTeamWithAvailableCredits to call this updated method and adds a check for falsy or empty membership results. API handlers and the Twilio webhook endpoint update their membership queries similarly and add safeguards against falsy membership results. Corresponding test cases are updated to mock the renamed repository method. No exported or public entity signatures were changed.

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/lib/server/repository/membership.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.

packages/trpc/server/routers/viewer/credits/buyCredits.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.

packages/trpc/server/routers/viewer/credits/getAllCredits.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 a952652 and 25bf835.

📒 Files selected for processing (3)
  • packages/lib/server/repository/membership.ts (1 hunks)
  • packages/trpc/server/routers/viewer/credits/buyCredits.handler.ts (1 hunks)
  • packages/trpc/server/routers/viewer/credits/getAllCredits.handler.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/lib/server/repository/membership.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). (2)
  • GitHub Check: Install dependencies / Yarn install & cache
  • GitHub Check: Security Check
🔇 Additional comments (4)
packages/trpc/server/routers/viewer/credits/buyCredits.handler.ts (2)

37-37: Good change to restrict to published teams only.

The method name change from findAllAcceptedMemberships to findAllAcceptedPublishedTeamMemberships correctly aligns with the PR objective to prevent unpublished organizations from being used in credit contexts.


39-39: Good defensive programming with null check.

Adding the !memberships || check prevents potential runtime errors if the repository method returns null or undefined, making the code more robust.

packages/trpc/server/routers/viewer/credits/getAllCredits.handler.ts (2)

28-28: Correct method update to filter published teams.

The method name change from findAllAcceptedMemberships to findAllAcceptedPublishedTeamMemberships is consistent with the PR objective and ensures only published organizations are considered in credit contexts.


30-30: Good addition of null safety check.

Adding the !memberships || check provides protection against null/undefined results from the repository method, improving code reliability.

✨ 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.

@graphite-app graphite-app bot requested a review from a team July 17, 2025 17:01
@keithwillcode keithwillcode added the core area: core, team members only label Jul 17, 2025
@dosubot dosubot bot added billing area: billing, stripe, payments, paypal, get paid 🐛 bug Something isn't working labels Jul 17, 2025
Copy link
Copy Markdown
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)
apps/web/pages/api/twilio/webhook.ts (1)

83-96: Consider using the new repository method for consistency.

The inline filtering logic is correct, but for better maintainability and consistency, consider using the new MembershipRepository.findAllAcceptedPublishedTeamMemberships method instead of duplicating the filtering logic.

Apply this refactor to use the centralized method:

-      const teamMembership = await prisma.membership.findFirst({
-        where: {
-          userId: parsedUserId,
-          accepted: true,
-          team: {
-            slug: { not: null },
-          },
-        },
-        select: {
-          teamId: true,
-        },
-      });
+      const { MembershipRepository } = await import("@calcom/lib/server/repository/membership");
+      const memberships = await MembershipRepository.findAllAcceptedPublishedTeamMemberships(parsedUserId);
+      const teamMembership = memberships[0];
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4dc2260 and 43df4bd.

📒 Files selected for processing (3)
  • apps/web/pages/api/twilio/webhook.ts (1 hunks)
  • packages/features/ee/billing/credit-service.ts (1 hunks)
  • packages/lib/server/repository/membership.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/lib/server/repository/membership.ts (1)
packages/prisma/index.ts (1)
  • PrismaTransaction (91-91)
packages/features/ee/billing/credit-service.ts (1)
packages/lib/server/repository/membership.ts (1)
  • MembershipRepository (72-436)
⏰ 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: Detect changes
  • GitHub Check: Security Check
🔇 Additional comments (2)
packages/lib/server/repository/membership.ts (1)

357-370: LGTM! Well-implemented method following established patterns.

The new findAllAcceptedPublishedTeamMemberships method correctly implements the filtering logic to exclude unpublished teams. The implementation follows the established patterns in the class with proper transaction handling and consistent return structure.

packages/features/ee/billing/credit-service.ts (1)

194-194: LGTM! Correctly implements the filtering for published teams only.

The change from findAllAcceptedMemberships to findAllAcceptedPublishedTeamMemberships properly addresses the PR objective by ensuring only published teams are considered in credit contexts.

@graphite-app
Copy link
Copy Markdown

graphite-app bot commented Jul 17, 2025

Graphite Automations

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

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

@anikdhabal anikdhabal requested a review from CarinaWolli July 18, 2025 09:24
@anikdhabal anikdhabal enabled auto-merge (squash) July 18, 2025 09:25
@anikdhabal anikdhabal merged commit c8de8ca into calcom:main Jul 18, 2025
56 of 61 checks passed
@github-actions
Copy link
Copy Markdown
Contributor

E2E results are ready!

@anikdhabal anikdhabal deleted the unpublished_org_for_credit branch July 18, 2025 13:15
devin-ai-integration bot added a commit that referenced this pull request Jul 18, 2025
…nario

- Add clearer comments explaining user has memberships in both teams
- Clarify that repository method filters out unpublished platform orgs
- Better document the architectural change from PR #22600

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
devin-ai-integration bot added a commit that referenced this pull request Jul 18, 2025
- Clarify that user has memberships in BOTH teams initially in database
- Explain that repository method filters out unpublished platform org (teamId: 1)
- Document that only regular team (teamId: 2) is returned to credit service
- Address user feedback about demonstrating the filtering behavior clearly
- Test validates integration with repository-level filtering from PR #22600

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
anikdhabal added a commit that referenced this pull request Jul 19, 2025
…credit usage (#22567)

* feat: add test to verify unpublished platform orgs are excluded from credit usage

- Add filtering logic in _getTeamWithAvailableCredits to skip unpublished platform organizations
- Add comprehensive test case that verifies user with memberships in both unpublished platform org and regular team
- Ensure only regular team is selected for credit usage, not unpublished platform org
- Test validates team.findUnique calls and credit balance checks for correct team filtering

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* Update credit-service.ts

* Update credit-service.test.ts

* fix: update test to work with repository-level filtering for unpublished platform orgs

- Remove obsolete team.findUnique mocking since filtering moved to repository layer
- Update test to mock findAllAcceptedPublishedTeamMemberships correctly
- Test now validates integration with repository-level filtering
- Maintains core validation that unpublished platform orgs are excluded from credit usage

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* docs: improve test comments to clarify repository-level filtering scenario

- Add clearer comments explaining user has memberships in both teams
- Clarify that repository method filters out unpublished platform orgs
- Better document the architectural change from PR #22600

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* docs: clarify test demonstrates user with memberships in both teams

- Add detailed comments explaining user has memberships in TWO teams initially
- Clarify that unpublished platform org (teamId: 1) and regular team (teamId: 2) scenario
- Explain repository-level filtering removes unpublished platform orgs before credit service
- Address user feedback about demonstrating two-team membership scenario

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* docs: add comprehensive comments explaining two-team filtering scenario

- Clarify that user has memberships in BOTH teams initially in database
- Explain that repository method filters out unpublished platform org (teamId: 1)
- Document that only regular team (teamId: 2) is returned to credit service
- Address user feedback about demonstrating the filtering behavior clearly
- Test validates integration with repository-level filtering from PR #22600

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* fix: update test to properly demonstrate filtering behavior

- Mock repository to return only regular team (teamId: 2) as expected after filtering
- Update credit balance mock and expectations to match teamId: 2
- Test now passes and validates that unpublished platform org is filtered out
- Address user feedback about showing correct filtering behavior in test logic

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* feat: demonstrate two-team membership scenario in test logic

- Mock repository to return both membership objects: teamId 1 and teamId 2
- Show user has memberships in both unpublished platform org and regular team
- Mock different credit states: teamId 1 has no credits/limit reached, teamId 2 has available credits
- Verify both teams are processed but only regular team (teamId 2) is selected
- Test now demonstrates actual filtering behavior in test logic, not just comments
- Addresses user feedback: 'create two membership with those two teams in that test'

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* feat: demonstrate two-team membership scenario in test logic

- Mock repository to return both membership objects: teamId 1 and teamId 2
- Show user has memberships in both unpublished platform org and regular team
- Mock different credit states: teamId 1 has no credits/limit reached, teamId 2 has available credits
- Verify both teams are processed but only regular team (teamId 2) is selected
- Test now demonstrates actual filtering behavior in test logic, not just comments
- Addresses user feedback: 'create two membership with those two teams in that test'

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* Revert "feat: demonstrate two-team membership scenario in test logic"

This reverts commit d7c4beb.

* Update credit-service.test.ts

* Update credit-service.test.ts

* Update credit-service.test.ts

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
zomars pushed a commit that referenced this pull request Jul 22, 2025
* fix: don't use unpublished org for any credit context

* type error

* fix test

* update
zomars pushed a commit that referenced this pull request Jul 22, 2025
…credit usage (#22567)

* feat: add test to verify unpublished platform orgs are excluded from credit usage

- Add filtering logic in _getTeamWithAvailableCredits to skip unpublished platform organizations
- Add comprehensive test case that verifies user with memberships in both unpublished platform org and regular team
- Ensure only regular team is selected for credit usage, not unpublished platform org
- Test validates team.findUnique calls and credit balance checks for correct team filtering

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* Update credit-service.ts

* Update credit-service.test.ts

* fix: update test to work with repository-level filtering for unpublished platform orgs

- Remove obsolete team.findUnique mocking since filtering moved to repository layer
- Update test to mock findAllAcceptedPublishedTeamMemberships correctly
- Test now validates integration with repository-level filtering
- Maintains core validation that unpublished platform orgs are excluded from credit usage

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* docs: improve test comments to clarify repository-level filtering scenario

- Add clearer comments explaining user has memberships in both teams
- Clarify that repository method filters out unpublished platform orgs
- Better document the architectural change from PR #22600

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* docs: clarify test demonstrates user with memberships in both teams

- Add detailed comments explaining user has memberships in TWO teams initially
- Clarify that unpublished platform org (teamId: 1) and regular team (teamId: 2) scenario
- Explain repository-level filtering removes unpublished platform orgs before credit service
- Address user feedback about demonstrating two-team membership scenario

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* docs: add comprehensive comments explaining two-team filtering scenario

- Clarify that user has memberships in BOTH teams initially in database
- Explain that repository method filters out unpublished platform org (teamId: 1)
- Document that only regular team (teamId: 2) is returned to credit service
- Address user feedback about demonstrating the filtering behavior clearly
- Test validates integration with repository-level filtering from PR #22600

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* fix: update test to properly demonstrate filtering behavior

- Mock repository to return only regular team (teamId: 2) as expected after filtering
- Update credit balance mock and expectations to match teamId: 2
- Test now passes and validates that unpublished platform org is filtered out
- Address user feedback about showing correct filtering behavior in test logic

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* feat: demonstrate two-team membership scenario in test logic

- Mock repository to return both membership objects: teamId 1 and teamId 2
- Show user has memberships in both unpublished platform org and regular team
- Mock different credit states: teamId 1 has no credits/limit reached, teamId 2 has available credits
- Verify both teams are processed but only regular team (teamId 2) is selected
- Test now demonstrates actual filtering behavior in test logic, not just comments
- Addresses user feedback: 'create two membership with those two teams in that test'

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* feat: demonstrate two-team membership scenario in test logic

- Mock repository to return both membership objects: teamId 1 and teamId 2
- Show user has memberships in both unpublished platform org and regular team
- Mock different credit states: teamId 1 has no credits/limit reached, teamId 2 has available credits
- Verify both teams are processed but only regular team (teamId 2) is selected
- Test now demonstrates actual filtering behavior in test logic, not just comments
- Addresses user feedback: 'create two membership with those two teams in that test'

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* Revert "feat: demonstrate two-team membership scenario in test logic"

This reverts commit d7c4beb.

* Update credit-service.test.ts

* Update credit-service.test.ts

* Update credit-service.test.ts

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@coderabbitai coderabbitai bot mentioned this pull request Aug 17, 2025
11 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

billing area: billing, stripe, payments, paypal, get paid 🐛 bug Something isn't working core area: core, team members only ready-for-e2e

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants