Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Send recovery url to users with expired checkout sessions #1555

Merged
merged 10 commits into from
Feb 10, 2025

Conversation

lukevella
Copy link
Owner

@lukevella lukevella commented Feb 9, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced the checkout experience with sessions expiring in 30 minutes and added recovery and promotional options for abandoned sessions.
    • Introduced automated abandoned checkout email notifications featuring personalized greetings, discount offers, and updated design elements.
    • Improved email communications by allowing customizable sender details and optional layout features.
    • Added a new email template specifically for abandoned checkouts.
    • Introduced a new component for rendering abandoned checkout emails.
  • Chores
    • Added a utility script to manage checkout session expiration for improved operations.

Copy link

vercel bot commented Feb 9, 2025

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

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 10, 2025 6:14am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
landing ⬜️ Skipped (Inspect) Feb 10, 2025 6:14am

Copy link
Contributor

coderabbitai bot commented Feb 9, 2025

Walkthrough

This change introduces several enhancements to the checkout and abandoned checkout flows. On the Stripe side, new properties have been added to the checkout session creation process, and a new case has been implemented in the webhook handler to process expired sessions. Additionally, a new billing script is added for session creation and expiration. Email functionality is extended with additional abandoned checkout templates, localized content, previews, and improved configuration for sender details. Several UI components were updated to support new properties, and a Signature component was introduced.

Changes

File(s) Changes Summary
apps/web/src/app/api/stripe/checkout/route.ts Added new properties expires_at (30 minutes ahead) and after_expiration with a recovery object to the Stripe checkout session creation process.
apps/web/src/app/api/stripe/webhook/route.ts Introduced a new case to handle the "checkout.session.expired" event; logs session details, validates metadata, checks the KV store, and sends an abandoned checkout email if conditions are met.
packages/billing/package.json
packages/billing/src/scripts/checkout-expiry.ts
Added a new script "checkout-expiry" in package.json and a new script file that creates a checkout session and immediately expires it using the Stripe API.
packages/emails/locales/en/emails.json
packages/emails/src/templates.ts
packages/emails/src/templates/abandoned-checkout.tsx
Added abandoned checkout email entries in localization, incorporated the new AbandonedCheckoutEmail template into the templates object, and implemented its structure and a getSubject method for localized subject lines.
packages/emails/src/components/email-layout.tsx
packages/emails/src/components/styled-components.tsx
packages/emails/src/previews/abandoned-checkout.tsx
packages/emails/src/send-email.tsx
Updated EmailLayout to conditionally render "Powered by" via an optional poweredBy prop, introduced a new Signature component, added an abandoned checkout email preview, and enhanced send-email logic with an optional from property.

Sequence Diagram(s)

sequenceDiagram
    participant Script as Checkout Expiry Script
    participant Stripe as Stripe API
    Note over Script,Stripe: Checkout Session Creation & Expiration
    Script->>Stripe: Create session with expires_at & after_expiration
    Stripe-->>Script: Return session ID & checkout URL
    Script->>Stripe: Expire session using session ID
    Stripe-->>Script: Confirm session expiry
Loading
sequenceDiagram
    participant Stripe as Stripe
    participant Webhook as Webhook Handler
    participant KV as KV Store
    participant Email as Email Client
    Note over Stripe,Email: Handling Expired Checkout Session Event
    Stripe->>Webhook: Send "checkout.session.expired" event
    Webhook->>Webhook: Log and extract session details
    Webhook->>KV: Check if promo email already sent
    alt Email not sent and user eligible
        KV-->>Webhook: Not found
        Webhook->>Email: Send abandoned checkout email
        Webhook->>KV: Set email sent flag (30-day expiry)
    else Already sent or missing data
        KV-->>Webhook: Already exists / Data missing
        Webhook->>Webhook: Log and exit
    end
Loading

Possibly related PRs

  • 💸 Create abstraction for handling pricing #1215: The changes in the main PR, which enhance the checkout session creation process in Stripe, are related to the retrieved PR that focuses on creating an abstraction for handling pricing, as both involve modifications to the pricing logic and session management within the Stripe API.
  • ♻️ Make user session optional #1515: The changes in the main PR related to the Stripe checkout session creation process are directly connected to the modifications in the retrieved PR, which also involve handling user sessions, specifically through the introduction of optional chaining for user session checks in the Stripe API routes.

Poem

Oh, how I hop with glee today,
In sessions new and emails that convey,
My stripes align in Stripe and code,
Abandoned checkouts light my abode.
With promos, previews, a signature so neat,
This bunny sings in every beat!
🐰✨


