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

chore: checkout rework #321

Merged
merged 1 commit into from
Feb 24, 2025
Merged

chore: checkout rework #321

merged 1 commit into from
Feb 24, 2025

Conversation

hmbanan666
Copy link
Contributor

@hmbanan666 hmbanan666 commented Feb 24, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a visual loading indicator for a smoother experience.
    • Enhanced cart and checkout interactions for faster, more responsive order processing.
  • Bug Fixes

    • Adjusted cart drawer layering and button behavior for improved display consistency.
    • Updated validations and conditional rendering on product and category pages to prevent UI issues.
  • Style

    • Refined button and form designs for a cleaner, more intuitive interface.
  • Refactor

    • Simplified state management across the catalog, cart, and checkout for more reliable performance.

Copy link

coderabbitai bot commented Feb 24, 2025

Walkthrough

This pull request introduces significant updates to state management by shifting from legacy composables to a centralized checkout store. Multiple components and pages now use useCheckoutStore() to access and update checkout state, and product as well as variant data are refactored to utilize the channel store. Legacy composables such as useCheckout, useCommandCenter, and useTime have been removed. Additional changes include UI adjustments, improved error handling in API endpoints via channel updates, and updates to type definitions for checkout lines.

Changes

Files Change Summary
apps/web-app/app/app.vue, .../components/Cart/Button.vue, .../components/Cart/DeliveryMethodSwitch.vue, .../components/Cart/Line.vue, .../components/Cart/LineCounter.vue, .../components/Cart/index.vue, .../components/DeliveryInfoBlock.vue, .../components/Modal/DeliveryInfo.vue, .../components/Navigation/Main.vue, .../pages/catalog/[categorySlug]/[productSlug]/index.vue, .../pages/checkout/index.vue Replaced legacy useCheckout() with useCheckoutStore(), streamlining checkout state access and conditional rendering across components and pages.
apps/web-app/app/components/Checkout/Line.vue, .../components/Form/UpdateProductVariant.vue, .../components/Modal/UpdateProductVariant.vue Refactored product and variant data access to use the channel store directly and removed redundant productId props.
apps/web-app/app/components/Cart/Drawer.vue, .../components/Cart/Button.vue Adjusted styling – increased z-index in Drawer and updated CSS variable usage in Button.
apps/web-app/app/components/Form/UpdateMenuCategory.vue, .../pages/catalog/[categorySlug]/index.vue, .../pages/command-center/menu/[id]/index.vue Updated property access to utilize optional chaining and reactive references (e.g., category.value, menu.value) for safer data retrieval.
apps/web-app/app/composables/useApp.ts, apps/web-app/app/composables/useCheckout.ts, apps/web-app/app/composables/useCommandCenter.ts, apps/web-app/app/composables/useTime.ts Simplified composable exports and removed legacy composables in favor of centralized store implementations.
apps/web-app/stores/channel.ts Enhanced channel store by modifying methods to return ComputedRefs and adding new functions getTimeSlots and getProductVariant for reactive data fetching.
apps/web-app/stores/checkout.ts Introduced a new checkout store with reactive state variables, computed properties, and asynchronous methods (update, add, change, changeLineQuantity) for robust checkout management.
packages/core/server/api/category/[id]/index.patch.ts, packages/core/server/api/category/index.post.ts Added extraction of channelId from runtime config and updated repository calls to record channel updates post category patch or creation.
packages/core/types/index.d.ts Updated the CheckoutLine interface by changing date types to strings, rearranging properties, and incorporating a new totalPrice field.
apps/web-app/app/pages/command-center/product/[id]/index.vue Removed redundant productId parameter from the variant click event, focusing solely on productVariantId for modal interactions.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant UI
  participant CheckoutStore
  participant API

  User->>UI: Click "Add to Cart"
  UI->>CheckoutStore: Invoke add(productVariantId)
  CheckoutStore->>API: POST /api/checkout/add
  API-->>CheckoutStore: Return updated checkout data
  CheckoutStore->>UI: Update reactive checkout state
Loading

Possibly related PRs

Poem

