From a59ed6e73a599a82d6ef248c57ad29f2ab9cb15d Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Mon, 29 Jul 2024 15:23:01 +0700
Subject: <iman> Merge branch 'Feature/category-management' into development

---
 src/lib/product/components/ProductSearch.jsx | 123 ++++++++++++++++++++++++---
 1 file changed, 112 insertions(+), 11 deletions(-)

(limited to 'src/lib/product/components/ProductSearch.jsx')

diff --git a/src/lib/product/components/ProductSearch.jsx b/src/lib/product/components/ProductSearch.jsx
index 34018ffe..4d510c5b 100644
--- a/src/lib/product/components/ProductSearch.jsx
+++ b/src/lib/product/components/ProductSearch.jsx
@@ -27,7 +27,9 @@ import ProductSearchSkeleton from './Skeleton/ProductSearchSkeleton';
 import SideBanner from '~/modules/side-banner';
 import FooterBanner from '~/modules/footer-banner';
 import CategorySection from './CategorySection';
+import LobSectionCategory from './LobSectionCategory';
 import { getIdFromSlug } from '@/core/utils/slug'
+import { data } from 'autoprefixer';
 
 const ProductSearch = ({
   query,
@@ -36,14 +38,105 @@ const ProductSearch = ({
   brand = null,
 }) => {
   const router = useRouter();
+   
   const { page = 1 } = query;
   const [q, setQ] = useState(query?.q || '*');
   const [search, setSearch] = useState(query?.q || '*');
   const [limit, setLimit] = useState(query?.limit || 30);
   const [orderBy, setOrderBy] = useState(router.query?.orderBy || 'popular');
+  const [finalQuery, setFinalQuery] = useState({});
+  const [queryFinal, setQueryFinal] = useState({});
+  const [dataCategoriesProduct, setDataCategoriesProduct] = useState([])
+  const [dataCategoriesLob, setDataCategoriesLob] = useState([])
+  const categoryId = getIdFromSlug(prefixUrl)
+  const [data, setData] = useState([])
+  const [dataLob, setDataLob] = useState([]);
   if (defaultBrand) query.brand = defaultBrand.toLowerCase();
+  const dataIdCategories = []
+  useEffect(() => {
+    if(prefixUrl.includes('category')){
+      const loadProduct = async () => {
+        const getCategoriesId = await odooApi('GET', `/api/v1/category/numFound?parent_id=${categoryId}`);
+        if (getCategoriesId) {
+          setDataCategoriesProduct(getCategoriesId);
+        }
+      };
+      loadProduct();
+    }else if(prefixUrl.includes('lob')){
+      const loadProduct = async () => {
+        const lobData = await odooApi('GET', `/api/v1/lob_homepage/${categoryId}/category_id`);
+         
+        if (lobData) {
+          setDataLob(lobData);
+        }
+      };
+      loadProduct();
+      
+    }
+  }, [categoryId]);
+  
+  const collectIds = (category) => {
+    const ids = [];
+    function recurse(cat) {
+      if (cat && cat.id) {
+        ids.push(cat.id);
+      }
+      if (Array.isArray(cat.children)) {
+        cat.children.forEach(recurse);
+      }
+    }
+    recurse(category);
+    return ids;
+  };
+  
+  useEffect(() => {
+    if(prefixUrl.includes('category')){
+      const ids = collectIds(dataCategoriesProduct);
+      const newQuery = {
+        fq: `category_id_ids:(${ids.join(' OR ')})`,
+        page,
+        brand : router.query.brand? router.query.brand : '',
+        category : router.query.category? router.query.category : '',
+      };
+      setFinalQuery(newQuery);
+    } else if (prefixUrl.includes('lob')){
+      
+      const fetchCategoryData = async () => {
+        if (dataLob[0]?.categoryIds) {
+          
+          for (const cate of dataLob[0].categoryIds) {
+           
+            dataIdCategories.push(cate.childId)
+          }
+          
+        
+          const mergedArray = dataIdCategories.flat();
+         
+          const newQuery = {
+            fq: `category_id_ids:(${mergedArray.join(' OR ')})`,
+            page,
+            brand : router.query.brand? router.query.brand : '',
+            category : router.query.category? router.query.category : '',
+          };
+       
+          setFinalQuery(newQuery);
+         
+        }
+      };
+      fetchCategoryData();
+    }
+  }, [dataCategoriesProduct, dataLob]);
+
+  useEffect(() => {
+    if (prefixUrl.includes('category') || prefixUrl.includes('lob')) {
+      setQueryFinal({ ...finalQuery, q, limit, orderBy });
+    } else {
+      setQueryFinal({ ...query, q, limit, orderBy });
+    }
+  }, [prefixUrl,dataCategoriesProduct, query, finalQuery]);
+
   const { productSearch } = useProductSearch({
-    query: { ...query, q, limit, orderBy },
+    query: queryFinal,
     operation: 'AND',
   });
   const [products, setProducts] = useState(null);
@@ -63,6 +156,7 @@ const ProductSearch = ({
   const [categoryValues, setCategory] = useState(
     query?.category?.split(',') || []
   );
+  
   const [priceFrom, setPriceFrom] = useState(query?.priceFrom || null);
   const [priceTo, setPriceTo] = useState(query?.priceTo || null);
 
@@ -71,9 +165,7 @@ const ProductSearch = ({
   const productRows = limit;
   const productFound = productSearch.data?.response.numFound;
   const [dataCategories, setDataCategories] = useState([])
-
-  const categoryId = getIdFromSlug(prefixUrl)
-
+  
   useEffect(() => {
     if (productFound == 0 && query.q && !spellings) {
       searchSpellApi({ query: query.q }).then((response) => {
@@ -103,7 +195,7 @@ const ProductSearch = ({
       });
     }
   }, [productFound, query, spellings]);
-
+  let id = []
   useEffect(() => {
     const checkIfBrand = async () => {
       const brand = await axios(
@@ -122,15 +214,20 @@ const ProductSearch = ({
   }, [q]);
  
   useEffect(() => {
-    const loadCategories = async () => {
-      const getCategories = await odooApi('GET', `/api/v1/category/child?parent_id=${categoryId}`) 
-     if(getCategories){
-      setDataCategories(getCategories)
-     }
+    if(prefixUrl.includes('category')){
+      const loadCategories = async () => {
+        const getCategories = await odooApi('GET', `/api/v1/category/child?parent_id=${categoryId}`)
+       if(getCategories){
+        setDataCategories(getCategories)
+       }
+      }
+      loadCategories()
     }
-    loadCategories()
   }, [])
 
+
+
+
   const brands = [];
   for (
     let i = 0;
@@ -277,6 +374,8 @@ const ProductSearch = ({
   };
 
   const isNotReadyStockPage = router.asPath !== '/shop/search?orderBy=stock';
+  
+  console.log("finalQuery",finalQuery)
 
   return (
     <>
@@ -338,6 +437,7 @@ const ProductSearch = ({
               SpellingComponent
             )}
           </div>
+          <LobSectionCategory categories={dataLob}/>
           <CategorySection categories={dataCategories}/>
 
           {productFound > 0 && (
@@ -429,6 +529,7 @@ const ProductSearch = ({
           </div>
 
           <div className='w-9/12 pl-6'>
+            <LobSectionCategory categories={dataLob}/>
             <CategorySection categories={dataCategories}/>
             {bannerPromotionHeader && bannerPromotionHeader?.image && (
               <div className='mb-3'>
-- 
cgit v1.2.3

