Skip to content

Loops billing#464

Merged
elie222 merged 2 commits intomainfrom
stripe-loops
May 28, 2025
Merged

Loops billing#464
elie222 merged 2 commits intomainfrom
stripe-loops

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented May 28, 2025

Summary by CodeRabbit

  • New Features
    • Introduced automated handling of subscription events, including trial starts, trial completions, upgrades to premium, and cancellations, ensuring user status is accurately reflected.
    • Added support for sending "completed trial" events with tier information to external systems.
  • Bug Fixes
    • Improved error handling to prevent interruptions during subscription data synchronization.
  • Tests
    • Added comprehensive tests covering all major subscription event scenarios for enhanced reliability.

@vercel
Copy link

vercel bot commented May 28, 2025

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

Name Status Preview Updated (UTC)
inbox-zero ✅ Ready (Inspect) Visit Preview May 28, 2025 9:28am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 28, 2025

Walkthrough

A new event handling function, handleLoopsEvents, was introduced to process Stripe subscription lifecycle changes and synchronize them with the Loops system. This function is now invoked after updating subscription data in the database. Comprehensive tests for handleLoopsEvents were added, and a new Loops API function, completedTrial, was implemented. Additionally, the Loops API function upgradedToPremium was renamed to startedTrial, and related imports and calls were updated accordingly.

Changes

File(s) Change Summary
apps/web/ee/billing/stripe/loops-events.ts Added handleLoopsEvents to process subscription trial, upgrade, and cancellation events with Loops integration.
apps/web/ee/billing/stripe/loops-events.test.ts Introduced a comprehensive test suite for handleLoopsEvents covering multiple subscription event scenarios.
apps/web/ee/billing/stripe/sync-stripe.ts Enhanced syncStripeDataToDb to call handleLoopsEvents after updating subscription data.
packages/loops/src/loops.ts Renamed upgradedToPremium to startedTrial; added new Loops API function completedTrial for "completed_trial" events.
apps/web/app/api/lemon-squeezy/webhook/route.ts Updated import and usage of startedTrial replacing upgradedToPremium in subscription created webhook handler.

Sequence Diagram(s)

sequenceDiagram
    participant Stripe
    participant syncStripeDataToDb
    participant DB
    participant handleLoopsEvents
    participant LoopsAPI

    Stripe->>syncStripeDataToDb: Stripe event (subscription update)
    syncStripeDataToDb->>DB: Retrieve current premium state
    syncStripeDataToDb->>DB: Update premium record with new subscription data
    syncStripeDataToDb->>handleLoopsEvents: Call with current and new subscription data
    handleLoopsEvents-->>LoopsAPI: createContact / startedTrial / cancelledPremium / completedTrial (as needed)
    LoopsAPI-->>handleLoopsEvents: Response
    handleLoopsEvents-->>syncStripeDataToDb: Complete
Loading

Poem

In the warren where code and carrots meet,
Stripe and Loops now sync so neat.
Trials, upgrades, cancels—each event in view,
Rabbits test it all, as thorough bunnies do.
With every hop, a function or two—
Premiums and trials, all handled anew!
🥕

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.

apps/web/app/api/lemon-squeezy/webhook/route.ts

