Skip to content

Feat/spree checkout#8

Merged
willymwai merged 28 commits intomasterfrom
feat/spree-checkout
Jan 18, 2025
Merged

Feat/spree checkout#8
willymwai merged 28 commits intomasterfrom
feat/spree-checkout

Conversation

@willymwai
Copy link
Member

@willymwai willymwai commented Jan 18, 2025

PR Type

Enhancement, Bug fix


Description

  • Introduced a comprehensive checkout integration for Spree commerce.

    • Added use-checkout and use-submit-checkout hooks.
    • Implemented checkout submission logic with address and payment handling.
    • Enhanced address fields validation and added support for onSuccessAction.
  • Refactored cart handling by centralizing cart-fetching logic into get-cart.

  • Added new types for cart, checkout, customer, and common utilities.

  • Updated package dependencies and bumped commerce-spree version to 0.1.0.


Changes walkthrough 📝

Relevant files
Enhancement
26 files
use-cart.tsx
Refactored cart fetching logic to use `get-cart`                 
+3/-71   
use-checkout.tsx
Added `use-checkout` hook for checkout data                           
+60/-0   
use-submit-checkout.tsx
Added `use-submit-checkout` hook for checkout submission 
+80/-0   
use-checkout.ts
Defined `useCheckout` hook for checkout handling                 
+34/-0   
use-submit-checkout.tsx
Defined `useSubmitCheckout` hook for checkout submission 
+23/-0   
index.tsx
Added core commerce provider for Spree                                     
+74/-0   
cart.ts
Added comprehensive cart-related types                                     
+265/-0 
checkout.ts
Added checkout-related types and handlers                               
+114/-0 
common.ts
Added common utility types for commerce                                   
+36/-0   
address.ts
Added types for customer address handling                               
+130/-0 
card.ts
Added types for customer card handling                                     
+138/-0 
index.ts
Added customer-related types and exports                                 
+54/-0   
index.ts
Exported all commerce-related types                                           
+5/-0     
default-fetcher.ts
Added default fetcher utilities for hooks                               
+12/-0   
define-property.ts
Added utility for defining object properties                         
+37/-0   
types.ts
Added utility types for commerce hooks                                     
+153/-0 
use-data.tsx
Added `useData` utility for SWR integration                           
+86/-0   
use-hook.ts
Added `useHook` utility for commerce hooks                             
+68/-0   
index.tsx
Updated exports and added checkout provider registration 
+9/-10   
provider.ts
Integrated checkout hooks into Spree provider                       
+7/-0     
registerCheckoutProvider.tsx
Added checkout provider registration and global actions   
+213/-0 
registerCommerceProvider.tsx
Updated commerce provider to include checkout actions       
+25/-22 
spree.tsx
Updated Spree provider exports and imports                             
+2/-5     
get-cart.ts
Centralized cart fetching logic                                                   
+80/-0   
submit-checkout.ts
Added utility for checkout submission                                       
+149/-0 
types.ts
Added utility types for commerce operations                           
+153/-0 
Dependencies
4 files
package.json
Bumped package version to 0.1.0 and added dependencies     
+2/-1     
package.json
Updated `commerce-spree` dependency to 0.1.0                         
+1/-1     
package.json
Updated `commerce-spree` dependency to 0.1.0                         
+1/-1     
package.json
Updated `commerce-spree` dependency to 0.1.0                         
+1/-1     
Bug fix
1 files
@plasmicpkgs+commerce+0.0.205.patch
Added patch for `@plasmicpkgs/commerce` to support checkout
+40/-0   