I'm a bunny in the code, so spry,
Hopping through changes, oh my, oh my!
From old composables I have leapt away,
To a checkout store that lights the way.
With each line of code, my joy does grow –
A rabbit’s delight in the code's warm glow!
🐇💻 Happy hopping in every row!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

@hmbanan666 hmbanan666 self-assigned this Feb 24, 2025
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: 4

🔭 Outside diff range comments (3)
apps/web-app/app/components/Form/UpdateProductVariant.vue (2)

124-134: 🛠️ Refactor suggestion

Add error handling for variant fetching.

The direct variant fetching is more efficient, but there's no handling for cases where the variant might not exist.

Consider adding error handling:

 const channel = useChannelStore()
-const productVariant = channel.getProductVariant(productVariantId)
+const productVariant = channel.getProductVariant(productVariantId)
+if (!productVariant.value) {
+  throw new Error(`Product variant with ID ${productVariantId} not found`)
+}

171-193: 🛠️ Refactor suggestion

Improve error message handling.

The error message is hardcoded as '...' instead of using the actual error details.

Consider using the actual error message:

 if (error.value) {
   console.error(error.value)
-  toast.add({ title: t('error.title'), description: '...' })
+  toast.add({
+    title: t('error.title'),
+    description: error.value?.message || t('error.unknown')
+  })
 }
apps/web-app/app/components/DeliveryInfoBlock.vue (1)

9-9: 💡 Verification agent

🧩 Analysis chain

Verify null safety approach for checkout object.

There's an inconsistency in null safety handling:

  • Template uses optional chaining: checkout?.deliveryMethod
  • Computed property accesses directly: checkout.deliveryMethod

Please verify if useCheckoutStore() guarantees a non-null checkout object. If it does, we can remove the optional chaining from the template. If not, we should add optional chaining to the computed property.

Also applies to: 24-24


🏁 Script executed:

#!/bin/bash
# Description: Check if useCheckoutStore() guarantees non-null checkout object

# Search for useCheckoutStore implementation
ast-grep --pattern $'export const useCheckoutStore = defineStore($_, {
  $$$
})'

# Search for null checks in components using useCheckoutStore
rg -A 5 'checkout\?' 'apps/web-app'

Length of output: 14284


Fix null safety inconsistency for checkout usage.

There’s a discrepancy between the computed property (line 24) and the template (line 9) in how checkout.deliveryMethod is accessed:

  • The template uses optional chaining (checkout?.deliveryMethod).
  • The computed property accesses it directly (checkout.deliveryMethod).

Since multiple components (e.g., in CheckoutCard.vue and others) consistently use optional chaining, it appears that a missing safeguard might lead to runtime errors. Please verify whether useCheckoutStore() guarantees a non-null checkout object. If it does not, update the computed property to use optional chaining for consistency; otherwise, remove the optional chaining in the template.

🧹 Nitpick comments (11)
apps/web-app/app/components/Form/UpdateProductVariant.vue (1)

149-169: Reduce code duplication in state initialization.

The state initialization logic is duplicated between the initial state and the reset function.

Consider extracting the state initialization to a reusable function:

+function getInitialState(): Partial<ProductVariantUpdateSchema> {
+  return {
+    name: productVariant.value?.name,
+    weightUnit: productVariant.value?.weightUnit as ProductVariantUpdateSchema['weightUnit'],
+    weightValue: productVariant.value?.weightValue,
+    gross: productVariant.value?.gross,
+    net: productVariant.value?.net ?? undefined,
+    sku: productVariant.value?.sku ?? undefined,
+    calories: productVariant.value?.calories ?? undefined,
+    carbohydrate: productVariant.value?.carbohydrate ?? undefined,
+    protein: productVariant.value?.protein ?? undefined,
+    fat: productVariant.value?.fat ?? undefined,
+  }
+}
+
-const state = ref<Partial<ProductVariantUpdateSchema>>({
-  name: productVariant.value?.name,
-  weightUnit: productVariant.value?.weightUnit as ProductVariantUpdateSchema['weightUnit'],
-  weightValue: productVariant.value?.weightValue,
-  gross: productVariant.value?.gross,
-  net: productVariant.value?.net ?? undefined,
-  sku: productVariant.value?.sku ?? undefined,
-  calories: productVariant.value?.calories ?? undefined,
-  carbohydrate: productVariant.value?.carbohydrate ?? undefined,
-  protein: productVariant.value?.protein ?? undefined,
-  fat: productVariant.value?.fat ?? undefined,
-})
+const state = ref<Partial<ProductVariantUpdateSchema>>(getInitialState())

 function resetState() {
-  state.value = {
-    name: productVariant.value?.name,
-    weightUnit: productVariant.value?.weightUnit as ProductVariantUpdateSchema['weightUnit'],
-    weightValue: productVariant.value?.weightValue,
-    gross: productVariant.value?.gross,
-    net: productVariant.value?.net ?? undefined,
-    sku: productVariant.value?.sku ?? undefined,
-    calories: productVariant.value?.calories ?? undefined,
-    carbohydrate: productVariant.value?.carbohydrate ?? undefined,
-    protein: productVariant.value?.protein ?? undefined,
-    fat: productVariant.value?.fat ?? undefined,
-  }
+  state.value = getInitialState()
 }
