From 865f509a8b45c6db195661f35417623572d33cea Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Sat, 3 Aug 2024 13:33:59 +0700
Subject: <iman> update unchek cart

---
 src-migrate/pages/shop/cart/index.tsx | 97 ++++++++++++++++++++++++++++-------
 1 file changed, 78 insertions(+), 19 deletions(-)

(limited to 'src-migrate/pages/shop/cart/index.tsx')

diff --git a/src-migrate/pages/shop/cart/index.tsx b/src-migrate/pages/shop/cart/index.tsx
index 73b002b6..cfb20284 100644
--- a/src-migrate/pages/shop/cart/index.tsx
+++ b/src-migrate/pages/shop/cart/index.tsx
@@ -1,6 +1,6 @@
 import style from './cart.module.css';
 
-import React, { useEffect, useMemo, useState } from 'react';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
 import Link from 'next/link';
 import { Button, Checkbox, Spinner, Tooltip } from '@chakra-ui/react';
 import { toast } from 'react-hot-toast';
@@ -28,10 +28,12 @@ const CartPage = () => {
   const [buttonSelectNow, setButtonSelectNow] = useState(true);
   const [isLoad, setIsLoad] = useState<boolean>(false)
   const [isLoadDelete, setIsLoadDelete] = useState<boolean>(false)
-  const { loadCart, cart, summary } = useCartStore();
+  const { loadCart, cart, summary, updateCartItem } = useCartStore();
   const useDivvice = useDevice();
   const { setRefreshCart } = useProductCartContext()
   const [isTop, setIsTop] = useState(true);
+  const [hasChanged, setHasChanged] = useState(false);
+  const prevCartRef = useRef<CartItem[] | null>(null);
 
   useEffect(() => {
     const handleScroll = () => {
@@ -51,6 +53,35 @@ const CartPage = () => {
     }
   }, [auth, loadCart, cart, isButtonChek]);
 
+  useEffect(() => {
+    if (typeof auth === 'object' && !cart) {
+      loadCart(auth.id);
+      setIsStepApproval(auth?.feature?.soApproval);
+    }
+  }, [auth, loadCart, cart, isButtonChek]);
+
+  useEffect(() => {
+    const hasSelectedChanged = () => {
+      if (prevCartRef.current && cart) {
+        const prevCart = prevCartRef.current;
+        return cart.products.some((item, index) => 
+          prevCart[index] && prevCart[index].selected !== item.selected
+        );
+      }
+      return false;
+    };
+
+    if (hasSelectedChanged()) {
+      setHasChanged(true)
+      // Perform necessary actions here if selection has changed
+    }else{
+      setHasChanged(false)
+    }
+
+    // Update the ref to the current cart state
+    prevCartRef.current = cart ? [...cart.products] : null;
+  }, [cart]);
+
   const hasSelectedPromo = useMemo(() => {
     if (!cart) return false;
     return cart.products.some(item => item.cart_type === 'promotion' && item.selected);
@@ -71,6 +102,31 @@ const CartPage = () => {
     return cart.products.every(item => item.selected);
   }, [cart]);
 
+
+  useEffect(() => {
+    const updateCartItems = async () => {
+      if (typeof auth === 'object' && cart) {
+        const upsertPromises = cart.products.map(item => 
+          upsertUserCart({
+            userId: auth.id,
+            type: item.cart_type,
+            id: item.id,
+            qty: item.quantity,
+            selected: item.selected
+          })
+        );
+        try {
+          await Promise.all(upsertPromises);
+          await loadCart(auth.id);
+        } catch (error) {
+          console.error('Failed to update cart items:', error);
+        }
+      }
+    };
+
+    updateCartItems();
+  }, [hasChanged]);
+
   const handleCheckout = () => {
     router.push('/shop/checkout');
   }
@@ -84,23 +140,26 @@ const CartPage = () => {
   }
 
   const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
-    if (typeof auth !== 'object' || !cart) return;
-    setIsLoad(true)
-    const newSelected = e.target.checked;
-    setIsSelectedAll(newSelected);
-
-    for (const item of cart.products) {
-      await upsertUserCart({
-        userId: auth.id,
-        type: item.cart_type,
-        id: item.id,
-        qty: item.quantity,
-        selected: newSelected
-      });
+    
+    // Ensure that cart is not null before attempting to update
+    if (cart) {
+      const updatedCart = {
+        ...cart,
+        products: cart.products.map(item => ({
+          ...item,
+          selected: !hasSelectedAll
+        }))
+      };
+      
+      updateCartItem(updatedCart); // Pass only valid CartProps to updateCartItem
+      if(hasSelectedAll){
+        setIsSelectedAll(false);
+      }else{
+        setIsSelectedAll(true);
+      }
     }
-    await loadCart(auth.id);
-    setIsLoad(false)
-  }
+  };
+
 
   const handleDelete = async () => {
     if (typeof auth !== 'object' || !cart) return;
@@ -136,7 +195,7 @@ const CartPage = () => {
               />
             )}
               <p className='p-2 text-caption-2'>
-                {hasSelectedAll ? "Unchek all" : "Select all"}
+                {hasSelectedAll ? "Uncheck all" : "Select all"}
               </p>
           </div>
             <div className='delate all flex items-center object-center'>
-- 
cgit v1.2.3


From 213b4444c48896f24dd6803a9db2ae58af5b0391 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Mon, 5 Aug 2024 10:01:18 +0700
Subject: <iman> update unchek cart

---
 src-migrate/pages/shop/cart/index.tsx | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

(limited to 'src-migrate/pages/shop/cart/index.tsx')

diff --git a/src-migrate/pages/shop/cart/index.tsx b/src-migrate/pages/shop/cart/index.tsx
index cfb20284..5e3e042a 100644
--- a/src-migrate/pages/shop/cart/index.tsx
+++ b/src-migrate/pages/shop/cart/index.tsx
@@ -78,7 +78,6 @@ const CartPage = () => {
       setHasChanged(false)
     }
 
-    // Update the ref to the current cart state
     prevCartRef.current = cart ? [...cart.products] : null;
   }, [cart]);
 
@@ -141,7 +140,7 @@ const CartPage = () => {
 
   const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
     
-    // Ensure that cart is not null before attempting to update
+    
     if (cart) {
       const updatedCart = {
         ...cart,
@@ -151,7 +150,7 @@ const CartPage = () => {
         }))
       };
       
-      updateCartItem(updatedCart); // Pass only valid CartProps to updateCartItem
+      updateCartItem(updatedCart); 
       if(hasSelectedAll){
         setIsSelectedAll(false);
       }else{
-- 
cgit v1.2.3