📜 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 8f0ffa1 and 11fbaf1.

📒 Files selected for processing (2)
  • packages/emails/locales/en/emails.json (1 hunks)
  • packages/emails/src/templates/abandoned-checkout.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/emails/src/templates/abandoned-checkout.tsx
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Unit tests
  • GitHub Check: Linting
  • GitHub Check: Type check
  • GitHub Check: Integration tests
🔇 Additional comments (2)
packages/emails/locales/en/emails.json (2)

56-56: Ensure Consistency in Changed Email Request Text

The updated "changeEmailRequest_text1" retains the same content but now uses explicit HTML bold tags for the email addresses. Please confirm this formatting change is intentional and aligns with your email template expectations.


57-65: Review New Abandoned Checkout Localization Keys

The new abandoned checkout entries (lines 57–65) are clearly defined and consistent in style. They include personalized greetings, content, offer details, button text, support information, a preview, subject, and sign-off. Ensure that these keys are referenced correctly in the AbandonedCheckoutEmail template and that any HTML markup within the strings is safely rendered.


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

@lukevella lukevella changed the title 📈 Send recovery url to users with expired checkout sessions ✨ Send recovery url to users with expired checkout sessions Feb 9, 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: 1

🧹 Nitpick comments (6)
packages/billing/src/scripts/checkout-expirey.ts (1)

1-40: Fix typo in filename: "expirey" should be "expiry".

The filename contains a spelling error. Rename the file from checkout-expirey.ts to checkout-expiry.ts to maintain correct spelling.

packages/emails/src/templates/abandoned-checkout.tsx (1)

82-82: Consider making the promotion code configurable.

The promotion code "GETPRO1Y20" is hardcoded. Consider making it a prop to allow for dynamic promotion codes and A/B testing.

-          GETPRO1Y20
+          {props.promoCode}
packages/emails/src/components/styled-components.tsx (1)

154-182: Consider making the Signature component more configurable.

The component has hardcoded values that might need to change:

  1. Image URL is hardcoded to a specific CDN path
  2. Name and title are hardcoded
  3. Image dimensions are fixed

Consider making these configurable through props for better reusability.

