Skip to content

Redirect to pricing purchase after sign up#15

Merged
AnthonyRonning merged 1 commit intomasterfrom
pricing-signup-redirect
Jan 31, 2025
Merged

Redirect to pricing purchase after sign up#15
AnthonyRonning merged 1 commit intomasterfrom
pricing-signup-redirect

Conversation

@AnthonyRonning
Copy link
Contributor

@AnthonyRonning AnthonyRonning commented Jan 31, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced login, signup, and pricing routes to support plan selection during authentication flow.
    • Added automatic plan checkout for logged-in users with a selected plan.
  • Improvements

    • Refined navigation logic to handle plan selection across authentication routes.
    • Improved search parameter validation for better route handling.
  • User Experience

    • Streamlined authentication process with seamless plan selection.
    • More intuitive redirection after login or signup based on selected plan.

@coderabbitai
Copy link

coderabbitai bot commented Jan 31, 2025

Walkthrough

The pull request introduces enhancements to the frontend routing system by integrating a selected_plan parameter across various authentication and pricing-related routes. Changes include the addition of type definitions for search parameters, the implementation of a validateSearch function for parameter validation, and updates to navigation logic in the login, signup, and OAuth callback processes. This ensures a consistent user experience when selecting and managing plans during authentication flows.

Changes

File Change Summary
frontend/src/routes/__root.tsx Added RootSearchParams type definition with optional properties and validateSearch function for route parameter validation.
frontend/src/routes/login.tsx Updated LoginSearchParams to include selected_plan, modified login navigation logic to handle plan selection.
frontend/src/routes/signup.tsx Added selected_plan to SignupSearchParams, updated signup navigation to support plan selection.
frontend/src/routes/auth.$provider.callback.tsx Modified OAuth callback redirection to handle selected_plan from session storage.
frontend/src/routes/pricing.tsx Introduced PricingSearchParams, added automatic checkout initiation for logged-in users with a selected plan.

Sequence Diagram

sequenceDiagram
    participant User
    participant LoginPage
    participant AuthCallback
    participant PricingPage
    
    User->>LoginPage: Selects plan before login
    LoginPage->>AuthCallback: Passes selected_plan
    AuthCallback->>PricingPage: Redirects with selected_plan
    PricingPage->>PricingPage: Automatically initiate checkout
Loading

Possibly related PRs

  • Team pricing #5: The changes in the PricingPage component include enhancements related to the handling of the selected_plan, which is also a focus in the main PR's RootSearchParams and validateSearch function. Both PRs deal with the validation and management of search parameters related to plans.

Poem

🐰 A Rabbit's Route to Pricing Delight
Hops of code, parameters so bright,
Selected plans now dance with might,
From login to signup, a seamless flight,
Redirecting users with technical height,
Our routing magic takes playful flight! 🚀


🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Jan 31, 2025

Deploying maple with  Cloudflare Pages  Cloudflare Pages

Latest commit: 6432bc9
Status: ✅  Deploy successful!
Preview URL: https://78ce2a0d.maple-ca8.pages.dev
Branch Preview URL: https://pricing-signup-redirect.maple-ca8.pages.dev

View logs

Copy link

@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 (6)
frontend/src/routes/auth.$provider.callback.tsx (2)

54-71: Consider reducing the redirect delay.

The 2-second delay before redirect might be longer than necessary for a good user experience.

-          }, 2000);
+          }, 1000);

128-131: Enhance the success message with more details.

The current message could be more informative about what happens next.

-        You have successfully authenticated with {formattedProvider}.
-        {sessionStorage.getItem("selected_plan")
-          ? "Redirecting to complete your plan selection..."
-          : "Redirecting to home page..."}
+        You have successfully authenticated with {formattedProvider}. 
+        {sessionStorage.getItem("selected_plan")
+          ? "Redirecting to pricing page to complete your plan selection..."
+          : "Redirecting to your dashboard..."}
frontend/src/routes/signup.tsx (1)