Oops! Something went wrong! :(

ESLint: 9.24.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

apps/web/ee/billing/stripe/loops-events.test.ts

Oops! Something went wrong! :(

ESLint: 9.24.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

apps/web/ee/billing/stripe/loops-events.ts

Oops! Something went wrong! :(

ESLint: 9.24.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

  • 1 others

📜 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 8573225 and 060cac6.

📒 Files selected for processing (4)
  • apps/web/app/api/lemon-squeezy/webhook/route.ts (2 hunks)
  • apps/web/ee/billing/stripe/loops-events.test.ts (1 hunks)
  • apps/web/ee/billing/stripe/loops-events.ts (1 hunks)
  • packages/loops/src/loops.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/loops/src/loops.ts
  • apps/web/ee/billing/stripe/loops-events.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/web/app/api/lemon-squeezy/webhook/route.ts (1)
packages/loops/src/loops.ts (1)
  • startedTrial (43-56)
🔇 Additional comments (10)
apps/web/app/api/lemon-squeezy/webhook/route.ts (1)

24-24: LGTM! Function rename is correctly applied.

The import and function call changes from upgradedToPremium to startedTrial are consistent and semantically more accurate for subscription creation events. The function signature remains the same, maintaining compatibility.

Also applies to: 162-162

apps/web/ee/billing/stripe/loops-events.test.ts (9)

1-31: Excellent test setup with proper mocking.

The test file demonstrates good testing practices:

  • Proper mocking of external dependencies (@inboxzero/loops and logger)
  • Clean mock setup with beforeEach cleanup
  • Well-organized imports and test structure

46-66: Thorough trial start scenario testing.

The test correctly validates the trial start logic with proper edge case handling:

  • Future trial end timestamp validation
  • Contact creation with proper name extraction (first name only)
  • Correct parameters passed to createContact

67-86: Good edge case coverage for past trial end.

The test correctly verifies that no contact is created when the trial end is in the past, which is appropriate business logic.


107-127: Proper handling of missing user names.

The test correctly verifies that when a user has no name, undefined is passed to createContact, which is the expected behavior for extracting the first name from a null value.


129-175: Comprehensive trial completion testing.

The test suite properly validates trial completion scenarios:

  • Transition from trialing to active status
  • Correct completedTrial function calls with email and tier
  • Proper exclusion logic when tier is null

177-290: Excellent direct upgrade scenario coverage.

The tests thoroughly cover direct subscription upgrades:

  • First-time subscriptions (no previous status)
  • Transitions from incomplete to active
  • Proper exclusions for null tiers and non-active statuses
  • Correct separation of trial completion vs. direct upgrade logic

292-372: Comprehensive cancellation scenario testing.

The test suite properly validates subscription cancellation events:

  • Multiple cancellation states (canceled, unpaid, incomplete_expired)
  • Proper status change detection to avoid duplicate events
  • Correct cancelledPremium function calls

374-454: Excellent edge case coverage.

The test suite demonstrates thorough edge case handling:

  • Null premium objects
  • Missing/empty emails
  • Admin email fallback logic
  • Graceful error handling for API failures
  • Proper early returns for invalid data

456-502: Complex scenario testing adds good coverage.

The additional complex scenarios provide valuable test coverage:

  • Trial state transitions without payment events
  • Name parsing with multiple spaces (first name extraction)
  • Proper isolation of different event types
✨ Finishing Touches
  • 📝 Generate Docstrings

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

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

🧹 Nitpick comments (1)
apps/web/ee/billing/stripe/loops-events.ts (1)

22-22: Consider typing the newSubscription parameter.

The newSubscription parameter is typed as any. Consider creating a proper type interface for better type safety and developer experience.

-  newSubscription: any;
+  newSubscription: {
+    status: string;
+    trial_end?: number | null;
+    // Add other fields as needed
+  };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0e2e86a and 8573225.

📒 Files selected for processing (4)
  • apps/web/ee/billing/stripe/loops-events.test.ts (1 hunks)
  • apps/web/ee/billing/stripe/loops-events.ts (1 hunks)
  • apps/web/ee/billing/stripe/sync-stripe.ts (5 hunks)
  • packages/loops/src/loops.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/web/ee/billing/stripe/sync-stripe.ts (1)
apps/web/ee/billing/stripe/loops-events.ts (1)
  • handleLoopsEvents (10-86)
🔇 Additional comments (14)
apps/web/ee/billing/stripe/sync-stripe.ts (4)

5-5: Good integration design.

The import is correctly placed and follows the project's import organization.


17-27: Excellent design pattern for state change detection.

Retrieving the current premium state before updating enables proper detection of subscription lifecycle events. The selected fields match exactly what handleLoopsEvents expects.


92-94: Good optimization and consistency improvement.

Extracting newTrialEnd to a variable improves readability and ensures consistency between the database update and the event handling logic.


119-124: Proper placement of event handling.

Calling handleLoopsEvents after the database update ensures the subscription data is persisted before triggering side effects. The error handling in handleLoopsEvents ensures Loops failures won't break the sync process.

apps/web/ee/billing/stripe/loops-events.ts (4)

38-47: Trial start detection logic is correct.

The logic properly checks for:

  • Future trial end date
  • No previous subscription status
  • Handles name extraction correctly

49-69: First payment detection handles multiple scenarios well.

The logic correctly identifies first payments from:

  • Trial completion
  • New direct subscriptions
  • Transitions from incomplete status

The conditional logic is well-structured and comprehensive.


71-81: Cancellation detection covers all terminal states.

The logic properly handles the main cancellation states: canceled, unpaid, and incomplete_expired. The status change check prevents duplicate events.


82-85: Excellent error handling strategy.

Not throwing errors from Loops API failures ensures that subscription sync operations aren't interrupted by external service issues. This is the correct approach for side-effect operations.

apps/web/ee/billing/stripe/loops-events.test.ts (6)

1-29: Excellent test setup and organization.

The test file has proper mocking setup for external dependencies and follows good testing practices with beforeEach cleanup.


44-125: Comprehensive trial start scenario coverage.

The tests cover all important edge cases:

  • Normal trial start
  • Past trial end dates
  • Existing subscription status
  • Missing user names

127-237: Thorough first payment scenario testing.

The tests validate all the complex first payment detection logic:

  • Trial completion
  • New subscriptions
  • Incomplete transitions
  • Null tier handling
  • Non-active status handling

239-319: Complete cancellation scenario coverage.

Tests cover all cancellation states and the important logic of preventing duplicate cancellation events when status hasn't changed.


321-399: Excellent edge case and error handling coverage.

The tests properly validate:

  • Null currentPremium handling
  • Missing email scenarios
  • Admin email fallback
  • Graceful error handling

401-448: Good complex scenario testing.

The complex scenarios test realistic edge cases like simultaneous trial start and payment, and proper name parsing with multiple spaces.

@elie222 elie222 merged commit 72fe513 into main May 28, 2025
6 checks passed
@elie222 elie222 deleted the stripe-loops branch December 18, 2025 23:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant