1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
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<void>;
updateCartItem: (updateCart: CartProps) => void;
};
export const useCartStore = create<State & Action>((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 };
};
|