85-87: Consider consolidating OAuth plan handling.

The plan storage logic is duplicated between GitHub and Google handlers.

+  const storeSelectedPlan = () => {
+    if (selected_plan) {
+      sessionStorage.setItem("selected_plan", selected_plan);
+    }
+  };
+
   const handleGitHubSignup = async () => {
     try {
       const { auth_url } = await os.initiateGitHubAuth("");
-      if (selected_plan) {
-        sessionStorage.setItem("selected_plan", selected_plan);
-      }
+      storeSelectedPlan();
       window.location.href = auth_url;
     } catch (error) {
       console.error("Failed to initiate GitHub signup:", error);
       setError("Failed to initiate GitHub signup. Please try again.");
     }
   };

   const handleGoogleSignup = async () => {
     try {
       const { auth_url } = await os.initiateGoogleAuth("");
-      if (selected_plan) {
-        sessionStorage.setItem("selected_plan", selected_plan);
-      }
+      storeSelectedPlan();
       window.location.href = auth_url;

Also applies to: 98-100

frontend/src/routes/pricing.tsx (3)

268-279: Consider adding error handling for invalid plan IDs.

While the redirection logic is correct, consider adding validation for the plan ID before redirection to prevent potential issues with invalid selections.

 const targetPlanName = product.name.toLowerCase();
+if (!product.id) {
+  console.error('Invalid product: missing ID');
+  navigate({ to: "/signup" });
+  return;
+}
 if (!targetPlanName.includes("free")) {
   navigate({
     to: "/signup",

363-371: Add cleanup and loading state management to the useEffect hook.

The auto-checkout effect could benefit from these improvements:

  1. Add cleanup to prevent state updates after unmount
  2. Add loading state management to prevent multiple triggers
 useEffect(() => {
+  let isSubscribed = true;
+
   // If user is logged in and there's a selected plan, trigger checkout
   if (isLoggedIn && selected_plan && !isBillingStatusLoading) {
+    if (loadingProductId) return; // Prevent multiple triggers
     const product = products?.find((p) => p.id === selected_plan);
     if (product) {
-      handleButtonClick(product);
+      if (isSubscribed) {
+        handleButtonClick(product);
+      }
     }
   }
+  return () => {
+    isSubscribed = false;
+  };
-}, [isLoggedIn, selected_plan, isBillingStatusLoading, products]);
+}, [isLoggedIn, selected_plan, isBillingStatusLoading, products, loadingProductId]);

614-619: Consider adding stricter validation for selected_plan.

While the type validation is correct, consider adding validation to ensure the selected_plan matches a valid product ID pattern to prevent invalid values from being processed.

 validateSearch: (search: Record<string, unknown>): PricingSearchParams => ({
-  selected_plan: typeof search.selected_plan === "string" ? search.selected_plan : undefined,
+  selected_plan: typeof search.selected_plan === "string" && 
+    /^prod_[A-Za-z0-9]{14,}$/.test(search.selected_plan) ? 
+    search.selected_plan : undefined,
   success: typeof search.success === "boolean" ? search.success : undefined,
   canceled: typeof search.canceled === "boolean" ? search.canceled : undefined
 })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9c2846e and bcd3e77.

📒 Files selected for processing (5)
  • frontend/src/routes/__root.tsx (1 hunks)
  • frontend/src/routes/auth.$provider.callback.tsx (2 hunks)
  • frontend/src/routes/login.tsx (5 hunks)
  • frontend/src/routes/pricing.tsx (5 hunks)
  • frontend/src/routes/signup.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (6)
frontend/src/routes/__root.tsx (2)

9-15: LGTM! Well-structured type definition.

The RootSearchParams type properly defines all optional parameters needed across routes.


19-25: LGTM! Robust search parameter validation.

The validation logic correctly handles type coercion for all parameters, ensuring type safety.

frontend/src/routes/signup.tsx (1)

13-14: LGTM! Consistent type handling.

The SignupSearchParams type and validation logic align well with the root route implementation.

Also applies to: 20-21

frontend/src/routes/login.tsx (1)

85-87: Consider consolidating OAuth plan handling.

Similar to the signup route, the plan storage logic is duplicated between OAuth handlers.

Apply the same refactoring pattern suggested for the signup route to reduce code duplication.

Also applies to: 98-100

frontend/src/routes/pricing.tsx (2)

15-19: LGTM! Well-structured type definition.

The PricingSearchParams type properly defines the optional parameters needed for plan selection and checkout status tracking.


134-134: LGTM! Proper usage of React Router hooks.

The selected_plan extraction using Route.useSearch() follows React Router patterns correctly.

@AnthonyRonning AnthonyRonning force-pushed the pricing-signup-redirect branch from 5c4828b to 6432bc9 Compare January 31, 2025 21:50
Copy link

@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)
frontend/src/routes/pricing.tsx (1)

268-279: Consider extracting the free plan check to a constant.

The implementation correctly handles navigation with plan selection, but the string check for free plans could be more maintainable.

Consider this improvement:

+const FREE_PLAN_IDENTIFIER = 'free';
+
 const handleButtonClick = (product: any) => {
   if (!isLoggedIn) {
     const targetPlanName = product.name.toLowerCase();
-    if (!targetPlanName.includes("free")) {
+    if (!targetPlanName.includes(FREE_PLAN_IDENTIFIER)) {
       navigate({
         to: "/signup",
         search: {
           next: "/pricing",
           selected_plan: product.id
         }
       });
       return;
     }
     navigate({ to: "/signup" });
     return;
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5c4828b and 6432bc9.

📒 Files selected for processing (5)
  • frontend/src/routes/__root.tsx (1 hunks)
  • frontend/src/routes/auth.$provider.callback.tsx (2 hunks)
  • frontend/src/routes/login.tsx (5 hunks)
  • frontend/src/routes/pricing.tsx (6 hunks)
  • frontend/src/routes/signup.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • frontend/src/routes/auth.$provider.callback.tsx
  • frontend/src/routes/__root.tsx
  • frontend/src/routes/login.tsx
  • frontend/src/routes/signup.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (4)
frontend/src/routes/pricing.tsx (4)

15-19: LGTM! Well-structured type definition.

The PricingSearchParams type clearly defines the optional parameters needed for plan selection and payment status tracking.


134-134: LGTM! Clean parameter extraction.

The implementation correctly extracts the selected_plan parameter using React Router's hook.


630-635: LGTM! Robust search parameter validation.

The validation implementation correctly handles type checking and undefined cases for all search parameters.


363-387: Add products array existence check to prevent potential race condition.

While the implementation handles loading states well, there's a potential race condition if the products array is accessed before it's loaded.

Consider adding an explicit check:

 useEffect(() => {
   let isSubscribed = true;

   // If user is logged in and there's a selected plan, trigger checkout
-  if (isLoggedIn && selected_plan && !isBillingStatusLoading) {
+  if (isLoggedIn && selected_plan && !isBillingStatusLoading && products) {
     if (loadingProductId) return; // Prevent multiple triggers
     const product = products?.find((p) => p.id === selected_plan);
     if (product) {
       if (isSubscribed) {
         handleButtonClick(product);
       }
     }
   }

   return () => {
     isSubscribed = false;
   };
 }, [
   isLoggedIn,
   selected_plan,
   isBillingStatusLoading,
   products,
   loadingProductId,
   handleButtonClick
 ]);

@AnthonyRonning AnthonyRonning merged commit 564c44d into master Jan 31, 2025
2 checks passed
@AnthonyRonning AnthonyRonning deleted the pricing-signup-redirect branch January 31, 2025 22:01
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