summaryrefslogtreecommitdiff
path: root/src-migrate/modules/cart/stores/useCartStore.ts
diff options
context:
space:
mode:
authorRafi Zadanly <zadanlyr@gmail.com>2023-12-15 17:15:32 +0700
committerRafi Zadanly <zadanlyr@gmail.com>2023-12-15 17:15:32 +0700
commitc9366090153e8aba3a673b2b77cbc8acc24e59a5 (patch)
tree9bad672e511d5585bb4be5b4e3190aca7c4a16af /src-migrate/modules/cart/stores/useCartStore.ts
parenta5321d82f4b5e8404f575f1d62e92d0322d78db9 (diff)
Update promotion program feature
Diffstat (limited to 'src-migrate/modules/cart/stores/useCartStore.ts')
-rw-r--r--src-migrate/modules/cart/stores/useCartStore.ts63
1 files changed, 63 insertions, 0 deletions
diff --git a/src-migrate/modules/cart/stores/useCartStore.ts b/src-migrate/modules/cart/stores/useCartStore.ts
new file mode 100644
index 00000000..1963df53
--- /dev/null
+++ b/src-migrate/modules/cart/stores/useCartStore.ts
@@ -0,0 +1,63 @@
+import { create } from 'zustand';
+import { CartProps } from '~/common/types/cart';
+import { deleteUserCart, getUserCart, upsertUserCart } 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>;
+};
+
+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 });
+ },
+}));
+
+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;
+ 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 = total * 0.11;
+ let grandTotal = total + tax;
+
+ return { subtotal, discount, total, tax, grandTotal };
+};