Need help?
  • Type /help how to ... in the comments thread for any question about Qodo Merge usage.
  • Check out the documentation for more information.
  • @willymwai willymwai self-assigned this Jan 18, 2025
    @qodo-code-review
    Copy link

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 No relevant tests
    🔒 Security concerns

    Sensitive information exposure:
    The checkout submission process handles sensitive data like email, addresses and payment details. While the code doesn't directly expose this information, it should be verified that all communication with the API is done over HTTPS and that sensitive data is not being logged in the console.info statements (lines 18-26 in use-submit-checkout.tsx).

    ⚡ Recommended focus areas for review

    Input Validation

    The validation logic only checks if any field exists, but does not validate the content/format of email, addresses, or payment details. This could lead to invalid data being submitted.

    if (
      !email &&
      !special_instructions &&
      !billing_address &&
      !shipping_address &&
      !payments
    ) {
      throw new ValidationError({
        message:
          'email or special_instructions or billing_address or shipping_address or payments needs to be provided.',
      })
    }
    Error Handling

    The error handling for payment processing and checkout submission could be more robust. Currently it only handles 404 errors specifically but other error cases should be handled gracefully.

    } catch (updateItemError) {
      if (
        updateItemError instanceof FetcherError &&
        updateItemError.status === 404
      ) {
        const { data: spreeRetroactiveCartCreateSuccessResponse } =
          await createEmptyCart(fetch)
    
        if (!isLoggedIn()) {
          setCartToken(
            spreeRetroactiveCartCreateSuccessResponse.data.attributes.token
          )
        }
    
        // Return an empty cart. The user has to update the item again.
        // This is going to be a rare situation.
    
        spreeCartResponse = spreeRetroactiveCartCreateSuccessResponse
      }
    
      throw updateItemError
    }
    State Management

    The cart token management logic could lead to race conditions when multiple cart operations happen simultaneously. Consider adding synchronization or locking mechanisms.

    if (!spreeCartResponse || spreeCartResponse?.data.attributes.completed_at) {
      const { data: spreeCartCreateSuccessResponse } = await createEmptyCart(
        fetch
      )
    
      spreeCartResponse = spreeCartCreateSuccessResponse
    
      if (!isLoggedIn()) {
        setCartToken(spreeCartResponse.data.attributes.token)
      }
    }
    return spreeCartResponse

    @qodo-code-review
    Copy link

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    Possible issue
    Add validation for required address fields in checkout submission to prevent incomplete orders

    Add input validation for billing_address and shipping_address fields since they are
    critical for order processing. These fields should be required and validated before
    proceeding with the checkout.

    platform/canvas-packages/internal_pkgs/spree/src/utils/submit-checkout.ts [50-55]

     if (!email) {
       throw new ValidationError({
         message: 'email needs to be provided.',
       })
     }
    +if (!billing_address || !shipping_address) {
    +  throw new ValidationError({
    +    message: 'Billing and shipping addresses need to be provided.',
    +  })
    +}
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: The suggestion adds critical validation for billing and shipping addresses which are essential for order processing. Missing address validation could lead to failed orders or shipping issues.

    8
    Add error handling for cart creation failure to prevent unhandled exceptions

    Add error handling for the case when createEmptyCart fails. Currently if cart
    creation fails, the error is not caught and handled properly.

    platform/canvas-packages/internal_pkgs/spree/src/utils/get-cart.ts [67-69]

    -const { data: spreeCartCreateSuccessResponse } = await createEmptyCart(
    -  fetch
    -)
    +try {
    +  const { data: spreeCartCreateSuccessResponse } = await createEmptyCart(fetch)
    +  spreeCartResponse = spreeCartCreateSuccessResponse
    +} catch (error) {
    +  console.error('Failed to create empty cart:', error)
    +  throw new Error('Unable to create new shopping cart')
    +}
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: The suggestion addresses a critical error handling gap that could lead to unhandled exceptions and poor user experience when cart creation fails. Adding proper error handling is essential for system stability.

    8
    Improve type safety by making payment-related fields more strictly typed to prevent inconsistent states

    The cardId field in the Checkout interface is marked as optional but hasPayment is
    required - this could lead to inconsistent states where hasPayment is true but no
    cardId exists. Consider making cardId required if hasPayment is true.

    platform/canvas-packages/internal_pkgs/spree/src/commerce/types/checkout.ts [8-25]

     export interface Checkout {
       hasPayment: boolean
    -  cardId?: string
    +  cardId: string | null
     }
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: The suggestion improves type safety by making cardId explicitly nullable, preventing potential runtime errors from inconsistent payment states. This makes the code more maintainable and less error-prone.

    7
    Strengthen input validation for required checkout fields to prevent incomplete submissions

    Add input validation for payment information before submission to prevent invalid
    checkout attempts.

    platform/canvas-packages/internal_pkgs/spree/src/checkout/use-submit-checkout.tsx [48-54]

    -if (
    -  !email &&
    -  !special_instructions &&
    -  !billing_address &&
    -  !shipping_address &&
    -  !payments
    -) {
    +if (!email || !billing_address || !shipping_address || !payments) {
    +  throw new ValidationError({
    +    message: 'Email, billing address, shipping address and payment information are required for checkout.',
    +  })
    +}
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: The suggestion improves the validation logic by making email, billing address, shipping address and payments mandatory fields, which helps prevent invalid checkout attempts and provides clearer error messages.

    7

    @willymwai willymwai merged commit 6ea4c28 into master Jan 18, 2025
    1 check passed
    @willymwai willymwai deleted the feat/spree-checkout branch January 18, 2025 07:04
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    1 participant