apps/web-app/app/pages/catalog/[categorySlug]/[productSlug]/index.vue (1)

133-135: Consider adding null check for checkout.lines.

The computed property should handle potential undefined lines array.

-return checkout.lines.find((l) => l.productVariantId === selectedVariant.value?.id)
+return checkout.lines?.find((l) => l.productVariantId === selectedVariant.value?.id)
apps/web-app/app/pages/catalog/[categorySlug]/index.vue (1)

32-32: Consider adding a default title for SEO.

While the null safety is good, having an empty title might not be ideal for SEO. Consider adding a default title when the category name is undefined.

-  title: category.value?.name,
+  title: category.value?.name ?? t('app.default-category-title'),

Also applies to: 37-37

apps/web-app/stores/checkout.ts (1)

13-31: Enhance error handling in the update function.

While the function handles basic error cases, it silently returns without notifying the user of failures.

 async function update() {
   const { data, error } = await useFetch('/api/checkout', {
     lazy: true,
     server: true,
     cache: 'no-cache',
     getCachedData: undefined,
   })
   if (!data.value || error.value) {
+    console.error('Failed to update checkout:', error.value)
+    throw createError({
+      statusCode: error.value?.statusCode ?? 500,
+      message: error.value?.message ?? 'Failed to update checkout',
+    })
     return
   }
apps/web-app/app/components/Checkout/Line.vue (2)

48-49: Add error handling to the total amount calculation.

The total amount calculation could fail if productVariant.value is undefined. Consider adding a null check or default value.

-const totalAmount = computed(() => formatNumberToLocal(productVariant.value?.gross ? productVariant.value?.gross * line.quantity : 0))
+const totalAmount = computed(() => {
+  const gross = productVariant.value?.gross ?? 0
+  return formatNumberToLocal(gross * line.quantity)
+})

46-47: Simplify the product URL computation.

The product URL computation can be simplified by using optional chaining.

-const productUrl = computed(() => `/catalog/${product.value?.category?.slug}/${product.value?.slug}`)
+const productUrl = computed(() => `/catalog/${product.value?.category?.slug ?? ''}/${product.value?.slug ?? ''}`)
apps/web-app/app/components/Cart/Line.vue (1)

15-15: Add error handling to the price formatting.

The price formatting could fail if productVariant?.gross is undefined.

-{{ formatNumberToLocal(productVariant?.gross) }} <span class="text-xs">{{ channel.currencySign }}</span>
+{{ formatNumberToLocal(productVariant?.gross ?? 0) }} <span class="text-xs">{{ channel.currencySign }}</span>
apps/web-app/app/pages/checkout/index.vue (2)

246-246: Fix type annotation spacing per ESLint.

Add spaces around type operators to comply with style guidelines.

-const remainingCheckout = ref<CheckoutDraft>({
+const remainingCheckout = ref< CheckoutDraft >({

-const isOkForAmount = computed<boolean>(() =>
+const isOkForAmount = computed< boolean >(() =>

Also applies to: 262-263

🧰 Tools
🪛 ESLint

[error] 246-246: Operator '<' must be spaced.

(style/space-infix-ops)


[error] 246-246: Operator '>' must be spaced.

(style/space-infix-ops)


268-281: Consider debouncing phone validation.

The phone validation runs on every character input, which might be excessive. Consider debouncing the validation.

+const debouncedValidatePhone = useDebounceFn(() => {
+  if (!remainingCheckout.value.phone) {
+    return
+  }
+  if (remainingCheckout.value.phone.length > 17) {
+    return
+  }
+
+  getPhoneNumberFormatter(channel.countryCode).input(remainingCheckout.value.phone)
+  isValidPhone.value = checkPhoneNumberValidity(remainingCheckout.value.phone, channel.countryCode)
+}, 300)

 watch(
   () => remainingCheckout.value.phone,
-  () => {
-    if (!remainingCheckout.value.phone) {
-      return
-    }
-    if (remainingCheckout.value.phone.length > 17) {
-      return
-    }
-
-    getPhoneNumberFormatter(channel.countryCode).input(remainingCheckout.value.phone)
-    isValidPhone.value = checkPhoneNumberValidity(remainingCheckout.value.phone, channel.countryCode)
-  },
+  debouncedValidatePhone,
 )
apps/web-app/stores/channel.ts (2)

75-87: Add type information and improve error handling.

The function implementation looks good but could benefit from the following improvements:

  1. Add explicit return type for better type safety
  2. Make the error message more descriptive
  3. Add specific error handling for different failure scenarios
-  async function getTimeSlots() {
+  async function getTimeSlots(): Promise<TimeSlot[]> {
     const { data } = await useFetch('/api/channel/time-slots', {
       lazy: true,
       server: true,
       cache: 'no-cache',
       getCachedData: undefined,
     })
     if (!data.value) {
-      throw new Error('Time slots not found')
+      throw new Error('Failed to fetch time slots from the channel API')
     }

     return data.value
   }

106-108: Consider caching flattened variants for better performance.

While the implementation is correct, flattening the variants array on every computation could be expensive with large datasets. Consider caching the flattened variants in a computed property.

+  const allVariants = computed(() => allProducts.value.flatMap((product) => product.variants))
+
   function getProductVariant(id: string): ComputedRef<ProductVariant | undefined> {
-    return computed(() => allProducts.value.flatMap((product) => product.variants).find((variant) => variant.id === id))
+    return computed(() => allVariants.value.find((variant) => variant.id === id))
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 15d22f9 and d120049.

📒 Files selected for processing (28)
  • apps/web-app/app/app.vue (2 hunks)
  • apps/web-app/app/components/Cart/Button.vue (1 hunks)
  • apps/web-app/app/components/Cart/DeliveryMethodSwitch.vue (1 hunks)
  • apps/web-app/app/components/Cart/Drawer.vue (1 hunks)
  • apps/web-app/app/components/Cart/Line.vue (2 hunks)
  • apps/web-app/app/components/Cart/LineCounter.vue (3 hunks)
  • apps/web-app/app/components/Cart/index.vue (1 hunks)
  • apps/web-app/app/components/Checkout/Line.vue (2 hunks)
  • apps/web-app/app/components/DeliveryInfoBlock.vue (1 hunks)
  • apps/web-app/app/components/Form/UpdateMenuCategory.vue (1 hunks)
  • apps/web-app/app/components/Form/UpdateProductVariant.vue (2 hunks)
  • apps/web-app/app/components/Modal/DeliveryInfo.vue (1 hunks)
  • apps/web-app/app/components/Modal/UpdateProductVariant.vue (0 hunks)
  • apps/web-app/app/components/Navigation/Main.vue (1 hunks)
  • apps/web-app/app/composables/useApp.ts (1 hunks)
  • apps/web-app/app/composables/useCheckout.ts (0 hunks)
  • apps/web-app/app/composables/useCommandCenter.ts (0 hunks)
  • apps/web-app/app/composables/useTime.ts (0 hunks)
  • apps/web-app/app/pages/catalog/[categorySlug]/[productSlug]/index.vue (3 hunks)
  • apps/web-app/app/pages/catalog/[categorySlug]/index.vue (2 hunks)
  • apps/web-app/app/pages/checkout/index.vue (3 hunks)
  • apps/web-app/app/pages/command-center/menu/[id]/index.vue (1 hunks)
  • apps/web-app/app/pages/command-center/product/[id]/index.vue (1 hunks)
  • apps/web-app/stores/channel.ts (2 hunks)
  • apps/web-app/stores/checkout.ts (1 hunks)
  • packages/core/server/api/category/[id]/index.patch.ts (2 hunks)
  • packages/core/server/api/category/index.post.ts (2 hunks)
  • packages/core/types/index.d.ts (1 hunks)
💤 Files with no reviewable changes (4)
  • apps/web-app/app/composables/useTime.ts
  • apps/web-app/app/components/Modal/UpdateProductVariant.vue
  • apps/web-app/app/composables/useCommandCenter.ts
  • apps/web-app/app/composables/useCheckout.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/web-app/app/components/Cart/Drawer.vue
🧰 Additional context used
🪛 ESLint
apps/web-app/app/pages/checkout/index.vue

[error] 246-246: Operator '<' must be spaced.

(style/space-infix-ops)


[error] 246-246: Operator '>' must be spaced.

(style/space-infix-ops)


[error] 263-263: Operator '<' must be spaced.

(style/space-infix-ops)


[error] 263-263: Operator '>' must be spaced.

(style/space-infix-ops)

🔇 Additional comments (25)
apps/web-app/app/components/Form/UpdateProductVariant.vue (1)

136-147: Well-structured state initialization!

The state management implementation is robust with proper null checks and explicit type casting.

apps/web-app/app/components/DeliveryInfoBlock.vue (1)

23-23: LGTM! Clean migration to centralized store.

The change from legacy composable to centralized checkout store aligns with the PR objectives and follows Vue's composition API best practices.

apps/web-app/app/pages/command-center/product/[id]/index.vue (1)

71-71:

❓ Verification inconclusive

LGTM! Streamlined variant data access.

The removal of productId aligns with the broader refactoring effort to simplify product variant handling. The variant data can now be accessed directly using productVariantId.

Let's verify that ModalUpdateProductVariant correctly handles the variant data without productId:


🏁 Script executed:

#!/bin/bash
# Description: Verify that ModalUpdateProductVariant component correctly handles variant data without productId

# Check if ModalUpdateProductVariant uses channel store to get variant data
ast-grep --pattern $'const variant = channel.getProductVariant($_)' apps/web-app/app/components/Modal/UpdateProductVariant.vue

Length of output: 127


LGTM! Streamlined variant data access.

The removal of productId in favor of directly using productVariantId aligns with the broader refactoring effort. However, the automated check in ModalUpdateProductVariant.vue did not confirm the use of channel.getProductVariant (or a similar retrieval mechanism), so please manually verify that the component correctly retrieves and processes variant data using the provided productVariantId.

packages/core/server/api/category/index.post.ts (1)

6-6: LGTM! Improved data consistency.

The addition of channel.setAsUpdated() ensures that the channel state is properly updated after category creation, maintaining data consistency across the system.

Also applies to: 19-20

packages/core/server/api/category/[id]/index.patch.ts (1)

6-7: LGTM! Consistent error handling.

The addition of channel.setAsUpdated() maintains consistency with the POST endpoint, ensuring proper channel state updates after category modifications.

Also applies to: 21-22

apps/web-app/app/components/Navigation/Main.vue (1)

58-58:

❓ Verification inconclusive

LGTM! Aligned with checkout store migration.

The change from useCheckout() to useCheckoutStore() aligns with the PR's objective of centralizing checkout state management.

Let's verify that all checkout composable usages have been migrated:


🏁 Script executed:

#!/bin/bash
# Description: Verify that no legacy useCheckout() calls remain

# Search for any remaining useCheckout() calls
rg "useCheckout\(\)" apps/web-app/

Length of output: 36


LGTM! The change from useCheckout() to useCheckoutStore() in apps/web-app/app/components/Navigation/Main.vue clearly supports the migration to a centralized checkout state management pattern.

  • The automated search using the provided rg command did not return any legacy useCheckout() usages, suggesting that the migration has been applied consistently in that area.
  • However, since the script's output was minimal, please perform a manual review or additional checks to ensure that no legacy usages remain elsewhere in the codebase.
apps/web-app/app/app.vue (2)

7-7: LGTM! Nice addition of loading indicator.

The loading indicator provides visual feedback during page transitions, using the UI primary color for consistency.


33-34: LGTM! Proper initialization of checkout store.

The checkout store is correctly initialized and updated after the channel store, following the same pattern.

apps/web-app/app/pages/command-center/menu/[id]/index.vue (1)

65-65: LGTM! Proper handling of reactive reference.

The condition correctly checks menu.value to handle the computed ref returned by getMenu.

apps/web-app/app/components/Form/UpdateMenuCategory.vue (1)

54-55: LGTM! Consistent handling of reactive references.

The code correctly and consistently accesses category properties through .value in both initial state and reset state functions.

Also applies to: 60-61

apps/web-app/app/components/Modal/DeliveryInfo.vue (1)

36-36: LGTM! Migration to centralized checkout store.

Successfully migrated from legacy useCheckout() composable to the new centralized useCheckoutStore(), aligning with the PR's objective.

apps/web-app/app/composables/useApp.ts (1)

1-1:

❓ Verification inconclusive

Verify the impact of removing shared state management.

The removal of createSharedComposable changes how state is shared between components. Ensure this doesn't affect components that rely on shared state from this composable.


🏁 Script executed:

#!/bin/bash
# Search for components using useApp
rg "useApp\(\)" -A 3

Length of output: 2017


Impact on Shared State Management: Please Verify Behavior

The removal of the createSharedComposable wrapper means that each call to useApp now creates its own instance rather than sharing state among components. Given that multiple components (e.g., Navigation, Cart components, SearchBlock, and Header) are calling useApp, please verify that their behavior remains as intended under the new pattern. In particular, check that:

  • The state (e.g., isNavbarOpened, isCartDrawerOpened, and searchQuery) is correctly managed and synchronized as needed.
  • The refactoring to centralized store management indeed covers all state-sharing requirements previously handled by the shared composable.
packages/core/types/index.d.ts (1)

164-167: LGTM! Type changes improve consistency.

The changes to createdAt and updatedAt types from Date to string better align with API response format, and the addition of totalPrice improves type safety.

apps/web-app/app/components/Cart/LineCounter.vue (1)

31-32: LGTM! Clean transition to centralized store.

The switch to useCheckoutStore and direct store access simplifies the code while maintaining functionality.

apps/web-app/app/components/Cart/Button.vue (2)

2-14: LGTM! Clean and consistent with the new store pattern.

The template has been updated to use the new checkout store pattern, with improved styling using CSS variables for better theming support.


19-19: LGTM! Consistent with the store migration.

Successfully migrated from the legacy composable to the new checkout store.

apps/web-app/app/components/Cart/DeliveryMethodSwitch.vue (2)

2-19: LGTM! Well-structured delivery method switch.

The component effectively uses both channel and checkout stores, with clean conditional rendering and consistent styling.


24-24: LGTM! Consistent with the store migration.

Successfully migrated from the legacy composable to the new checkout store.

apps/web-app/app/pages/catalog/[categorySlug]/index.vue (2)

5-5: LGTM! Robust null-safety handling.

The template correctly uses optional chaining to handle potential undefined values, preventing runtime errors.

Also applies to: 11-11


24-24: LGTM! Improved error handling.

The error check now correctly validates the ref value instead of the ref object itself.

apps/web-app/stores/checkout.ts (1)

1-11: LGTM! Well-structured state management.

The store has well-typed state variables and focused computed properties.

apps/web-app/app/components/Cart/index.vue (1)

2-58: Well-structured implementation with proper error handling!

The component has been nicely refactored to use the checkout store, with proper conditional rendering and clear separation of concerns.

apps/web-app/stores/channel.ts (3)

88-99: LGTM! Improved reactivity with ComputedRef.

The changes to return ComputedRef types improve reactivity handling and align with Vue 3's composition API best practices. The implementation is consistent across all getter functions.


141-141: LGTM! Exports are well-organized.

The new functions are properly exported and maintain the logical organization of the store's public API.

Also applies to: 148-148


88-108:

❓ Verification inconclusive

Verify updates in dependent components.

The changes to getter functions affect how data is accessed in dependent components. Please ensure that all components listed in the AI summary have been updated to handle the new ComputedRef return types correctly:

  • Cart/Button.vue
  • Cart/DeliveryMethodSwitch.vue
  • Cart/Line.vue
  • catalog/[categorySlug]/[productSlug]/index.vue
  • checkout/index.vue

🏁 Script executed:

#!/bin/bash
# Description: Check if dependent components are using the new API correctly

# Search for direct access to computed values without .value
rg -A 5 "getProductVariant|getMenu|getMenuCategory|getActiveMenuCategory|getActiveMenuCategoryBySlug" apps/web-app/app/components/Cart/ apps/web-app/app/pages/catalog/ apps/web-app/app/pages/checkout/

Length of output: 1166


Verify updates in dependent components.

The changes to channel stored getter functions now return a ComputedRef, so all dependent components must access the computed values using .value. Our search confirms that in:

  • apps/web-app/app/components/Cart/Line.vue: The getters (getProductVariant and getProduct) are used with .value correctly.
  • apps/web-app/app/pages/catalog/[categorySlug]/index.vue: The computed value from getActiveMenuCategoryBySlug is appropriately accessed via .value.

Please review the following components as well to ensure they handle the new API properly:

  • apps/web-app/app/components/Cart/Button.vue
  • apps/web-app/app/components/Cart/DeliveryMethodSwitch.vue
  • apps/web-app/app/pages/checkout/index.vue

If any instances are found where the computed values are accessed directly (without .value), update them accordingly.

@@ -41,7 +41,7 @@
variant="gradient"
icon="food:busket"
class="w-fit flex flex-row gap-2 items-center"
@click="addProduct(variantId ?? '')"
@click="checkout.add(variantId ?? '')"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for the add to cart action.

The direct call to checkout.add should include error handling to manage potential failures gracefully.

-@click="checkout.add(variantId ?? '')"
+@click="async () => {
+  try {
+    await checkout.add(variantId ?? '')
+  } catch (error) {
+    // Handle error (e.g., show notification)
+    console.error('Failed to add item to cart:', error)
+  }
+}"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@click="checkout.add(variantId ?? '')"
@click="async () => {
try {
await checkout.add(variantId ?? '')
} catch (error) {
// Handle error (e.g., show notification)
console.error('Failed to add item to cart:', error)
}
}"

Comment on lines +32 to +63
async function add(productVariantId: string) {
try {
await $fetch(
'/api/checkout/add',
{
method: 'POST',
body: { productVariantId },
},
)

await update()
} catch (error) {
console.error(error)
}
}
async function change(checkout: Partial<Checkout>) {
try {
const data = await $fetch(
'/api/checkout',
{
method: 'PATCH',
body: checkout,
},
)

await update()

return data
} catch (error) {
console.error(error)
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling in add and change functions.

The functions catch errors but only log them, which might lead to silent failures in the UI.

 async function add(productVariantId: string) {
   try {
     await $fetch(
       '/api/checkout/add',
       {
         method: 'POST',
         body: { productVariantId },
       },
     )

     await update()
   } catch (error) {
     console.error(error)
+    throw createError({
+      statusCode: error.statusCode ?? 500,
+      message: error.message ?? 'Failed to add item to checkout',
+    })
   }
 }
 async function change(checkout: Partial<Checkout>) {
   try {
     const data = await $fetch(
       '/api/checkout',
       {
         method: 'PATCH',
         body: checkout,
       },
     )

     await update()

     return data
   } catch (error) {
     console.error(error)
+    throw createError({
+      statusCode: error.statusCode ?? 500,
+      message: error.message ?? 'Failed to update checkout',
+    })
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function add(productVariantId: string) {
try {
await $fetch(
'/api/checkout/add',
{
method: 'POST',
body: { productVariantId },
},
)
await update()
} catch (error) {
console.error(error)
}
}
async function change(checkout: Partial<Checkout>) {
try {
const data = await $fetch(
'/api/checkout',
{
method: 'PATCH',
body: checkout,
},
)
await update()
return data
} catch (error) {
console.error(error)
}
}
async function add(productVariantId: string) {
try {
await $fetch(
'/api/checkout/add',
{
method: 'POST',
body: { productVariantId },
},
)
await update()
} catch (error) {
console.error(error)
throw createError({
statusCode: error.statusCode ?? 500,
message: error.message ?? 'Failed to add item to checkout',
})
}
}
async function change(checkout: Partial<Checkout>) {
try {
const data = await $fetch(
'/api/checkout',
{
method: 'PATCH',
body: checkout,
},
)
await update()
return data
} catch (error) {
console.error(error)
throw createError({
statusCode: error.statusCode ?? 500,
message: error.message ?? 'Failed to update checkout',
})
}
}

Comment on lines +64 to +78
async function changeLineQuantity(id: string, method: 'increment' | 'decrement') {
try {
await $fetch(
`/api/checkout/line/${id}`,
{
method: 'POST',
body: { method },
},
)

await update()
} catch (error) {
console.error(error)
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling in changeLineQuantity function.

The function follows the same pattern of catching and only logging errors.

 async function changeLineQuantity(id: string, method: 'increment' | 'decrement') {
   try {
     await $fetch(
       `/api/checkout/line/${id}`,
       {
         method: 'POST',
         body: { method },
       },
     )

     await update()
   } catch (error) {
     console.error(error)
+    throw createError({
+      statusCode: error.statusCode ?? 500,
+      message: error.message ?? 'Failed to update line quantity',
+    })
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function changeLineQuantity(id: string, method: 'increment' | 'decrement') {
try {
await $fetch(
`/api/checkout/line/${id}`,
{
method: 'POST',
body: { method },
},
)
await update()
} catch (error) {
console.error(error)
}
}
async function changeLineQuantity(id: string, method: 'increment' | 'decrement') {
try {
await $fetch(
`/api/checkout/line/${id}`,
{
method: 'POST',
body: { method },
},
)
await update()
} catch (error) {
console.error(error)
throw createError({
statusCode: error.statusCode ?? 500,
message: error.message ?? 'Failed to update line quantity',
})
}
}

Comment on lines +159 to +168
<UFormField v-if="selectedPaymentMethod?.type === 'CASH'" :label="$t('app.checkout.change-label')">
<UInputNumber
v-model="remainingCheckout.change"
size="xl"
icon="food:cash"
orientation="vertical"
class="w-full"
:min="0"
:placeholder="channel.currencySign"
/>
</UFormField>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add validation for change amount.

The change amount should be validated against the total price to ensure it's not less than the order total.

 <UFormField v-if="selectedPaymentMethod?.type === 'CASH'" :label="$t('app.checkout.change-label')">
   <UInputNumber
     v-model="remainingCheckout.change"
     size="xl"
     orientation="vertical"
     class="w-full"
-    :min="0"
+    :min="checkout.totalPrice"
     :placeholder="channel.currencySign"
+    :error="remainingCheckout.change < checkout.totalPrice ? $t('app.checkout.change-error') : ''"
   />
 </UFormField>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<UFormField v-if="selectedPaymentMethod?.type === 'CASH'" :label="$t('app.checkout.change-label')">
<UInputNumber
v-model="remainingCheckout.change"
size="xl"
icon="food:cash"
orientation="vertical"
class="w-full"
:min="0"
:placeholder="channel.currencySign"
/>
</UFormField>
<UFormField v-if="selectedPaymentMethod?.type === 'CASH'" :label="$t('app.checkout.change-label')">
<UInputNumber
v-model="remainingCheckout.change"
size="xl"
orientation="vertical"
class="w-full"
:min="checkout.totalPrice"
:placeholder="channel.currencySign"
:error="remainingCheckout.change < checkout.totalPrice ? $t('app.checkout.change-error') : ''"
/>
</UFormField>

@hmbanan666 hmbanan666 merged commit 59a7a54 into main Feb 24, 2025
6 checks passed
@hmbanan666 hmbanan666 deleted the checkout branch February 24, 2025 18:19
@coderabbitai coderabbitai bot mentioned this pull request Feb 25, 2025
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