diff options
| author | trisusilo <tri.susilo@altama.co.id> | 2023-10-18 09:21:18 +0000 |
|---|---|---|
| committer | trisusilo <tri.susilo@altama.co.id> | 2023-10-18 09:21:18 +0000 |
| commit | 0a88ef1da1c04f4d40c0133edb7d27701c7a9746 (patch) | |
| tree | ae3768ba44054d51b1abcc0dcc90d18d4895e412 /src/lib/product/components | |
| parent | b4b17e22832a4665042a45030b77c3744fe61534 (diff) | |
| parent | 2a84fb3ce03cfa46cb3c7664e988957e1bd2731b (diff) | |
Merged in CR/UI (pull request #104)
CR/UI
Diffstat (limited to 'src/lib/product/components')
| -rw-r--r-- | src/lib/product/components/Product/Breadcrumb.jsx | 69 | ||||
| -rw-r--r-- | src/lib/product/components/Product/Product.jsx | 38 | ||||
| -rw-r--r-- | src/lib/product/components/Product/ProductDesktop.jsx | 126 | ||||
| -rw-r--r-- | src/lib/product/components/Product/ProductMobile.jsx | 31 | ||||
| -rw-r--r-- | src/lib/product/components/ProductCard.jsx | 31 | ||||
| -rw-r--r-- | src/lib/product/components/ProductFilter.jsx | 120 | ||||
| -rw-r--r-- | src/lib/product/components/ProductFilterDesktop.jsx | 199 | ||||
| -rw-r--r-- | src/lib/product/components/ProductSearch.jsx | 147 |
8 files changed, 586 insertions, 175 deletions
diff --git a/src/lib/product/components/Product/Breadcrumb.jsx b/src/lib/product/components/Product/Breadcrumb.jsx new file mode 100644 index 00000000..0554dba5 --- /dev/null +++ b/src/lib/product/components/Product/Breadcrumb.jsx @@ -0,0 +1,69 @@ +import odooApi from '@/core/api/odooApi' +import { createSlug } from '@/core/utils/slug' +import { + Breadcrumb as ChakraBreadcrumb, + BreadcrumbItem, + BreadcrumbLink, + Skeleton +} from '@chakra-ui/react' +import classNames from 'classnames' +import Link from 'next/link' +import { useQuery } from 'react-query' + +/** + * Renders a breadcrumb component based on the provided `productId`. + * + * @param {Object} props - The properties passed to the component. + * @param {number} props.productId - The ID of the product. + * @param {string} props.productName - The ID of the product. + * @return {ReactElement} The rendered breadcrumb component. + */ +const Breadcrumb = ({ productId, productName }) => { + const categories = useQuery( + `detail/categories/${productId}`, + async () => await odooApi('GET', `/api/v1/product/${productId}/category-breadcrumb`), + { + enabled: !!productId + } + ) + + return ( + <Skeleton + isLoaded={!categories.isLoading} + className={classNames({ + 'w-2/3': categories.isLoading, + 'w-full': !categories.isLoading + })} + > + <ChakraBreadcrumb + mb={10} + overflowX={'auto'} + className='text-caption-2 md:text-body-2 p-4 md:p-0' + > + <BreadcrumbItem> + <BreadcrumbLink as={Link} href='/' className='!text-danger-500 whitespace-nowrap'> + Home + </BreadcrumbLink> + </BreadcrumbItem> + + {categories.data?.map((category) => ( + <BreadcrumbItem key={category.id}> + <BreadcrumbLink + as={Link} + href={createSlug('/shop/category/', category.name, category.id)} + className='!text-danger-500 whitespace-nowrap' + > + {category.name} + </BreadcrumbLink> + </BreadcrumbItem> + ))} + + <BreadcrumbItem isCurrentPage> + <BreadcrumbLink className='whitespace-nowrap'>{productName}</BreadcrumbLink> + </BreadcrumbItem> + </ChakraBreadcrumb> + </Skeleton> + ) +} + +export default Breadcrumb diff --git a/src/lib/product/components/Product/Product.jsx b/src/lib/product/components/Product/Product.jsx index 54490c26..6e983c2e 100644 --- a/src/lib/product/components/Product/Product.jsx +++ b/src/lib/product/components/Product/Product.jsx @@ -36,29 +36,21 @@ const Product = ({ product, isVariant = false }) => { } }, [product, isVariant]) - if (isVariant == true) { - return ( - <> - <ProductDesktopVariant - product={product} - wishlist={wishlist} - toggleWishlist={toggleWishlist} - /> - <ProductMobileVariant - product={product} - wishlist={wishlist} - toggleWishlist={toggleWishlist} - /> - </> - ) - } else { - return ( - <> - <ProductMobile product={product} wishlist={wishlist} toggleWishlist={toggleWishlist} /> - <ProductDesktop products={product} wishlist={wishlist} toggleWishlist={toggleWishlist} /> - </> - ) - } + return isVariant == true ? ( + <> + <ProductDesktopVariant + product={product} + wishlist={wishlist} + toggleWishlist={toggleWishlist} + /> + <ProductMobileVariant product={product} wishlist={wishlist} toggleWishlist={toggleWishlist} /> + </> + ) : ( + <> + <ProductMobile product={product} wishlist={wishlist} toggleWishlist={toggleWishlist} /> + <ProductDesktop products={product} wishlist={wishlist} toggleWishlist={toggleWishlist} /> + </> + ) } export default Product diff --git a/src/lib/product/components/Product/ProductDesktop.jsx b/src/lib/product/components/Product/ProductDesktop.jsx index aa771eab..11c34009 100644 --- a/src/lib/product/components/Product/ProductDesktop.jsx +++ b/src/lib/product/components/Product/ProductDesktop.jsx @@ -24,6 +24,8 @@ import ColumnsSLA from './ColumnsSLA' import { useProductCartContext } from '@/contexts/ProductCartContext' import { Box, Skeleton, Tooltip } from '@chakra-ui/react' import { Info } from 'lucide-react' +import Breadcrumb from './Breadcrumb' +import { sellingProductFormat } from '@/core/utils/formatValue' const ProductDesktop = ({ products, wishlist, toggleWishlist }) => { const router = useRouter() @@ -89,38 +91,38 @@ const ProductDesktop = ({ products, wishlist, toggleWishlist }) => { } const updateCart = (variantId, quantity, source) => { - let dataUpdate + let dataUpdate = { + productId: variantId, + quantity, + selected: true, + source: source === 'buy' ? 'buy' : null + } + if (product.variants.length > 1) { let variantIndex = product.variants.findIndex((varian) => varian.id == variantId) - dataUpdate = { - productId: variantId, - quantity, - programLineId: product.variants[variantIndex].programActive, - selected: true, - source: source === 'buy' ? 'buy' : null - } + dataUpdate['programLineId'] = product.variants[variantIndex].programActive } else { - dataUpdate = { - productId: variantId, - quantity, - programLineId: promotionActiveId, - selected: true, - source: source === 'buy' ? 'buy' : null - } + dataUpdate['programLineId'] = promotionActiveId } + updateItemCart(dataUpdate) } - const handleAddToCart = (variantId) => { - if (!auth) { - router.push(`/login?next=/shop/product/${slug}`) - return - } + const redirectToLogin = (action, variantId, quantity) => { + const nextURL = `/shop/product/${slug}?action=${action}&variantId=${variantId}&qty=${quantity}` + router.push(`/login?next=${encodeURIComponent(nextURL)}`) + return true + } + const handleAddToCart = (variantId) => { const quantity = variantQuantityRefs.current[variantId].value if (!validQuantity(quantity)) return + if (!auth) { + return redirectToLogin('add_to_cart', variantId, quantity) + } + let source = 'cart' updateCart(variantId, quantity, source) setRefreshCart(true) @@ -140,6 +142,10 @@ const ProductDesktop = ({ products, wishlist, toggleWishlist }) => { const quantity = variantQuantityRefs.current[variant].value if (!validQuantity(quantity)) return + if (!auth) { + return redirectToLogin('buy', variant, quantity) + } + let source = 'buy' updateCart(variant, quantity, source) router.push(`/shop/checkout?source=buy`) @@ -199,47 +205,49 @@ const ProductDesktop = ({ products, wishlist, toggleWishlist }) => { return ( <DesktopView> <div className='container mx-auto pt-10'> + <Breadcrumb productId={product.id} productName={product.name} /> <div className='flex'> <div className='w-full flex flex-wrap'> <div className='w-5/12'> <div className='relative mb-2'> - {product?.flashSale?.remainingTime > 0 && lowestPrice?.price.discountPercentage > 0 && ( - <div className={`absolute bottom-0 w-full`}> - <div className='absolute bottom-0 w-full h-full'> - <ImageNext - src={backgorundFlashSale || '/images/GAMBAR-BG-FLASH-SALE.jpg'} - width={1000} - height={100} - /> - </div> - <div className='relative'> - <div className='flex gap-x-2 items-center p-2'> - <div className='bg-yellow-400 rounded-full p-1 h-9 w-20 flex items-center justify-center '> - <span className='text-lg font-bold'> - {Math.floor(product.lowestPrice.discountPercentage)}% - </span> - </div> - <div - className={`bg-red-600 border border-solid border-yellow-400 rounded-full h-9 p-2 flex w-[50%] items-center justify-center gap-x-4`} - > - <ImageNext - src='/images/ICON_FLASH_SALE_WEBSITE_INDOTEKNIK.svg' - width={17} - height={10} - /> - <span className='text-white text-lg font-semibold'> - {product?.flashSale?.tag != 'false' || product?.flashSale?.tag - ? product?.flashSale?.tag - : 'FLASH SALE'} - </span> - </div> - <div> - <CountDown2 initialTime={product.flashSale.remainingTime} /> + {product?.flashSale?.remainingTime > 0 && + lowestPrice?.price.discountPercentage > 0 && ( + <div className={`absolute bottom-0 w-full`}> + <div className='absolute bottom-0 w-full h-full'> + <ImageNext + src={backgorundFlashSale || '/images/GAMBAR-BG-FLASH-SALE.jpg'} + width={1000} + height={100} + /> + </div> + <div className='relative'> + <div className='flex gap-x-2 items-center p-2'> + <div className='bg-yellow-400 rounded-full p-1 h-9 w-20 flex items-center justify-center '> + <span className='text-lg font-bold'> + {Math.floor(product.lowestPrice.discountPercentage)}% + </span> + </div> + <div + className={`bg-red-600 border border-solid border-yellow-400 rounded-full h-9 p-2 flex w-[50%] items-center justify-center gap-x-4`} + > + <ImageNext + src='/images/ICON_FLASH_SALE_WEBSITE_INDOTEKNIK.svg' + width={17} + height={10} + /> + <span className='text-white text-lg font-semibold'> + {product?.flashSale?.tag != 'false' || product?.flashSale?.tag + ? product?.flashSale?.tag + : 'FLASH SALE'} + </span> + </div> + <div> + <CountDown2 initialTime={product.flashSale.remainingTime} /> + </div> </div> </div> </div> - </div> - )} + )} <Image src={product.image} alt={product.name} @@ -390,7 +398,7 @@ const ProductDesktop = ({ products, wishlist, toggleWishlist }) => { ))} </div> <div className='flex'> - <div className='w-3/4 leading-7 product__description'> + <div className='w-3/4 leading-8 product__description'> <TabContent active={informationTab == 'description'}> <span dangerouslySetInnerHTML={{ @@ -411,7 +419,7 @@ const ProductDesktop = ({ products, wishlist, toggleWishlist }) => { </div> </div> - <div className='w-[25%]'> + <div className='w-[30%]'> {product.variants.length > 1 && product.lowestPrice.priceDiscount > 0 && ( <div className='text-gray_r-12/80'>Harga mulai dari: </div> )} @@ -440,7 +448,11 @@ const ProductDesktop = ({ products, wishlist, toggleWishlist }) => { )} </div> )} */} - + {product?.qtySold > 0 && ( + <div className='text-gray_r-9'> + {sellingProductFormat(product?.qtySold) + ' Terjual'} + </div> + )} {lowestPrice?.isFlashsale && lowestPrice?.price.discountPercentage > 0 ? ( <> <div className='flex gap-x-1 items-center mt-2'> diff --git a/src/lib/product/components/Product/ProductMobile.jsx b/src/lib/product/components/Product/ProductMobile.jsx index ffa75f72..ef2c0002 100644 --- a/src/lib/product/components/Product/ProductMobile.jsx +++ b/src/lib/product/components/Product/ProductMobile.jsx @@ -19,9 +19,14 @@ import { gtagAddToCart } from '@/core/utils/googleTag' import odooApi from '@/core/api/odooApi' import ImageNext from 'next/image' import CountDown2 from '@/core/components/elements/CountDown/CountDown2' +import Breadcrumb from './Breadcrumb' +import useAuth from '@/core/hooks/useAuth' +import { sellingProductFormat } from '@/core/utils/formatValue' const ProductMobile = ({ product, wishlist, toggleWishlist }) => { const router = useRouter() + const auth = useAuth() + const { slug } = router.query const [quantity, setQuantity] = useState('1') const [selectedVariant, setSelectedVariant] = useState(null) @@ -58,7 +63,8 @@ const ProductMobile = ({ product, wishlist, toggleWishlist }) => { price: getLowestPrice(), stock: product.stockTotal, weight: product.weight, - hasProgram: false + hasProgram: false, + qtySold: product.qtySold }) const variantOptions = product.variants?.map((variant) => { @@ -101,7 +107,8 @@ const ProductMobile = ({ product, wishlist, toggleWishlist }) => { stock: variant.stock, weight: variant.weight, hasProgram: variant.hasProgram, - isFlashsale: variant.isFlashsale + isFlashsale: variant.isFlashsale, + qtySold: variant.qtySold } setActiveVariant(newActiveVariant) @@ -127,9 +134,20 @@ const ProductMobile = ({ product, wishlist, toggleWishlist }) => { return isValid } + const redirectToLogin = (action) => { + const nextURL = `/shop/product/${slug}?action=${action}&variantId=${activeVariant.id}&qty=${quantity}` + router.push(`/login?next=${encodeURIComponent(nextURL)}`) + return true + } + const handleClickCart = () => { if (!validAction()) return gtagAddToCart(activeVariant, quantity) + + if (!auth) { + return redirectToLogin('add_to_cart') + } + updateItemCart({ productId: activeVariant.id, quantity, @@ -142,6 +160,10 @@ const ProductMobile = ({ product, wishlist, toggleWishlist }) => { const handleClickBuy = () => { if (!validAction()) return + if (!auth) { + return redirectToLogin('buy') + } + updateItemCart({ productId: activeVariant.id, quantity, @@ -160,6 +182,7 @@ const ProductMobile = ({ product, wishlist, toggleWishlist }) => { return ( <MobileView> + <Breadcrumb productId={product.id} productName={product.name} /> <div className='relative'> {product?.flashSale?.remainingTime > 0 && activeVariant?.price.discountPercentage > 0 && ( <div className={`absolute bottom-0 w-full`}> @@ -225,7 +248,9 @@ const ProductMobile = ({ product, wishlist, toggleWishlist }) => { </button> </div> <h1 className='leading-6 font-medium mb-3'>{activeVariant?.name}</h1> - + {product?.qtySold > 0 && ( + <div className='text-gray_r-9'>{sellingProductFormat(activeVariant?.qtySold) + ' Terjual'}</div> + )} {product.variants.length > 1 && activeVariant.price.priceDiscount > 0 && !selectedVariant && ( diff --git a/src/lib/product/components/ProductCard.jsx b/src/lib/product/components/ProductCard.jsx index bc2174e4..9500a3fd 100644 --- a/src/lib/product/components/ProductCard.jsx +++ b/src/lib/product/components/ProductCard.jsx @@ -1,6 +1,7 @@ import Image from '@/core/components/elements/Image/Image' import Link from '@/core/components/elements/Link/Link' import currencyFormat from '@/core/utils/currencyFormat' +import { sellingProductFormat } from '@/core/utils/formatValue' import { createSlug } from '@/core/utils/slug' import whatsappUrl from '@/core/utils/whatsappUrl' import ImageNext from 'next/image' @@ -82,9 +83,7 @@ const ProductCard = ({ product, simpleTitle, variant = 'vertical' }) => { )} <Link href={createSlug('/shop/product/', product?.name, product?.id)} - className={`mb-3 !text-gray_r-12 leading-6 block ${ - simpleTitle ? 'line-clamp-2 h-12' : 'line-clamp-3 h-[64px]' - }`} + className={`mb-2 !text-gray_r-12 leading-6 block line-clamp-3 h-[64px]`} title={product?.name} > {product?.name} @@ -123,12 +122,11 @@ const ProductCard = ({ product, simpleTitle, variant = 'vertical' }) => { </div> )} - {product?.stockTotal > 0 && ( - <div className='flex gap-x-1'> - <div className='badge-solid-red'>Ready Stock</div> - <div className='badge-gray'>{product?.stockTotal > 5 ? '> 5' : '< 5'}</div> - </div> - )} + <div className='flex w-full items-center gap-x-1 '> + {product?.stockTotal > 0 && <div className='badge-solid-red'>Ready Stock</div>} + {/* <div className='badge-gray'>{product?.stockTotal > 5 ? '> 5' : '< 5'}</div> */} + {product?.qtySold > 0 && <div className='text-gray_r-9 text-[11px]'>{sellingProductFormat(product?.qtySold) + ' Terjual'}</div>} + </div> </div> </div> ) @@ -186,9 +184,7 @@ const ProductCard = ({ product, simpleTitle, variant = 'vertical' }) => { )} <Link href={createSlug('/shop/product/', product?.name, product?.id)} - className={`mb-3 !text-gray_r-12 leading-6 ${ - simpleTitle ? 'line-clamp-2' : 'line-clamp-3' - }`} + className={`mb-3 !text-gray_r-12 leading-6 line-clamp-3`} > {product?.name} </Link> @@ -229,12 +225,11 @@ const ProductCard = ({ product, simpleTitle, variant = 'vertical' }) => { </div> )} - {product?.stockTotal > 0 && ( - <div className='flex gap-x-1'> - <div className='badge-solid-red'>Ready Stock</div> - <div className='badge-gray'>{product?.stockTotal > 5 ? '> 5' : '< 5'}</div> - </div> - )} + <div className='flex w-full items-center gap-x-1 '> + {product?.stockTotal > 0 && <div className='badge-solid-red'>Ready Stock</div>} + {/* <div className='badge-gray'>{product?.stockTotal > 5 ? '> 5' : '< 5'}</div> */} + {product?.qtySold > 0 && <div className='text-gray_r-9 text-[11px]'>{sellingProductFormat(product?.qtySold) + ' Terjual'}</div>} + </div> </div> </div> ) diff --git a/src/lib/product/components/ProductFilter.jsx b/src/lib/product/components/ProductFilter.jsx index 34357526..d52fcb90 100644 --- a/src/lib/product/components/ProductFilter.jsx +++ b/src/lib/product/components/ProductFilter.jsx @@ -3,6 +3,7 @@ import { useRouter } from 'next/router' import { useState } from 'react' import _ from 'lodash' import { toQuery } from 'lodash-contrib' +import { Checkbox } from '@chakra-ui/react' const orderOptions = [ { value: 'price-asc', label: 'Harga Terendah' }, @@ -14,12 +15,51 @@ const orderOptions = [ const ProductFilter = ({ active, close, brands, categories, prefixUrl, defaultBrand = null }) => { const router = useRouter() const { query } = router - const [order, setOrder] = useState(query?.orderBy) + const [order, setOrder] = useState(query?.orderBy || 'popular') const [brand, setBrand] = useState(query?.brand) const [category, setCategory] = useState(query?.category) const [priceFrom, setPriceFrom] = useState(query?.priceFrom) const [priceTo, setPriceTo] = useState(query?.priceTo) + const [stock, setStock] = useState(query?.stock) + + const [activeRange, setActiveRange] = useState(null) + + const priceRange = [ + { + priceFrom: 100000, + priceTo: 200000 + }, + { + priceFrom: 200000, + priceTo: 300000 + }, + { + priceFrom: 300000, + priceTo: 400000 + }, + { + priceFrom: 400000, + priceTo: 500000 + } + ] + + const handlePriceFromChange = async (priceFromr, priceTor, index) => { + await setPriceFrom(priceFromr) + await setPriceTo(priceTor) + setActiveRange(index) + } + + const handleReadyStockChange = (event) => { + const value = event.target.value + const isChecked = event.target.checked + if (isChecked) { + setStock(value) + } else { + setStock(null) + } + } + const handleSubmit = () => { let params = { q: router.query.q, @@ -27,17 +67,27 @@ const ProductFilter = ({ active, close, brands, categories, prefixUrl, defaultBr brand, category, priceFrom, - priceTo + priceTo, + stock: stock } params = _.pickBy(params, _.identity) params = toQuery(params) router.push(`${prefixUrl}?${params}`) } + const formatCurrency = (value) => { + if (value >= 1000) { + const thousands = Math.floor(value / 1000) // Menghitung ribuan + return `Rp${thousands}k` + } else { + return `Rp${value}` + } + } + return ( <BottomPopup active={active} close={close} title='Filter Produk'> <div className='flex flex-col gap-y-4'> - {!defaultBrand && ( + {!router.pathname.includes('brands') && !defaultBrand && ( <div> <label>Brand</label> <select @@ -46,15 +96,22 @@ const ProductFilter = ({ active, close, brands, categories, prefixUrl, defaultBr value={brand} onChange={(e) => setBrand(e.target.value)} > - <option value=''>Pilih Brand...</option> - {brands.map((brand, index) => ( - <option value={brand} key={index}> - {brand} - </option> - ))} + {brands.length > 0 ? ( + <> + <option value=''>Pilih Brand...</option> + {brands.map((brand, index) => ( + <option value={brand.brand} key={index}> + {brand.brand} <span className='text-sm text-gray-200'>({brand.qty})</span> + </option> + ))} + </> + ) : ( + <option value=''>Brands tidak tersedia</option> + )} </select> </div> )} + <div> <label>Kategori</label> <select @@ -63,12 +120,18 @@ const ProductFilter = ({ active, close, brands, categories, prefixUrl, defaultBr value={category} onChange={(e) => setCategory(e.target.value)} > - <option value=''>Pilih Kategori...</option> - {categories.map((category, index) => ( - <option value={category} key={index}> - {category} - </option> - ))} + {categories.length > 0 ? ( + <> + <option value=''>Pilih Kategori...</option> + {categories.map((category, index) => ( + <option value={category.name} key={index}> + {category.name} <span className='text-sm text-gray-200'>({category.qty})</span> + </option> + ))} + </> + ) : ( + <option value=''>Kategori tidak tersedia</option> + )} </select> </div> <div> @@ -106,7 +169,34 @@ const ProductFilter = ({ active, close, brands, categories, prefixUrl, defaultBr onChange={(e) => setPriceTo(e.target.value)} /> </div> + <div className='grid grid-cols-2 gap-x-3 gap-y-2 mt-2'> + {priceRange.map((price, i) => ( + <button + key={i} + onClick={() => handlePriceFromChange(price.priceFrom, price.priceTo, i)} + className={`w-full border ${ + i === activeRange ? 'border-red-600' : 'border-gray-400' + } + py-2 p-3 rounded-full text-sm whitespace-nowrap`} + > + {formatCurrency(price.priceFrom)} - {formatCurrency(price.priceTo)} + </button> + ))} + </div> </div> + {/* <div> + <label>Ketersedian Stok</label> + <div className='mt-2'> + <Checkbox + isChecked={stock === 'ready stock'} + onChange={handleReadyStockChange} + value={'ready stock'} + size='md' + > + Ketersedian Stok + </Checkbox> + </div> + </div> */} <button type='button' className='btn-solid-red w-full mt-2' onClick={handleSubmit}> Terapkan Filter </button> diff --git a/src/lib/product/components/ProductFilterDesktop.jsx b/src/lib/product/components/ProductFilterDesktop.jsx index b64349c7..6118ed6b 100644 --- a/src/lib/product/components/ProductFilterDesktop.jsx +++ b/src/lib/product/components/ProductFilterDesktop.jsx @@ -1,5 +1,5 @@ import { useRouter } from 'next/router' -import { useState } from 'react' +import { useEffect, useState } from 'react' import _ from 'lodash' import { toQuery } from 'lodash-contrib' import { @@ -17,6 +17,7 @@ import { Stack, VStack } from '@chakra-ui/react' +import Image from '@/core/components/elements/Image/Image' const ProductFilterDesktop = ({ brands, categories, prefixUrl, defaultBrand = null }) => { const router = useRouter() @@ -26,6 +27,32 @@ const ProductFilterDesktop = ({ brands, categories, prefixUrl, defaultBrand = nu const [categoryValues, setCategory] = useState(query?.category?.split(',') || []) const [priceFrom, setPriceFrom] = useState(query?.priceFrom) const [priceTo, setPriceTo] = useState(query?.priceTo) + const [stock, setStock] = useState(query?.stock) + const [activeRange, setActiveRange] = useState(null) + const [activeIndeces, setActiveIndeces] = useState([]) + + const priceRange = [ + { + priceFrom: 100000, + priceTo: 200000 + }, + { + priceFrom: 200000, + priceTo: 300000 + }, + { + priceFrom: 300000, + priceTo: 400000 + }, + { + priceFrom: 400000, + priceTo: 500000 + } + ] + + const indexRange = priceRange.findIndex((range) => { + return range.priceFrom === parseInt(priceFrom) && range.priceTo == parseInt(priceTo) + }) const handleCategoriesChange = (event) => { const value = event.target.value @@ -46,6 +73,22 @@ const ProductFilterDesktop = ({ brands, categories, prefixUrl, defaultBrand = nu } } + const handleReadyStockChange = (event) => { + const value = event.target.value + const isChecked = event.target.checked + if (isChecked) { + setStock(value) + } else { + setStock(null) + } + } + + const handlePriceFromChange = async (priceFromr, priceTor, index) => { + await setPriceFrom(priceFromr) + await setPriceTo(priceTor) + setActiveRange(index) + } + const handleSubmit = () => { let params = { q: router.query.q, @@ -53,41 +96,80 @@ const ProductFilterDesktop = ({ brands, categories, prefixUrl, defaultBrand = nu brand: brandValues.join(','), category: categoryValues.join(','), priceFrom, - priceTo + priceTo, + stock: stock } params = _.pickBy(params, _.identity) params = toQuery(params) router.push(`${prefixUrl}?${params}`) } + const formatCurrency = (value) => { + if (value >= 1000) { + const thousands = Math.floor(value / 1000) // Menghitung ribuan + return `Rp${thousands}k` + } else { + return `Rp${value}` + } + } + + /*const handleIndexAccordion = async () => { + if (brandValues) { + await setActiveIndeces([...activeIndeces, 0]) + } + if (categoryValues) { + await setActiveIndeces([...activeIndeces, !router.pathname.includes('brands') ? 1 : 0]) + } + if (priceRange) { + await setActiveIndeces([...activeIndeces, !router.pathname.includes('brands') ? 2 : 1]) + } + if (stock) { + await setActiveIndeces([...activeIndeces, !router.pathname.includes('brands') ? 3 : 2]) + } + }*/ + + useEffect(() => { + setActiveRange(indexRange) + }, []) + + return ( <> <Accordion defaultIndex={[0]} allowMultiple> - <AccordionItem> - <AccordionButton padding={[2, 4]}> - <Box as='span' flex='1' textAlign='left' fontWeight='semibold'> - Brand - </Box> - <AccordionIcon /> - </AccordionButton> + {!router.pathname.includes('brands') && ( + <AccordionItem> + <AccordionButton padding={[2, 4]}> + <Box as='span' flex='1' textAlign='left' fontWeight='semibold'> + Brand + </Box> + <AccordionIcon /> + </AccordionButton> - <AccordionPanel> - <Stack gap={3} direction='column' maxH={'240px'} overflow='auto'> - {brands.map((brand, index) => ( - <div className='flex items-center gap-2' key={index}> - <Checkbox - isChecked={brandValues.includes(brand)} - onChange={handleBrandsChange} - value={brand} - size='md' - > - {brand} - </Checkbox> - </div> - ))} - </Stack> - </AccordionPanel> - </AccordionItem> + <AccordionPanel> + <Stack gap={3} direction='column' maxH={'240px'} overflow='auto'> + {brands && brands.length > 0 ? ( + brands.map((brand, index) => ( + <div className='flex items-center gap-2 ' key={index}> + <Checkbox + isChecked={brandValues.includes(brand.brand)} + onChange={handleBrandsChange} + value={brand.brand} + size='md' + > + <div className='flex items-center gap-2'> + <span>{brand.brand} </span> + <span className='text-sm text-gray-600'>({brand.qty})</span> + </div> + </Checkbox> + </div> + )) + ) : ( + <div className='flex items-center gap-2'>Brands tidak tersedia</div> + )} + </Stack> + </AccordionPanel> + </AccordionItem> + )} <AccordionItem> <AccordionButton padding={[2, 4]}> @@ -99,18 +181,25 @@ const ProductFilterDesktop = ({ brands, categories, prefixUrl, defaultBrand = nu <AccordionPanel> <Stack gap={3} direction='column' maxH={'240px'} overflow='auto'> - {categories.map((category, index) => ( - <div className='flex items-center gap-2' key={index}> - <Checkbox - isChecked={categoryValues.includes(category)} - onChange={handleCategoriesChange} - value={category} - size='md' - > - {category} - </Checkbox> - </div> - ))} + {categories && categories.length > 0 ? ( + categories.map((category, index) => ( + <div className='flex items-center gap-2' key={index}> + <Checkbox + isChecked={categoryValues.includes(category.name)} + onChange={handleCategoriesChange} + value={category.name} + size='md' + > + <div className='flex items-center gap-2'> + <span>{category.name} </span> + <span className='text-sm text-gray-600'>({category.qty})</span> + </div> + </Checkbox> + </div> + )) + ) : ( + <div className='flex items-center gap-2'>Kategori tidak tersedia</div> + )} </Stack> </AccordionPanel> </AccordionItem> @@ -143,9 +232,43 @@ const ProductFilterDesktop = ({ brands, categories, prefixUrl, defaultBrand = nu onChange={(e) => setPriceTo(e.target.value)} /> </InputGroup> + <div className='grid grid-cols-2 gap-x-3 gap-y-2'> + {priceRange.map((price, i) => ( + <button + key={i} + onClick={() => handlePriceFromChange(price.priceFrom, price.priceTo, i)} + className={`w-full border ${ + i === activeRange ? 'border-red-600' : 'border-gray-400' + } + py-2 p-3 rounded-full text-sm whitespace-nowrap`} + > + {formatCurrency(price.priceFrom)} - {formatCurrency(price.priceTo)} + </button> + ))} + </div> </VStack> </AccordionPanel> </AccordionItem> + + {/* <AccordionItem> + <AccordionButton padding={[2, 4]}> + <Box as='span' flex='1' textAlign='left' fontWeight='semibold'> + Ketersedian Stok + </Box> + <AccordionIcon /> + </AccordionButton> + + <AccordionPanel paddingY={4}> + <Checkbox + isChecked={stock === 'ready stock'} + onChange={handleReadyStockChange} + value={'ready stock'} + size='md' + > + Ketersedian Stock + </Checkbox> + </AccordionPanel> + </AccordionItem> */} </Accordion> <Button className='w-full mt-6' colorScheme='red' onClick={handleSubmit}> diff --git a/src/lib/product/components/ProductSearch.jsx b/src/lib/product/components/ProductSearch.jsx index df9aa91b..9d59b305 100644 --- a/src/lib/product/components/ProductSearch.jsx +++ b/src/lib/product/components/ProductSearch.jsx @@ -15,22 +15,27 @@ import { useRouter } from 'next/router' import searchSpellApi from '@/core/api/searchSpellApi' import Link from '@/core/components/elements/Link/Link' import whatsappUrl from '@/core/utils/whatsappUrl' +import { Image } from '@chakra-ui/react' +import odooApi from '@/core/api/odooApi' const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { const router = useRouter() const { page = 1 } = query const [q, setQ] = useState(query?.q || '*') + const [limit, setLimit] = useState(query?.limit || 30) + const [orderBy, setOrderBy] = useState(router.query?.orderBy || 'popular') if (defaultBrand) query.brand = defaultBrand.toLowerCase() - const { productSearch } = useProductSearch({ query: { ...query, q } }) + const { productSearch } = useProductSearch({ query: { ...query, q, limit, orderBy } }) const [products, setProducts] = useState(null) const [spellings, setSpellings] = useState(null) + const [bannerPromotionHeader, setBannerPromotionHeader] = useState(null) + const [bannerPromotionFooter, setBannerPromotionFooter] = useState(null) const popup = useActive() + const numRows = [30, 50, 80, 100] - const pageCount = Math.ceil( - productSearch.data?.response.numFound / productSearch.data?.responseHeader.params.rows - ) + const pageCount = Math.ceil(productSearch.data?.response.numFound / limit) const productStart = productSearch.data?.responseHeader.params.start - const productRows = productSearch.data?.responseHeader.params.rows + const productRows = limit const productFound = productSearch.data?.response.numFound useEffect(() => { @@ -63,20 +68,44 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { } }, [productFound, query, spellings]) - const brands = productSearch.data?.facetCounts?.facetFields?.manufactureName?.filter( + const brands = [] + for ( + let i = 0; + i < productSearch.data?.facetCounts?.facetFields?.manufactureNameS.length; + i += 2 + ) { + const brand = productSearch.data?.facetCounts?.facetFields?.manufactureNameS[i] + const qty = productSearch.data?.facetCounts?.facetFields?.manufactureNameS[i + 1] + if (qty > 0) { + brands.push({ brand, qty }) + } + } + /*const brandsList = productSearch.data?.facetCounts?.facetFields?.manufactureName?.filter( (value, index) => { if (index % 2 === 0) { - return true + const brand = value + const qty = index + 1 + brands.push({ brand, qty }) } } - ) - const categories = productSearch.data?.facetCounts?.facetFields?.categoryName?.filter( + )*/ + + const categories = [] + for (let i = 0; i < productSearch.data?.facetCounts?.facetFields?.categoryName.length; i += 2) { + const name = productSearch.data?.facetCounts?.facetFields?.categoryName[i] + const qty = productSearch.data?.facetCounts?.facetFields?.categoryName[i + 1] + if (qty > 0) { + categories.push({ name, qty }) + } + } + + /*const categories = productSearch.data?.facetCounts?.facetFields?.categoryName?.filter( (value, index) => { if (index % 2 === 0) { return true } } - ) + )*/ const orderOptions = [ { value: 'price-asc', label: 'Harga Terendah' }, @@ -95,6 +124,30 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { router.push(`${prefixUrl}?${params}`) } + const handleLimit = (e) => { + let params = { + ...router.query, + limit: e.target.value + } + params = _.pickBy(params, _.identity) + params = toQuery(params) + router.push(`${prefixUrl}?${params}`) + } + const getBanner = async () => { + if (router.pathname.includes('search')) { + const getBannerHeader = await odooApi('GET', '/api/v1/banner?type=promotion-header') + const getBannerFooter = await odooApi('GET', '/api/v1/banner?type=promotion-footer') + var randomIndex = Math.floor(Math.random() * getBannerHeader.length) + var randomIndexFooter = Math.floor(Math.random() * getBannerFooter.length) + setBannerPromotionHeader(getBannerHeader[randomIndex]) + setBannerPromotionFooter(getBannerFooter[randomIndexFooter]) + } + } + + useEffect(() => { + getBanner() + }, []) + useEffect(() => { setProducts(productSearch.data?.response?.products) }, [productSearch]) @@ -117,7 +170,7 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { <> <MobileView> {productSearch.isLoading && <ProductSearchSkeleton />} - <div className='p-4'> + <div className='p-4 pt-0'> <h1 className='mb-2 font-semibold text-h-sm'>Produk</h1> <div className='mb-2 leading-6 text-gray_r-11'> @@ -127,9 +180,9 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { {pageCount > 1 ? ( <> {productStart + 1}- - {productStart + productRows > productFound + {parseInt(productStart) + parseInt(productRows) > productFound ? productFound - : productStart + productRows} + : parseInt(productStart) + parseInt(productRows)} dari </> ) : ( @@ -149,9 +202,28 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { </div> {productFound > 0 && ( - <button className='btn-light mb-6 py-2 px-5' onClick={popup.activate}> - Filter - </button> + <div className='flex items-center gap-x-2 mb-5 justify-between'> + <div> + <button className='btn-light py-2 px-5 h-[40px]' onClick={popup.activate}> + Filter + </button> + </div> + <div className=''> + <select + name='limit' + className='form-input w-24' + value={router.query?.limit || ''} + onChange={(e) => handleLimit(e)} + > + {numRows.map((option, index) => ( + <option key={index} value={option}> + {' '} + {option}{' '} + </option> + ))} + </select> + </div> + </div> )} <div className='grid grid-cols-2 gap-3'> @@ -178,7 +250,7 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { </MobileView> <DesktopView> - <div className='container mx-auto mt-10 flex mb-3'> + <div className='container mx-auto flex mb-3'> <div className='w-3/12'> <ProductFilterDesktop brands={brands || []} @@ -188,6 +260,16 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { /> </div> <div className='w-9/12 pl-6'> + {bannerPromotionHeader && bannerPromotionHeader?.image && ( + <div className='mb-3'> + <Image + src={bannerPromotionHeader?.image} + alt='' + className='object-cover object-center h-full mx-auto' + /> + </div> + )} + <h1 className='text-2xl mb-2 font-semibold'>Hasil Pencarian</h1> <div className='flex justify-between items-center mb-2'> <div className='mb-2 leading-6 text-gray_r-11'> @@ -197,9 +279,9 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { {pageCount > 1 ? ( <> {productStart + 1}- - {productStart + productRows > productFound + {parseInt(productStart) + parseInt(productRows) > productFound ? productFound - : productStart + productRows} + : parseInt(productStart) + parseInt(productRows)} dari </> ) : ( @@ -222,10 +304,9 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { <select name='urutan' className='form-input mt-2' - value={router.query?.orderBy || ''} + value={orderBy} onChange={(e) => handleOrderBy(e)} > - <option value=''>Urutkan</option> {orderOptions.map((option, index) => ( <option key={index} value={option.value}> {' '} @@ -234,6 +315,21 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { ))} </select> </div> + <div className='ml-3'> + <select + name='limit' + className='form-input mt-2' + value={router.query?.limit || ''} + onChange={(e) => handleLimit(e)} + > + {numRows.map((option, index) => ( + <option key={index} value={option}> + {' '} + {option}{' '} + </option> + ))} + </select> + </div> </div> </div> {productSearch.isLoading && <ProductSearchSkeleton />} @@ -275,6 +371,15 @@ const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => { className='!justify-end' /> </div> + {bannerPromotionFooter && bannerPromotionFooter?.image && ( + <div className='mb-3'> + <Image + src={bannerPromotionFooter?.image} + alt='' + className='object-cover object-center h-full mx-auto' + /> + </div> + )} </div> </div> </DesktopView> |
