-
Notifications
You must be signed in to change notification settings - Fork 8
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
Conversation
WalkthroughThis pull request introduces significant updates to state management by shifting from legacy composables to a centralized checkout store. Multiple components and pages now use Changes
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
Possibly related PRs
Poem
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
There was a problem hiding this 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 suggestionAdd 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 suggestionImprove 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 whetheruseCheckoutStore()
guarantees a non-nullcheckout
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:
- Add explicit return type for better type safety
- Make the error message more descriptive
- 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
📒 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 usingproductVariantId
.Let's verify that
ModalUpdateProductVariant
correctly handles the variant data withoutproductId
:
🏁 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.vueLength of output: 127
LGTM! Streamlined variant data access.
The removal of
productId
in favor of directly usingproductVariantId
aligns with the broader refactoring effort. However, the automated check inModalUpdateProductVariant.vue
did not confirm the use ofchannel.getProductVariant
(or a similar retrieval mechanism), so please manually verify that the component correctly retrieves and processes variant data using the providedproductVariantId
.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()
touseCheckoutStore()
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()
touseCheckoutStore()
inapps/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 legacyuseCheckout()
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 bygetMenu
.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 centralizeduseCheckoutStore()
, 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 3Length of output: 2017
Impact on Shared State Management: Please Verify Behavior
The removal of the
createSharedComposable
wrapper means that each call touseApp
now creates its own instance rather than sharing state among components. Given that multiple components (e.g., Navigation, Cart components, SearchBlock, and Header) are callinguseApp
, please verify that their behavior remains as intended under the new pattern. In particular, check that:
- The state (e.g.,
isNavbarOpened
,isCartDrawerOpened
, andsearchQuery
) 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
andupdatedAt
types fromDate
tostring
better align with API response format, and the addition oftotalPrice
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
andgetProduct
) are used with.value
correctly.apps/web-app/app/pages/catalog/[categorySlug]/index.vue
: The computed value fromgetActiveMenuCategoryBySlug
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 ?? '')" |
There was a problem hiding this comment.
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.
@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) | |
} | |
}" |
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) | ||
} | ||
} |
There was a problem hiding this comment.
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.
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', | |
}) | |
} | |
} |
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) | ||
} | ||
} |
There was a problem hiding this comment.
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.
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', | |
}) | |
} | |
} |
<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> |
There was a problem hiding this comment.
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.
<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> |
Summary by CodeRabbit
New Features
Bug Fixes
Style
Refactor