import { create } from 'zustand'; import { CartItem, CartProps } from '~/types/cart'; import { getUserCart } from '~/services/cart'; type State = { cart: CartProps | null; isLoadCart: boolean; summary: { subtotal: number; discount: number; total: number; tax: number; grandTotal: number; }; }; type Action = { loadCart: (userId: number) => Promise; updateCartItem: (updateCart: CartProps) => void; }; export const useCartStore = create((set, get) => ({ cart: null, isLoadCart: false, summary: { subtotal: 0, discount: 0, total: 0, tax: 0, grandTotal: 0, }, loadCart: async (userId) => { if (get().isLoadCart === true) return; set({ isLoadCart: true }); const cart: CartProps = (await getUserCart(userId)) as CartProps; set({ cart }); set({ isLoadCart: false }); const summary = computeSummary(cart); set({ summary }); }, updateCartItem: (updatedCart) => { const cart = get().cart; if (!cart) return; set({ cart: updatedCart }); const summary = computeSummary(updatedCart); set({ summary }); }, })); const computeSummary = (cart: CartProps) => { let subtotal = 0; let discount = 0; for (const item of cart.products) { if (!item.selected) continue; let price = 0; if (item.cart_type === 'promotion') price = (item?.package_price || 0) * item.quantity; else if (item.cart_type === 'product') price = item.price.price * item.quantity; subtotal += price; discount += price - item.price.price_discount * item.quantity; } let total = subtotal - discount; let tax = Math.round(total * 0.11); let grandTotal = total + tax; return { subtotal, discount, total, tax, grandTotal }; };