Skip to content

fix(billing): a user can add payment while upgrading their plan#2120

Merged
mcstepp merged 4 commits intomainfrom
ENG-1181-upgrade-payment-flow
Sep 20, 2024
Merged

fix(billing): a user can add payment while upgrading their plan#2120
mcstepp merged 4 commits intomainfrom
ENG-1181-upgrade-payment-flow

Conversation

@mcstepp
Copy link
Collaborator

@mcstepp mcstepp commented Sep 20, 2024

What does this PR do?

Previously, when a free user without a payment method was attempting to upgrade their plan, it would error out and notify the user that they must add add a payment method before upgrading.

This change will now catch a missing payment method (stripe association) when the user is upgrading their plan and redirect them Stripe to configure a payment method, and then continue the processing the plan change upon stripe success.

Edge case: When a user has already their stripe associated with Unkey, but has deleted their payment method from stripe, the user will get an error PRECONDITION FAILED when attempting to process their plan change. This is due to technical limitation due to where the stripe check lives (client-side), but it's still checked and guarded on the trpc route. The likelihood of a user configuring stripe and then deleting a payment is very slim.

New Package: PostHog-node to capture the plan change event from the server-side.

New Env variables for PostHog-node:

  • NEXT_PUBLIC_POSTHOG_HOST
  • NEXT_PUBLIC_POSTHOG_KEY

Fixes #2080

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

Manual testing

  1. Sign into unkey as a free user without a Stripe association
  2. Go to Settings > Billing > Change Plans
  3. Select Pro and confirm
  4. Be redirected to Stripe
  5. Add payment method and confirm
  6. Redirect back to Billing
  7. Notice plan has changed to Pro

Upgrade flow when user has added a payment method first is unchanged.

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features

    • Introduced a streamlined process for changing billing plans, including redirects to payment settings if necessary.
    • Enhanced Stripe checkout success flow to handle new plan parameters effectively.
  • Bug Fixes

    • Improved logic for updating the database during plan changes and logging events.
  • Chores

    • Added a new PostHog client wrapper for improved analytics tracking.
    • Updated dependencies to include posthog-node for future use.

@linear
Copy link

linear bot commented Sep 20, 2024

@changeset-bot
Copy link

changeset-bot bot commented Sep 20, 2024

⚠️ No Changeset found

Latest commit: 8fbb621

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel
Copy link

vercel bot commented Sep 20, 2024

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

Name Status Preview Comments Updated (UTC)
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 20, 2024 6:33pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 20, 2024 6:33pm
3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
dashboard ⬜️ Ignored (Inspect) Visit Preview Sep 20, 2024 6:33pm
planetfall ⬜️ Ignored (Inspect) Visit Preview Sep 20, 2024 6:33pm
workflows ⬜️ Ignored (Inspect) Visit Preview Sep 20, 2024 6:33pm

@vercel vercel bot temporarily deployed to Preview – workflows September 20, 2024 18:03 Inactive
@github-actions
Copy link
Contributor

github-actions bot commented Sep 20, 2024

Thank you for following the naming conventions for pull request titles! 🙏

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 20, 2024

Walkthrough

Walkthrough

The changes involve modifications to the billing and Stripe integration components within the dashboard application. Key updates include the introduction of a handleClick function in the ChangePlanButton component to manage billing plan changes and the enhancement of the StripeRedirect and StripeSuccess functions to handle new plan parameters during the checkout process. Additionally, a new PostHog client wrapper has been implemented for analytics, and a new dependency has been added to the project.

Changes

Files Change Summary
apps/dashboard/app/(app)/settings/billing/plans/button.tsx Added handleClick function to manage billing plan changes, including payment method checks and redirection logic. Updated button's onClick event handler.
apps/dashboard/app/(app)/settings/billing/stripe/page.tsx Updated StripeRedirect function to include a new Props type for handling optional new_plan parameter and modified URL construction based on the new plan.
apps/dashboard/app/(app)/settings/billing/stripe/success/page.tsx Enhanced StripeSuccess function to destructure new_plan from searchParams, updated logic for session retrieval, and conditionally included plan changes in DB updates.
apps/dashboard/lib/posthog.ts Introduced a singleton PostHog client wrapper for analytics, ensuring a single access point throughout the application.
apps/dashboard/package.json Added posthog-node dependency version ^4.2.0 to the project.

Assessment against linked issues