-export const Signature = () => {
+export const Signature = ({
+  name = "Luke Vella",
+  title = "Founder",
+  imageUrl = "https://d39ixtfgglw55o.cloudfront.net/images/luke.jpg",
+  imageSize = 48,
+}: {
+  name?: string;
+  title?: string;
+  imageUrl?: string;
+  imageSize?: number;
+}) => {
   return (
     <Section>
       <UnstyledText
         style={{
           fontSize: 16,
           margin: 0,
           fontWeight: "bold",
           color: darkTextColor,
           fontFamily,
         }}
       >
-        Luke Vella
+        {name}
       </UnstyledText>
       <UnstyledText
         style={{ fontSize: 16, margin: 0, color: lightTextColor, fontFamily }}
       >
-        Founder
+        {title}
       </UnstyledText>
       <img
-        src="https://d39ixtfgglw55o.cloudfront.net/images/luke.jpg"
-        alt="Luke Vella"
+        src={imageUrl}
+        alt={name}
         style={{ borderRadius: "50%", marginTop: 16 }}
-        width={48}
-        height={48}
+        width={imageSize}
+        height={imageSize}
       />
     </Section>
   );
 };
apps/web/src/app/api/stripe/webhook/route.ts (1)

212-232: Enhance error messages for better debugging

The error handling is good, but the messages could be more descriptive by including the session ID.

-        console.info("No user ID found in Checkout Session metadata");
-        Sentry.captureMessage("No user ID found in Checkout Session metadata");
+        console.info(`No user ID found in Checkout Session metadata (session: ${session.id})`);
+        Sentry.captureMessage(`No user ID found in Checkout Session metadata (session: ${session.id})`);

-        console.info("No email or recovery URL found in Checkout Session");
-        Sentry.captureMessage(
-          "No email or recovery URL found in Checkout Session",
-        );
+        console.info(`No email or recovery URL found in Checkout Session (session: ${session.id})`);
+        Sentry.captureMessage(
+          `No email or recovery URL found in Checkout Session (session: ${session.id})`,
+        );
packages/billing/package.json (1)

11-11: Fix typo in script name

The script name contains a typo: "expirey" should be "expiry".

-    "checkout-expirey": "dotenv -e ../../.env -- tsx ./src/scripts/checkout-expirey.ts",
+    "checkout-expiry": "dotenv -e ../../.env -- tsx ./src/scripts/checkout-expiry.ts",

Note: This change will require renaming the script file as well.

packages/emails/locales/en/emails.json (1)

60-60: Parameterize the discount percentage

The discount percentage is hardcoded in the string. Consider making it dynamic to allow for different promotional offers.

-  "abandoned_checkout_offer": "To help you get started, you can get <b>20% off</b> your first year. Just use the code below when you check out:",
+  "abandoned_checkout_offer": "To help you get started, you can get <b>{{discountPercentage}}% off</b> your first year. Just use the code below when you check out:",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5437b91 and 822ece7.

📒 Files selected for processing (11)
  • apps/web/src/app/api/stripe/checkout/route.ts (1 hunks)
  • apps/web/src/app/api/stripe/webhook/route.ts (2 hunks)
  • packages/billing/package.json (1 hunks)
  • packages/billing/src/scripts/checkout-expirey.ts (1 hunks)
  • packages/emails/locales/en/emails.json (1 hunks)
  • packages/emails/src/components/email-layout.tsx (3 hunks)
  • packages/emails/src/components/styled-components.tsx (2 hunks)
  • packages/emails/src/previews/abandoned-checkout.tsx (1 hunks)
  • packages/emails/src/send-email.tsx (2 hunks)
  • packages/emails/src/templates.ts (2 hunks)
  • packages/emails/src/templates/abandoned-checkout.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Unit tests
  • GitHub Check: Integration tests
  • GitHub Check: Type check
  • GitHub Check: Linting
🔇 Additional comments (10)
packages/emails/src/previews/abandoned-checkout.tsx (1)

1-12: LGTM!

The preview component is well-structured and follows the established pattern for email previews. The hardcoded values are appropriate for preview purposes.

packages/emails/src/templates.ts (1)

1-1: LGTM!

The AbandonedCheckoutEmail template is correctly imported and added to the templates object, maintaining the file's structure and organization.

Also applies to: 23-23

packages/billing/src/scripts/checkout-expirey.ts (2)

7-19: Verify hardcoded values are for development only.

The script contains hardcoded values that should only be used in development:

Please ensure this script is not used in production.


20-26: LGTM!

The expiration and recovery configuration is well-structured:

  • 30-minute expiration window
  • Recovery enabled with promotion codes
packages/emails/src/components/email-layout.tsx (1)

18-18: LGTM!

The changes are well-implemented:

  • Optional poweredBy prop with default value maintains backward compatibility
  • Conditional rendering of the "Powered by" section is correct
  • UTM parameters in the link help track email sources

Also applies to: 34-34, 53-71

apps/web/src/app/api/stripe/checkout/route.ts (1)

106-112: LGTM! Good implementation of checkout session expiration and recovery.

The 30-minute expiration window and recovery options are well-configured, following Stripe's recommended patterns for abandoned checkout recovery.

packages/emails/src/templates/abandoned-checkout.tsx (1)

1-134: Add tests for the email template.

Consider adding tests to verify the template renders correctly with different props combinations (with/without name, different URLs, etc.).

Would you like me to help create a test suite for this component?

packages/emails/src/send-email.tsx (1)

13-21: LGTM! Good implementation of customizable sender details.

The changes properly implement optional sender customization while maintaining type safety and backward compatibility.

Also applies to: 113-113

apps/web/src/app/api/stripe/webhook/route.ts (1)

7-7: LGTM!

The new imports are correctly added and used appropriately in the new handler.

Also applies to: 12-12

packages/emails/locales/en/emails.json (1)

57-65: LGTM!

The email content is well-structured, personalized, and follows the established pattern of other email templates.

apps/web/src/app/api/stripe/webhook/route.ts Show resolved Hide resolved
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)
packages/billing/src/scripts/checkout-expiry.ts (1)

39-39: Add error handling for the script execution.

The script should handle potential errors that might occur during execution.

-createAndExpireCheckout();
+createAndExpireCheckout()
+  .catch((error) => {
+    console.error("❌ Error:", error.message);
+    process.exit(1);
+  });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 822ece7 and caa294a.

📒 Files selected for processing (2)
  • packages/billing/package.json (1 hunks)
  • packages/billing/src/scripts/checkout-expiry.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/billing/package.json
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Unit tests
  • GitHub Check: Integration tests
  • GitHub Check: Linting
  • GitHub Check: Type check
🔇 Additional comments (3)
packages/billing/src/scripts/checkout-expiry.ts (3)

1-3: LGTM! Clear imports and function naming.