Objective Addressed Explanation
User should be redirected to the payment screen if no payment method is attached (#[2080])
Display an error if the user needs to attach a credit card (#[2080]) No error message is displayed for missing payment methods.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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.
    -- Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    -- @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 generate unit testing code.
    -- @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.

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

@vercel vercel bot temporarily deployed to Preview – planetfall September 20, 2024 18:07 Inactive
@vercel vercel bot temporarily deployed to Preview – www September 20, 2024 18:11 Inactive
@vercel vercel bot temporarily deployed to Preview – workflows September 20, 2024 18:13 Inactive
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: 3

Outside diff range and nitpick comments (1)
apps/dashboard/app/(app)/settings/billing/stripe/success/page.tsx (1)

88-92: Add error handling for PostHog event capture

To prevent uncaught exceptions during event capture, add error handling around PostHogClient.capture.

Apply this diff to add a try-catch block:

if (isChangingPlan) {
+ try {
    PostHogClient.capture({
      distinctId: tenantId,
      event: "plan_changed",
      properties: { plan: new_plan, workspace: ws.id },
    });
+ } catch (error) {
+   console.error("PostHog capture failed:", error);
+ }
}
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ee07672 and 1e0c6c1.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (5)
  • apps/dashboard/app/(app)/settings/billing/plans/button.tsx (2 hunks)
  • apps/dashboard/app/(app)/settings/billing/stripe/page.tsx (2 hunks)
  • apps/dashboard/app/(app)/settings/billing/stripe/success/page.tsx (3 hunks)
  • apps/dashboard/lib/posthog.ts (1 hunks)
  • apps/dashboard/package.json (1 hunks)
Additional comments not posted (10)
apps/dashboard/lib/posthog.ts (1)

3-27: LGTM!

The PostHogClientWrapper class is a well-designed singleton that provides a centralized way to initialize and access the PostHog client instance. It handles the case when the required environment variables are missing by providing a mock client, ensuring that the application gracefully handles missing configuration. The class encapsulates the initialization logic and configuration of the PostHog client, making it easier to manage and update.

apps/dashboard/app/(app)/settings/billing/stripe/page.tsx (3)

10-14: LGTM!

The Props type definition is clear and accurately captures the structure of the StripeRedirect function's parameter. The new_plan property is well-defined with the possible values it can take.


16-17: LGTM!

The StripeRedirect function signature is correctly updated to accept the props parameter of type Props. Destructuring new_plan from props.searchParams is a clean and readable approach.


63-68: LGTM!

The modification to the successUrl string is a good addition. It allows the URL to carry the new plan information when redirecting after a successful Stripe checkout session. The condition ensures that the new_plan parameter is only appended when necessary, i.e., when it's defined and different from the current plan.

apps/dashboard/app/(app)/settings/billing/plans/button.tsx (2)

48-58: LGTM!

The handleClick function correctly manages the logic for changing the billing plan. It checks for the presence of a payment method and redirects the user to add a payment method if necessary before proceeding with the plan change. The logic is well-structured and improves the user experience.


105-105: LGTM!

Updating the button's onClick event handler to call the handleClick function is a good change. It centralizes the plan change logic and improves code readability.

apps/dashboard/package.json (1)

92-92: New dependency added for server-side analytics.

The posthog-node package has been added as a new dependency, likely for implementing server-side analytics. This is a good addition to gain insights into user behavior and application performance.

Please ensure that the package is being utilized effectively in the codebase to capture relevant events and metrics. Additionally, consider setting up a process to keep this dependency updated to benefit from bug fixes and enhancements while respecting the specified version constraint.

Can you provide more context on the specific use case and implementation of posthog-node in this project?

apps/dashboard/app/(app)/settings/billing/stripe/success/page.tsx (3)

75-75: Check logical conditions for isChangingPlan

Ensure that the logic correctly handles all cases, including when new_plan is undefined or the same as ws.plan.

Run the following script to verify the possible values of new_plan and ws.plan:

#!/bin/bash
# Description: List all possible values of `ws.plan` in the codebase.

rg --type javascript --type typescript 'ws\.plan' -A 2

88-92: Ensure compliance with data privacy when using tenantId

Using tenantId as distinctId might raise privacy concerns if it can be linked to an individual. Verify that this usage complies with your data privacy policies.

Run the following script to review all usages of tenantId with PostHog:

#!/bin/bash
# Description: Find all instances where `tenantId` is used with PostHogClient.

rg --type javascript --type typescript 'PostHogClient\.capture\({\s*distinctId:\s*tenantId' -A 5

6-6: Ensure PostHogClient is properly configured

The import statement adds PostHogClient, but please verify that it is correctly configured and initialized to avoid any runtime issues.

Run the following script to check the initialization of PostHogClient:

Verification successful

PostHogClient is properly configured and used

The verification process has confirmed that the PostHogClient is correctly set up and utilized in the codebase:

  1. The PostHogClient is defined and configured in apps/dashboard/lib/posthog.ts as a singleton instance, with proper error handling for missing environment variables.
  2. The PostHogProvider component in apps/dashboard/providers/PostHogProvider.tsx ensures client-side initialization and provides additional tracking utilities.
  3. In the file under review, PostHogClient is correctly imported and used to capture an event (line 88).

No further action is required regarding the PostHogClient configuration.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find where PostHogClient is initialized.
rg --type javascript --type typescript 'PostHogClient\s*=\s*' -A 5

Length of output: 256


Script:

#!/bin/bash
# Search for any occurrences of PostHogClient in the codebase
echo "Searching for PostHogClient occurrences:"
rg "PostHogClient" --type typescript --type javascript

echo "\nSearching for PostHogClient imports:"
rg "import.*PostHogClient" --type typescript --type javascript

echo "\nSearching for PostHog configuration files:"
fd "posthog" --type f

Length of output: 696


Script:

#!/bin/bash
echo "Content of apps/dashboard/lib/posthog.ts:"
cat apps/dashboard/lib/posthog.ts

echo "\nContent of apps/dashboard/providers/PostHogProvider.tsx:"
cat apps/dashboard/providers/PostHogProvider.tsx

echo "\nChecking usage of PostHogClient in apps/dashboard/app/(app)/settings/billing/stripe/success/page.tsx:"
grep -n "PostHogClient" apps/dashboard/app/\(app\)/settings/billing/stripe/success/page.tsx

Length of output: 3515

@vercel vercel bot temporarily deployed to Preview – play September 20, 2024 18:15 Inactive
@vercel vercel bot temporarily deployed to Preview – dashboard September 20, 2024 18:15 Inactive
@vercel vercel bot temporarily deployed to Preview – play September 20, 2024 18:32 Inactive
@vercel vercel bot temporarily deployed to Preview – www September 20, 2024 18:32 Inactive
@mcstepp mcstepp added this pull request to the merge queue Sep 20, 2024
Merged via the queue into main with commit 2cf7e94 Sep 20, 2024
@mcstepp mcstepp deleted the ENG-1181-upgrade-payment-flow branch September 20, 2024 18:58
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.

Upgrade account flow is broken due to requiring a payment

2 participants