The imports provide the necessary Stripe functionality, and the function name clearly describes its purpose.


20-26: LGTM! Well-configured expiration and recovery settings.

The expiration time is correctly set to 30 minutes, and the recovery options are properly configured to support the PR's objective of sending recovery URLs to users with expired sessions.


29-37: LGTM! Comprehensive logging and proper session expiration.

The code provides helpful debug information and correctly handles session expiration.

@vercel vercel bot temporarily deployed to Preview – landing February 10, 2025 05:51 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: 0

🧹 Nitpick comments (4)
packages/emails/src/templates/abandoned-checkout.tsx (3)

20-27: Consider enhancing the preview text for better engagement.

The current preview text "Upgrade to Rallly Pro to get more features and support" could be more engaging. Consider mentioning the 20% discount to increase open rates.

       preview={ctx.t("abandoned_checkout_preview", {
-        defaultValue: "Upgrade to Rallly Pro to get more features and support.",
+        defaultValue: "Exclusive offer: Get 20% off your first year of Rallly Pro!",
         ns: "emails",
       })}

77-98: Consider making the discount code configurable.

The discount code "GETPRO1Y20" is hardcoded. Consider making it a prop to allow for dynamic discount codes and A/B testing.

interface AbandonedCheckoutEmailProps {
  recoveryUrl: string;
  name?: string;
  ctx: EmailContext;
+ discountCode?: string;
}

// In the component:
-            GETPRO1Y20
+            {props.discountCode ?? "GETPRO1Y20"}

126-134: Consider enhancing the subject line for better open rates.

The current subject line could be more engaging by mentioning the 20% discount.

   return ctx.t("abandoned_checkout_subject", {
-    defaultValue: "A special offer for Rallly Pro",
+    defaultValue: "🎉 Exclusive: 20% off your first year of Rallly Pro",
     ns: "emails",
   });
packages/emails/src/components/styled-components.tsx (1)

155-183: Consider making the signature configurable.

The signature component has hardcoded values for name, title, and image URL. Consider making these configurable to:

  1. Support different signers
  2. Allow for environment-specific image URLs
+ interface SignatureProps {
+   name: string;
+   title: string;
+   imageUrl: string;
+ }

- export const Signature = () => {
+ export const Signature = ({ name, title, imageUrl }: SignatureProps) => {
   return (
     <Section>
       <UnstyledText
         style={{
           fontSize: 16,
           margin: 0,
           fontWeight: "bold",
           color: darkTextColor,
           fontFamily,
         }}
       >
-        Luke Vella
+        {name}
       </UnstyledText>
       <UnstyledText
         style={{ fontSize: 16, margin: 0, color: lightTextColor, fontFamily }}
       >
-        Founder
+        {title}
       </UnstyledText>
       <img
-        src="https://d39ixtfgglw55o.cloudfront.net/images/luke.jpg"
-        alt="Luke Vella"
+        src={imageUrl}
+        alt={name}
         style={{ borderRadius: "50%", marginTop: 16 }}
         width={48}
         height={48}
       />
     </Section>
   );
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between caa294a and 8f0ffa1.

📒 Files selected for processing (5)
  • apps/web/src/utils/emails.ts (1 hunks)
  • packages/emails/locales/en/emails.json (1 hunks)
  • packages/emails/src/components/email-context.tsx (1 hunks)
  • packages/emails/src/components/styled-components.tsx (3 hunks)
  • packages/emails/src/templates/abandoned-checkout.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/emails/src/components/email-context.tsx
  • apps/web/src/utils/emails.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/emails/locales/en/emails.json
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Unit tests
  • GitHub Check: Integration tests
  • GitHub Check: Type check
  • GitHub Check: Linting
🔇 Additional comments (3)
packages/emails/src/templates/abandoned-checkout.tsx (2)

8-18: LGTM!

Props interface is well-defined with appropriate types and optionality.


28-49: LGTM!

The personalization logic is well-implemented with proper i18n support for both named and anonymous greetings.

packages/emails/src/components/styled-components.tsx (1)

52-52: LGTM!

The button styling changes improve visual hierarchy with a more compact and prominent appearance.

Also applies to: 59-60

@vercel vercel bot temporarily deployed to Preview – landing February 10, 2025 06:11 Inactive
@lukevella lukevella enabled auto-merge (squash) February 10, 2025 06:11
@lukevella lukevella merged commit 9fdd5f3 into main Feb 10, 2025
10 checks passed
@lukevella lukevella deleted the abandoned-cart branch February 10, 2025 06:37
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