diff options
| author | it-fixcomart <it@fixcomart.co.id> | 2024-11-13 16:11:09 +0700 |
|---|---|---|
| committer | it-fixcomart <it@fixcomart.co.id> | 2024-11-13 16:11:09 +0700 |
| commit | c873a401f0ea13e1881278e7977d4013d3a87394 (patch) | |
| tree | 5474f90a5e2530f3d3fae38a0a9876fd20bd2c00 | |
| parent | b9e64c111f21ac32466fa2a0f095df83ff111252 (diff) | |
| parent | 66e990de0a552cbc63e2db0e9e93c84520a806f2 (diff) | |
Merge branch 'new-release' into Feature/pengajuan-tempo
37 files changed, 1867 insertions, 685 deletions
diff --git a/package.json b/package.json index 54ce592f..3990e5cd 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ }, "dependencies": { "@chakra-ui/react": "^2.8.1", + "@choc-ui/chakra-autocomplete": "^5.6.2", "@emotion/react": "^11.11.1", "@emotion/styled": "^11.11.0", "@heroicons/react": "^2.0.13", diff --git a/public/images/writing.png b/public/images/writing.png Binary files differnew file mode 100644 index 00000000..17fedd74 --- /dev/null +++ b/public/images/writing.png diff --git a/src-migrate/modules/cart/components/Item.tsx b/src-migrate/modules/cart/components/Item.tsx index 6ffbb524..ab2e7ce1 100644 --- a/src-migrate/modules/cart/components/Item.tsx +++ b/src-migrate/modules/cart/components/Item.tsx @@ -36,26 +36,29 @@ const CartItem = ({ item, editable = true, selfPicking}: Props) => { )} <div className='w-2' /> <div> - Selamat! Pembelian anda lebih hemat {' '} + Selamat! Pembelian anda lebih hemat{' '} <span className={style.savingAmt}> - Rp{formatCurrency((item.package_price || 0) * item.quantity - item.subtotal)} + Rp + {formatCurrency( + (item.package_price || 0) * item.quantity - item.subtotal + )} </span> </div> </div> )} <div className={style.mainProdWrapper}> - {editable && ( - <CartItemSelect item={item} /> - )} + {editable && <CartItemSelect item={item} />} <div className='w-4' /> <CartItem.Image item={item} /> <div className={style.details}> - {(item.is_in_bu) && (item.on_hand_qty >= item.quantity) && ( + {item?.available_quantity > 0 && ( <div className='text-[10px] text-red-500 italic'> - *Barang ini bisa di pickup maksimal pukul 16.00 + {item.quantity <= item?.available_quantity + ? '*Barang ini bisa di pickup maksimal pukul 16.00' + : `*${item?.available_quantity} Barang ini bisa di pickup maksimal pukul 16.00`} </div> )} <CartItem.Name item={item} /> diff --git a/src-migrate/modules/product-detail/components/AddToCart.tsx b/src-migrate/modules/product-detail/components/AddToCart.tsx index a5284637..280e4a7a 100644 --- a/src-migrate/modules/product-detail/components/AddToCart.tsx +++ b/src-migrate/modules/product-detail/components/AddToCart.tsx @@ -1,51 +1,55 @@ -import BottomPopup from '@/core/components/elements/Popup/BottomPopup' +import BottomPopup from '@/core/components/elements/Popup/BottomPopup'; import style from '../styles/price-action.module.css'; -import { Button, Link, useToast } from '@chakra-ui/react' -import product from 'next-seo/lib/jsonld/product' -import { useRouter } from 'next/router' -import { useEffect, useState } from 'react' -import Image from '~/components/ui/image' -import { getAuth } from '~/libs/auth' -import { upsertUserCart } from '~/services/cart' +import { Button, Link, useToast } from '@chakra-ui/react'; +import product from 'next-seo/lib/jsonld/product'; +import { useRouter } from 'next/router'; +import { useEffect, useState } from 'react'; +import Image from '~/components/ui/image'; +import { getAuth } from '~/libs/auth'; +import { upsertUserCart } from '~/services/cart'; import LazyLoad from 'react-lazy-load'; import ProductSimilar from '../../../../src/lib/product/components/ProductSimilar'; import { IProductDetail } from '~/types/product'; import ImageNext from 'next/image'; -import { useProductCartContext } from '@/contexts/ProductCartContext' -import { createSlug } from '~/libs/slug' -import formatCurrency from '~/libs/formatCurrency' +import { useProductCartContext } from '@/contexts/ProductCartContext'; +import { createSlug } from '~/libs/slug'; +import formatCurrency from '~/libs/formatCurrency'; import { useProductDetail } from '../stores/useProductDetail'; type Props = { - variantId: number | null, + variantId: number | null; quantity?: number; source?: 'buy' | 'add_to_cart'; - products : IProductDetail -} + products: IProductDetail; +}; -type Status = 'idle' | 'loading' | 'success' +type Status = 'idle' | 'loading' | 'success'; const AddToCart = ({ variantId, quantity = 1, source = 'add_to_cart', - products + products, }: Props) => { - const auth = getAuth() - const router = useRouter() + let auth = getAuth(); + const router = useRouter(); const toast = useToast({ position: 'top', - isClosable: true - }) + isClosable: true, + }); - const { - askAdminUrl, - } = useProductDetail(); + const { askAdminUrl } = useProductDetail(); const [product, setProducts] = useState(products); - const [status, setStatus] = useState<Status>('idle') - const { productCart, setRefreshCart, setProductCart, refreshCart, isLoading, setIsloading } = - useProductCartContext() + const [status, setStatus] = useState<Status>('idle'); + const { + productCart, + setRefreshCart, + setProductCart, + refreshCart, + isLoading, + setIsloading, + } = useProductCartContext(); const productSimilarQuery = [ product?.name, @@ -55,32 +59,48 @@ const AddToCart = ({ const [addCartAlert, setAddCartAlert] = useState(false); const handleButton = async () => { - if (typeof auth !== 'object') { - const currentUrl = encodeURIComponent(router.asPath) - router.push(`/login?next=${currentUrl}`) - return; + let isLoggedIn = typeof auth === 'object'; + + if (!isLoggedIn) { + const currentUrl = encodeURIComponent(router.asPath); + await router.push(`/login?next=${currentUrl}`); + + // Tunggu login berhasil, misalnya dengan memantau perubahan status auth. + const authCheckInterval = setInterval(() => { + const newAuth = getAuth(); + if (typeof newAuth === 'object') { + isLoggedIn = true; + auth = newAuth; // Update nilai auth setelah login + clearInterval(authCheckInterval); + } + }, 500); // Periksa status login setiap 500ms + + await new Promise((resolve) => { + const checkLogin = setInterval(() => { + if (isLoggedIn) { + clearInterval(checkLogin); + resolve(null); + } + }, 500); + }); } - - if ( - !variantId || - isNaN(quantity) || - typeof auth !== 'object' - ) return; - if (status === 'success') return - setStatus('loading') + + if (!variantId || isNaN(quantity) || typeof auth !== 'object') return; + if (status === 'success') return; + setStatus('loading'); await upsertUserCart({ userId: auth.id, - type: 'product', - id: variantId, - qty: quantity, - selected: true, - source: source, - qtyAppend: true - }) - setStatus('idle') + type: 'product', + id: variantId, + qty: quantity, + selected: true, + source: source, + qtyAppend: true, + }); + setStatus('idle'); setRefreshCart(true); setAddCartAlert(true); - + toast({ title: 'Tambah ke keranjang', description: 'Berhasil menambahkan barang ke keranjang belanja', @@ -88,120 +108,130 @@ const AddToCart = ({ duration: 3000, isClosable: true, position: 'top', - }) - + }); + if (source === 'buy') { - router.push('/shop/checkout?source=buy') + router.push('/shop/checkout?source=buy'); } - } + }; useEffect(() => { - if (status === 'success') setTimeout(() => { setStatus('idle') }, 3000) - }, [status]) + if (status === 'success') + setTimeout(() => { + setStatus('idle'); + }, 3000); + }, [status]); const btnConfig = { - 'add_to_cart': { + add_to_cart: { colorScheme: 'yellow', - text: 'Keranjang' + text: 'Keranjang', }, - 'buy': { + buy: { colorScheme: 'red', - text: 'Beli' - } - } + text: 'Beli', + }, + }; return ( <div className='w-full'> - <Button onClick={handleButton} colorScheme={btnConfig[source].colorScheme} className='w-full'> + <Button + onClick={handleButton} + colorScheme={btnConfig[source].colorScheme} + className='w-full' + > {btnConfig[source].text} </Button> <BottomPopup - className='!container' - title='Berhasil Ditambahkan' - active={addCartAlert} - close={() => { - setAddCartAlert(false); - }} - > - <div className='flex mt-4'> - <div className='w-[10%]'> - <ImageNext - src={product.image} - alt={product.name} - className='h-32 object-contain object-center w-full border border-gray_r-4' - width={80} - height={80} - /> - </div> - <div className='ml-3 flex flex-1 items-start font-medium justify-center flex-col gap-y-1'> - {!!product.manufacture.name ? ( - <Link - href={createSlug('/shop/brands/', product.manufacture.name, product.manufacture.id.toString())} - className=' hover:underline' - color={"red"} - > - {product.manufacture.name} - </Link> - ) : '-'} - <p className='text-ellipsis overflow-hidden'> - {product.name} - </p> - <p> - {product.code} - </p> - {!!product.lowest_price && product.lowest_price.price > 0 && ( + className='!container' + title='Berhasil Ditambahkan' + active={addCartAlert} + close={() => { + setAddCartAlert(false); + }} + > + <div className='flex mt-4'> + <div className='w-[10%]'> + <ImageNext + src={product.image} + alt={product.name} + className='h-32 object-contain object-center w-full border border-gray_r-4' + width={80} + height={80} + /> + </div> + <div className='ml-3 flex flex-1 items-start font-medium justify-center flex-col gap-y-1'> + {!!product.manufacture.name ? ( + <Link + href={createSlug( + '/shop/brands/', + product.manufacture.name, + product.manufacture.id.toString() + )} + className=' hover:underline' + color={'red'} + > + {product.manufacture.name} + </Link> + ) : ( + '-' + )} + <p className='text-ellipsis overflow-hidden'>{product.name}</p> + <p>{product.code}</p> + {!!product.lowest_price && product.lowest_price.price > 0 && ( + <> + <div className='flex items-end gap-x-2'> + {product.lowest_price.discount_percentage > 0 && ( <> - <div className='flex items-end gap-x-2'> - {product.lowest_price.discount_percentage > 0 && ( - <> - <div className='badge-solid-red'> - {Math.floor(product.lowest_price.discount_percentage)}% - </div> - <div className='text-gray_r-11 line-through text-[11px] sm:text-caption-2'> - Rp {formatCurrency(product.lowest_price.price || 0)} - </div> - </> - )} - <div className='text-danger-500 font-semibold'> - Rp {formatCurrency(product.lowest_price.price_discount || 0)} - </div> + <div className='badge-solid-red'> + {Math.floor(product.lowest_price.discount_percentage)}% + </div> + <div className='text-gray_r-11 line-through text-[11px] sm:text-caption-2'> + Rp {formatCurrency(product.lowest_price.price || 0)} </div> </> )} + <div className='text-danger-500 font-semibold'> + Rp{' '} + {formatCurrency(product.lowest_price.price_discount || 0)} + </div> + </div> + </> + )} - {!!product.lowest_price && product.lowest_price.price === 0 && ( - <span> - Hubungi kami untuk dapatkan harga terbaik,{' '} - <Link - href={askAdminUrl} - target='_blank' - className='font-medium underline' - color={'red'} - > - klik disini - </Link> - </span> - )} - </div> - <div className='ml-3 flex items-center font-normal'> - <Link - href='/shop/cart' - className='flex-1 py-2 text-gray_r-12 btn-yellow' - > - Lihat Keranjang - </Link> - </div> + {!!product.lowest_price && product.lowest_price.price === 0 && ( + <span> + Hubungi kami untuk dapatkan harga terbaik,{' '} + <Link + href={askAdminUrl} + target='_blank' + className='font-medium underline' + color={'red'} + > + klik disini + </Link> + </span> + )} + </div> + <div className='ml-3 flex items-center font-normal'> + <Link + href='/shop/cart' + className='flex-1 py-2 text-gray_r-12 btn-yellow' + > + Lihat Keranjang + </Link> </div> - <div className='mt-8 mb-4'> - <div className='text-h-sm font-semibold mb-6'> - Kamu Mungkin Juga Suka - </div> - <LazyLoad> - <ProductSimilar query={productSimilarQuery} /> - </LazyLoad> + </div> + <div className='mt-8 mb-4'> + <div className='text-h-sm font-semibold mb-6'> + Kamu Mungkin Juga Suka </div> - </BottomPopup> + <LazyLoad> + <ProductSimilar query={productSimilarQuery} /> + </LazyLoad> + </div> + </BottomPopup> </div> - ) -} + ); +}; -export default AddToCart
\ No newline at end of file +export default AddToCart; diff --git a/src-migrate/modules/product-detail/components/AddToQuotation.tsx b/src-migrate/modules/product-detail/components/AddToQuotation.tsx new file mode 100644 index 00000000..f9b6c2b3 --- /dev/null +++ b/src-migrate/modules/product-detail/components/AddToQuotation.tsx @@ -0,0 +1,227 @@ +import BottomPopup from '@/core/components/elements/Popup/BottomPopup'; +import style from '../styles/price-action.module.css'; +import { Button, Link, useToast } from '@chakra-ui/react'; +import { ArrowDownTrayIcon } from '@heroicons/react/24/outline'; +import product from 'next-seo/lib/jsonld/product'; +import { useRouter } from 'next/router'; +import { useEffect, useState } from 'react'; +import Image from '~/components/ui/image'; +import { getAuth } from '~/libs/auth'; +import { upsertUserCart } from '~/services/cart'; +import LazyLoad from 'react-lazy-load'; +import ProductSimilar from '../../../../src/lib/product/components/ProductSimilar'; +import { IProductDetail } from '~/types/product'; +import ImageNext from 'next/image'; +import { useProductCartContext } from '@/contexts/ProductCartContext'; +import { createSlug } from '~/libs/slug'; +import formatCurrency from '~/libs/formatCurrency'; +import { useProductDetail } from '../stores/useProductDetail'; + +type Props = { + variantId: number | null; + quantity?: number; + source?: 'buy' | 'add_to_cart'; + products: IProductDetail; +}; + +type Status = 'idle' | 'loading' | 'success'; + +const AddToQuotation = ({ + variantId, + quantity = 1, + source = 'add_to_cart', + products, +}: Props) => { + const auth = getAuth(); + const router = useRouter(); + const toast = useToast({ + position: 'top', + isClosable: true, + }); + + const { askAdminUrl } = useProductDetail(); + + const [product, setProducts] = useState(products); + const [status, setStatus] = useState<Status>('idle'); + const { + productCart, + setRefreshCart, + setProductCart, + refreshCart, + isLoading, + setIsloading, + } = useProductCartContext(); + + const productSimilarQuery = [ + product?.name, + `fq=-product_id_i:${product.id}`, + `fq=-manufacture_id_i:${product.manufacture?.id || 0}`, + ].join('&'); + const [addCartAlert, setAddCartAlert] = useState(false); + + const handleButton = async () => { + if (typeof auth !== 'object') { + const currentUrl = encodeURIComponent(router.asPath); + router.push(`/login?next=${currentUrl}`); + return; + } + + if (!variantId || isNaN(quantity) || typeof auth !== 'object') return; + if (status === 'success') return; + setStatus('loading'); + await upsertUserCart({ + userId: auth.id, + type: 'product', + id: variantId, + qty: quantity, + selected: true, + source: source, + qtyAppend: true, + }); + setStatus('idle'); + setRefreshCart(true); + setAddCartAlert(true); + + toast({ + title: 'Tambah ke keranjang', + description: 'Berhasil menambahkan barang ke keranjang belanja', + status: 'success', + duration: 3000, + isClosable: true, + position: 'top', + }); + + if (source === 'buy') { + router.push('/shop/quotation?source=buy'); + } + }; + useEffect(() => { + if (status === 'success') + setTimeout(() => { + setStatus('idle'); + }, 3000); + }, [status]); + + const btnConfig = { + add_to_cart: { + colorScheme: 'yellow', + + text: 'Keranjang', + }, + buy: { + colorScheme: 'red', + text: 'Beli', + }, + }; + + return ( + <div className='w-full'> + <Button + onClick={handleButton} + color={'red'} + colorScheme='white' + className='w-full border-2 p-2 gap-1 hover:bg-slate-100 flex items-center' + > + <ImageNext + src='/images/writing.png' + alt='penawaran instan' + className='' + width={25} + height={25} + /> + Penawaran Harga Instan + </Button> + <BottomPopup + className='!container' + title='Berhasil Ditambahkan' + active={addCartAlert} + close={() => { + setAddCartAlert(false); + }} + > + <div className='flex mt-4'> + <div className='w-[10%]'> + <ImageNext + src={product.image} + alt={product.name} + className='h-32 object-contain object-center w-full border border-gray_r-4' + width={80} + height={80} + /> + </div> + <div className='ml-3 flex flex-1 items-start font-medium justify-center flex-col gap-y-1'> + {!!product.manufacture.name ? ( + <Link + href={createSlug( + '/shop/brands/', + product.manufacture.name, + product.manufacture.id.toString() + )} + className=' hover:underline' + color={'red'} + > + {product.manufacture.name} + </Link> + ) : ( + '-' + )} + <p className='text-ellipsis overflow-hidden'>{product.name}</p> + <p>{product.code}</p> + {!!product.lowest_price && product.lowest_price.price > 0 && ( + <> + <div className='flex items-end gap-x-2'> + {product.lowest_price.discount_percentage > 0 && ( + <> + <div className='badge-solid-red'> + {Math.floor(product.lowest_price.discount_percentage)}% + </div> + <div className='text-gray_r-11 line-through text-[11px] sm:text-caption-2'> + Rp {formatCurrency(product.lowest_price.price || 0)} + </div> + </> + )} + <div className='text-danger-500 font-semibold'> + Rp{' '} + {formatCurrency(product.lowest_price.price_discount || 0)} + </div> + </div> + </> + )} + + {!!product.lowest_price && product.lowest_price.price === 0 && ( + <span> + Hubungi kami untuk dapatkan harga terbaik,{' '} + <Link + href={askAdminUrl} + target='_blank' + className='font-medium underline' + color={'red'} + > + klik disini + </Link> + </span> + )} + </div> + <div className='ml-3 flex items-center font-normal'> + <Link + href='/shop/cart' + className='flex-1 py-2 text-gray_r-12 btn-yellow' + > + Lihat Keranjang + </Link> + </div> + </div> + <div className='mt-8 mb-4'> + <div className='text-h-sm font-semibold mb-6'> + Kamu Mungkin Juga Suka + </div> + <LazyLoad> + <ProductSimilar query={productSimilarQuery} /> + </LazyLoad> + </div> + </BottomPopup> + </div> + ); +}; + +export default AddToQuotation; diff --git a/src-migrate/modules/product-detail/components/Information.tsx b/src-migrate/modules/product-detail/components/Information.tsx index 75ae3c41..b9f4be91 100644 --- a/src-migrate/modules/product-detail/components/Information.tsx +++ b/src-migrate/modules/product-detail/components/Information.tsx @@ -1,56 +1,226 @@ -import style from '../styles/information.module.css' +import { + AutoComplete, + AutoCompleteInput, + AutoCompleteItem, + AutoCompleteList, +} from '@choc-ui/chakra-autocomplete'; +import style from '../styles/information.module.css'; -import React from 'react' -import dynamic from 'next/dynamic' -import Link from 'next/link' -import { useQuery } from 'react-query' +import dynamic from 'next/dynamic'; +import Link from 'next/link'; +import { useEffect, useRef, useState } from 'react'; -import { IProductDetail } from '~/types/product' -import { IProductVariantSLA } from '~/types/productVariant' -import { createSlug } from '~/libs/slug' -import { getVariantSLA } from '~/services/productVariant' -import { formatToShortText } from '~/libs/formatNumber' +import currencyFormat from '@/core/utils/currencyFormat'; +import { InputGroup, InputRightElement } from '@chakra-ui/react'; +import { ChevronDownIcon } from '@heroicons/react/24/outline'; +import Image from 'next/image'; +import { formatToShortText } from '~/libs/formatNumber'; +import { createSlug } from '~/libs/slug'; +import { getVariantSLA } from '~/services/productVariant'; +import { IProductDetail } from '~/types/product'; +import { useProductDetail } from '../stores/useProductDetail'; -const Skeleton = dynamic(() => import('@chakra-ui/react').then((mod) => mod.Skeleton)) +const Skeleton = dynamic(() => + import('@chakra-ui/react').then((mod) => mod.Skeleton) +); type Props = { - product: IProductDetail -} + product: IProductDetail; +}; const Information = ({ product }: Props) => { - const querySLA = useQuery<IProductVariantSLA>({ - queryKey: ['variant-sla', product.variants[0]?.id], - queryFn: () => getVariantSLA(product.variants[0].id), - enabled: product.variant_total === 1 - }) + const { selectedVariant, setSelectedVariant, setSla, setActive, sla } = + useProductDetail(); - const sla = querySLA?.data + const [inputValue, setInputValue] = useState<string | null>( + selectedVariant?.code + ' - ' + selectedVariant?.attributes[0] + ); + const [disableFilter, setDisableFilter] = useState<boolean>(false); + const inputRef = useRef<HTMLInputElement>(null); + + const [variantOptions, setVariantOptions] = useState<any[]>( + product?.variants + ); + // let variantOptions = product?.variants; + + // const querySLA = useQuery<IProductVariantSLA>({ + // queryKey: ['variant-sla', selectedVariant?.id], + // queryFn: () => getVariantSLA(selectedVariant?.id), + // enabled: !!selectedVariant?.id, + // }); + // const sla = querySLA?.data; + + const getsla = async () => { + const querySLA = await getVariantSLA(selectedVariant?.id); + setSla(querySLA); + }; + + useEffect(() => { + if (selectedVariant) { + getsla(); + setInputValue( + selectedVariant?.code + + (selectedVariant?.attributes[0] + ? ' - ' + selectedVariant?.attributes[0] + : '') + ); + } + }, [selectedVariant]); + + const handleOnChange = (vals: any) => { + setDisableFilter(true); + let code = vals.replace(/\s-\s.*$/, '').trim(); + let variant = variantOptions.find((item) => item.code === code); + setSelectedVariant(variant); + setInputValue( + variant?.code + + (variant?.attributes[0] ? ' - ' + variant?.attributes[0] : '') + ); + if (variant) { + const filteredOptions = product?.variants.filter( + (item) => item !== variant + ); + const newOptions = [variant, ...filteredOptions]; + setVariantOptions(newOptions); + } + }; + + const handleOnKeyUp = (e: any) => { + setDisableFilter(false); + setInputValue(e.target.value); + }; return ( <div className={style['wrapper']}> + <div className='realtive mb-5'> + <label className='form-label mb-2 text-lg text-red-600'> + Pilih Variant * :{' '} + <span className='text-gray_r-9 text-sm'> + {product?.variant_total} Variants + </span>{' '} + </label> + <AutoComplete + disableFilter={disableFilter} + openOnFocus + className='form-input' + onChange={(vals) => handleOnChange(vals)} + > + <InputGroup> + <AutoCompleteInput + ref={inputRef} + value={inputValue as string} + onChange={(e) => handleOnKeyUp(e)} + onFocus={() => setDisableFilter(true)} + /> + <InputRightElement className='mr-4'> + <ChevronDownIcon + className='h-6 w-6 text-gray-500' + onClick={() => inputRef?.current?.focus()} + /> + </InputRightElement> + </InputGroup> + + <AutoCompleteList> + {variantOptions.map((option, cid) => ( + <AutoCompleteItem + key={`option-${cid}`} + value={ + option.code + + (option?.attributes[0] ? ' - ' + option?.attributes[0] : '') + } + _selected={ + option.id === selectedVariant?.id + ? { + bg: 'gray.300', + } + : undefined + } + textTransform='capitalize' + > + <div + key={cid} + className='flex gap-x-2 w-full justify-between px-3 items-center p-2' + > + <div className='text-small'> + {option.code + + (option?.attributes[0] + ? ' - ' + option?.attributes[0] + : '')} + </div> + <div + className={ + option?.price?.discount_percentage + ? 'flex gap-x-4 items-center justify-between' + : '' + } + > + {option?.price?.discount_percentage > 0 && ( + <> + <div className='badge-solid-red text-xs'> + {Math.floor(option?.price?.discount_percentage)}% + </div> + <div className='min-w-16 sm:min-w-24 text-gray_r-11 line-through text-[11px] sm:text-caption-2'> + {currencyFormat(option?.price?.price)} + </div> + </> + )} + <div className='min-w-20 sm:min-w-28 text-danger-500 font-semibold'> + {currencyFormat(option?.price?.price_discount)} + </div> + </div> + </div> + </AutoCompleteItem> + ))} + </AutoCompleteList> + </AutoComplete> + </div> + <div className={style['row']}> - <div className={style['label']}>SKU Number</div> - <div className={style['value']}>SKU-{product.id}</div> + <div className={style['label']}>Item Code</div> + <div className={style['value']}>{selectedVariant?.code}</div> </div> <div className={style['row']}> <div className={style['label']}>Manufacture</div> <div className={style['value']}> {!!product.manufacture.name ? ( <Link - href={createSlug('/shop/brands/', product.manufacture.name, product.manufacture.id.toString())} - className='text-danger-500 hover:underline' + href={createSlug( + '/shop/brands/', + product.manufacture.name, + product.manufacture.id.toString() + )} > - {product.manufacture.name} + <Image + height={50} + width={100} + src={product.manufacture.logo} + alt={product.manufacture.name} + className='h-8 object-fit' + /> </Link> - ) : '-'} + ) : ( + '-' + )} + </div> + </div> + <div className={style['row']}> + <div className={style['label']}>Berat Barang</div> + <div className={style['value']}> + {selectedVariant?.weight > 0 ? `${selectedVariant?.weight} Kg` : '-'} </div> </div> <div className={style['row']}> <div className={style['label']}>Terjual</div> - <div className={style['value']}>{product.qty_sold > 0 ? formatToShortText(product.qty_sold) : '-'}</div> + <div className={style['value']}> + {product.qty_sold > 0 ? formatToShortText(product.qty_sold) : '-'} + </div> + </div> + <div className={style['row']}> + <div className={style['label']}>Persiapan Barang</div> + <div className={style['value']}>{sla?.sla_date}</div> </div> </div> - ) -} + ); +}; -export default Information
\ No newline at end of file +export default Information; diff --git a/src-migrate/modules/product-detail/components/PriceAction.tsx b/src-migrate/modules/product-detail/components/PriceAction.tsx index 9021264e..413c643a 100644 --- a/src-migrate/modules/product-detail/components/PriceAction.tsx +++ b/src-migrate/modules/product-detail/components/PriceAction.tsx @@ -1,12 +1,17 @@ import style from '../styles/price-action.module.css'; -import React, { useEffect } from 'react'; +import Image from 'next/image'; +import Link from 'next/link'; +import { useEffect, useState } from 'react'; import formatCurrency from '~/libs/formatCurrency'; import { IProductDetail } from '~/types/product'; import { useProductDetail } from '../stores/useProductDetail'; import AddToCart from './AddToCart'; -import Link from 'next/link'; +import AddToQuotation from './AddToQuotation'; import { getAuth } from '~/libs/auth'; +import useDevice from '@/core/hooks/useDevice'; +import odooApi from '~/libs/odooApi'; +import { Button, Skeleton } from '@chakra-ui/react'; type Props = { product: IProductDetail; @@ -22,27 +27,58 @@ const PriceAction = ({ product }: Props) => { askAdminUrl, isApproval, setIsApproval, + selectedVariant, + sla, } = useProductDetail(); - + const [qtyPickUp, setQtyPickUp] = useState(0); + const { isDesktop, isMobile } = useDevice(); useEffect(() => { - setActive(product.variants[0]) - if(product.variants.length > 2 && product.variants[0].price.price === 0){ - const variants = product.variants + setActive(selectedVariant); + if (product.variants.length > 2 && product.variants[0].price.price === 0) { + const variants = product.variants; for (let i = 0; i < variants.length; i++) { - if(variants[i].price.price > 0){ - setActive(variants[i]) + if (variants[i].price.price > 0) { + setActive(variants[i]); break; } } } - - }, [product, setActive]); + }, [product, setActive, selectedVariant]); + useEffect(() => { + const fetchData = async () => { + const qty_available = await odooApi( + 'GET', + `/api/v1/product_variant/${selectedVariant.id}/qty_available` + ); + + setQtyPickUp(qty_available?.qty); + }; + fetchData(); + }, [selectedVariant]); + useEffect(() => { + setQuantityInput('1'); + }, [selectedVariant]); + + let voucherPastiHemat = 0; + + if ( + product?.voucher_pasti_hemat + ? product?.voucher_pasti_hemat.length + : voucherPastiHemat > 0 + ) { + const stringVoucher = product?.voucher_pasti_hemat[0]; + const validJsonString = stringVoucher.replace(/'/g, '"'); + voucherPastiHemat = JSON.parse(validJsonString); + } return ( <div - className='block md:sticky top-[150px] bg-white py-0 md:py-6 z-10' + className={`block md:sticky md:top-[150px] md:py-6 fixed bottom-0 left-0 right-0 bg-white p-2 z-10 ${ + isMobile && + 'pb-6 pt-6 rounded-lg shadow-[rgba(0,0,4,0.1)_0px_-4px_4px_0px] ' + }`} id='price-section' > {!!activePrice && activePrice.price > 0 && ( @@ -84,18 +120,69 @@ const PriceAction = ({ product }: Props) => { )} <div className='h-4' /> + <div className='flex gap-x-5 items-center'> + <div className='relative flex items-center'> + <button + type='button' + className='absolute left-0 px-2 py-1 h-full text-gray-500' + onClick={() => + setQuantityInput(String(Math.max(1, Number(quantityInput) - 1))) + } + > + - + </button> + <input + type='number' + id='quantity' + min={1} + value={quantityInput} + onChange={(e) => setQuantityInput(e.target.value)} + className={style['quantity-input']} + /> + <button + type='button' + className='absolute right-0 px-2 py-1 h-full text-gray-500' + onClick={() => setQuantityInput(String(Number(quantityInput) + 1))} + > + + + </button> + </div> + + <div> + <Skeleton + isLoaded={sla} + h='21px' + // w={16} + className={sla?.qty < 10 ? 'text-red-600 font-medium' : ''} + > + Stock : {sla?.qty}{' '} + </Skeleton> + {/* <span className={sla?.qty < 10 ? 'text-red-600 font-medium' : ''}> + {' '} + </span> */} + </div> + <div> + {product?.is_in_bu && ( + <Link href='/panduan-pick-up-service' className='group'> + <Image + src='/images/PICKUP-NOW.png' + className='group-hover:scale-105 transition-transform duration-200' + alt='pickup now' + width={100} + height={12} + /> + </Link> + )} + </div> + </div> + {qtyPickUp > 0 && ( + <div className='text-[12px] mt-1 text-red-500 italic'> + * {qtyPickUp} barang bisa di pickup + </div> + )} + <div className='h-4' /> - <div className={style['action-wrapper']}> - <label htmlFor='quantity' className='hidden'> - Quantity - </label> - <input - type='number' - id='quantity' - value={quantityInput} - onChange={(e) => setQuantityInput(e.target.value)} - className={style['quantity-input']} - /> + <div className={`${style['action-wrapper']}`}> <AddToCart products={product} variantId={activeVariantId} @@ -110,6 +197,14 @@ const PriceAction = ({ product }: Props) => { /> )} </div> + <div className='mt-4'> + <AddToQuotation + source='buy' + products={product} + variantId={activeVariantId} + quantity={Number(quantityInput)} + /> + </div> </div> ); }; diff --git a/src-migrate/modules/product-detail/components/ProductDetail.tsx b/src-migrate/modules/product-detail/components/ProductDetail.tsx index e4555913..b036cc2d 100644 --- a/src-migrate/modules/product-detail/components/ProductDetail.tsx +++ b/src-migrate/modules/product-detail/components/ProductDetail.tsx @@ -1,46 +1,52 @@ -import style from '../styles/product-detail.module.css' - -import Link from 'next/link' -import { useRouter } from 'next/router' -import { useEffect } from 'react' - -import { Button } from '@chakra-ui/react' -import { MessageCircleIcon, Share2Icon } from 'lucide-react' -import { LazyLoadComponent } from 'react-lazy-load-image-component' -import { RWebShare } from 'react-web-share' - -import useDevice from '@/core/hooks/useDevice' -import { whatsappUrl } from '~/libs/whatsappUrl' -import ProductPromoSection from '~/modules/product-promo/components/Section' -import { IProductDetail } from '~/types/product' -import { useProductDetail } from '../stores/useProductDetail' -import AddToWishlist from './AddToWishlist' -import Breadcrumb from './Breadcrumb' -import ProductImage from './Image' -import Information from './Information' -import PriceAction from './PriceAction' -import SimilarBottom from './SimilarBottom' -import SimilarSide from './SimilarSide' -import VariantList from './VariantList' -import { getAuth } from '~/libs/auth' - -import { gtagProductDetail } from '@/core/utils/googleTag' +import style from '../styles/product-detail.module.css'; + +import Link from 'next/link'; +import { useRouter } from 'next/router'; +import { useEffect } from 'react'; + +import { Button } from '@chakra-ui/react'; +import { MessageCircleIcon, Share2Icon } from 'lucide-react'; +import { LazyLoadComponent } from 'react-lazy-load-image-component'; +import { RWebShare } from 'react-web-share'; + +import useDevice from '@/core/hooks/useDevice'; +import { getAuth } from '~/libs/auth'; +import { whatsappUrl } from '~/libs/whatsappUrl'; +import ProductPromoSection from '~/modules/product-promo/components/Section'; +import { IProductDetail } from '~/types/product'; +import { useProductDetail } from '../stores/useProductDetail'; +import AddToWishlist from './AddToWishlist'; +import Breadcrumb from './Breadcrumb'; +import ProductImage from './Image'; +import Information from './Information'; +import PriceAction from './PriceAction'; +import SimilarBottom from './SimilarBottom'; +import SimilarSide from './SimilarSide'; + +import { gtagProductDetail } from '@/core/utils/googleTag'; type Props = { - product: IProductDetail -} + product: IProductDetail; +}; -const SELF_HOST = process.env.NEXT_PUBLIC_SELF_HOST +const SELF_HOST = process.env.NEXT_PUBLIC_SELF_HOST; const ProductDetail = ({ product }: Props) => { - const { isDesktop, isMobile } = useDevice() - const router = useRouter() - const auth = getAuth() - const { setAskAdminUrl, askAdminUrl, activeVariantId, setIsApproval, isApproval } = useProductDetail() + const { isDesktop, isMobile } = useDevice(); + const router = useRouter(); + const auth = getAuth(); + const { + setAskAdminUrl, + askAdminUrl, + activeVariantId, + setIsApproval, + isApproval, + setSelectedVariant, + } = useProductDetail(); useEffect(() => { gtagProductDetail(product); - },[product]) + }, [product]); useEffect(() => { const createdAskUrl = whatsappUrl({ @@ -48,76 +54,43 @@ const ProductDetail = ({ product }: Props) => { payload: { manufacture: product.manufacture.name, productName: product.name, - url: process.env.NEXT_PUBLIC_SELF_HOST + router.asPath + url: process.env.NEXT_PUBLIC_SELF_HOST + router.asPath, }, - fallbackUrl: router.asPath - }) + fallbackUrl: router.asPath, + }); - setAskAdminUrl(createdAskUrl) - }, [router.asPath, product.manufacture.name, product.name, setAskAdminUrl]) + setAskAdminUrl(createdAskUrl); + }, [router.asPath, product.manufacture.name, product.name, setAskAdminUrl]); useEffect(() => { if (typeof auth === 'object') { setIsApproval(auth?.feature?.soApproval); } + setSelectedVariant(product?.variants[0]) }, []); return ( <> <div className='md:flex md:flex-wrap'> - <div className="w-full mb-4 md:mb-0 px-4 md:px-0"> + <div className='w-full mb-4 md:mb-0 px-4 md:px-0'> <Breadcrumb id={product.id} name={product.name} /> </div> <div className='md:w-9/12 md:flex md:flex-col md:pr-4 md:pt-6'> <div className='md:flex md:flex-wrap'> - <div className="md:w-4/12"> + <div className='md:w-4/12'> <ProductImage product={product} /> </div> <div className='md:w-8/12 px-4 md:pl-6'> <div className='h-6 md:h-0' /> - <h1 className={style['title']}> - {product.name} - </h1> + <h1 className={style['title']}>{product.name}</h1> - <div className='h-6 md:h-8' /> + <div className='h-3 md:h-0' /> <Information product={product} /> <div className='h-6' /> - - <div className="flex gap-x-5"> - <Button - as={Link} - href={askAdminUrl} - variant='link' - target='_blank' - colorScheme='gray' - leftIcon={<MessageCircleIcon size={18} />} - > - Ask Admin - </Button> - - <AddToWishlist productId={product.id} /> - - <RWebShare - data={{ - text: 'Check out this product', - title: `${product.name} - Indoteknik.com`, - url: SELF_HOST + router.asPath - }} - > - <Button - variant='link' - colorScheme='gray' - leftIcon={<Share2Icon size={18} />} - > - Share - </Button> - </RWebShare> - </div> - </div> </div> @@ -131,38 +104,72 @@ const ProductDetail = ({ product }: Props) => { <div className='h-4 md:h-10' /> {!!activeVariantId && !isApproval && <ProductPromoSection product={product} productId={activeVariantId} />} - <div className={style['section-card']}> + {/* <div className={style['section-card']}> <h2 className={style['heading']}> Variant ({product.variant_total}) </h2> <div className='h-4' /> <VariantList variants={product.variants} /> - </div> + </div> */} <div className='h-0 md:h-6' /> <div className={style['section-card']}> - <h2 className={style['heading']}> - Informasi Produk - </h2> + <h2 className={style['heading']}>Informasi Produk</h2> <div className='h-4' /> <div className={style['description']} - dangerouslySetInnerHTML={{ __html: !product.description || product.description == '<p><br></p>' ? 'Belum ada deskripsi' : product.description }} + dangerouslySetInnerHTML={{ + __html: + !product.description || product.description == '<p><br></p>' + ? 'Belum ada deskripsi' + : product.description, + }} /> </div> </div> </div> {isDesktop && ( - <div className="md:w-3/12"> + <div className='md:w-3/12'> <PriceAction product={product} /> + <div className='flex gap-x-5 items-center justify-center'> + <Button + as={Link} + href={askAdminUrl} + variant='link' + target='_blank' + colorScheme='gray' + leftIcon={<MessageCircleIcon size={18} />} + > + Ask Admin + </Button> + + <span>|</span> + + <AddToWishlist productId={product.id} /> + + <span>|</span> + + <RWebShare + data={{ + text: 'Check out this product', + title: `${product.name} - Indoteknik.com`, + url: SELF_HOST + router.asPath, + }} + > + <Button + variant='link' + colorScheme='gray' + leftIcon={<Share2Icon size={18} />} + > + Share + </Button> + </RWebShare> + </div> <div className='h-6' /> - - <div className={style['heading']}> - Produk Serupa - </div> + <div className={style['heading']}>Produk Serupa</div> <div className='h-4' /> @@ -171,9 +178,7 @@ const ProductDetail = ({ product }: Props) => { )} <div className='md:w-full pt-4 md:py-10 px-4 md:px-0'> - <div className={style['heading']}> - Kamu Mungkin Juga Suka - </div> + <div className={style['heading']}>Kamu Mungkin Juga Suka</div> <div className='h-6' /> @@ -185,7 +190,7 @@ const ProductDetail = ({ product }: Props) => { <div className='h-6 md:h-0' /> </div> </> - ) -} + ); +}; -export default ProductDetail
\ No newline at end of file +export default ProductDetail; diff --git a/src-migrate/modules/product-detail/stores/useProductDetail.ts b/src-migrate/modules/product-detail/stores/useProductDetail.ts index eb409930..dee6b342 100644 --- a/src-migrate/modules/product-detail/stores/useProductDetail.ts +++ b/src-migrate/modules/product-detail/stores/useProductDetail.ts @@ -7,6 +7,8 @@ type State = { quantityInput: string; askAdminUrl: string; isApproval : boolean; + selectedVariant : any; + sla : any; }; type Action = { @@ -14,6 +16,8 @@ type Action = { setQuantityInput: (value: string) => void; setAskAdminUrl: (url: string) => void; setIsApproval : (value : boolean) => void; + setSelectedVariant : (value : any) => void; + setSla : (value : any) => void; }; export const useProductDetail = create<State & Action>((set, get) => ({ @@ -22,6 +26,8 @@ export const useProductDetail = create<State & Action>((set, get) => ({ quantityInput: '1', askAdminUrl: '', isApproval : false, + selectedVariant: null, + sla : null, setActive: (variant) => { set({ activeVariantId: variant?.id, activePrice: variant?.price }); }, @@ -33,5 +39,11 @@ export const useProductDetail = create<State & Action>((set, get) => ({ }, setIsApproval : (value : boolean) => { set({ isApproval : value }) + }, + setSelectedVariant : (value : any) => { + set({ selectedVariant : value }) + }, + setSla : (value : any ) => { + set({ sla : value }) } })); diff --git a/src-migrate/modules/product-detail/styles/information.module.css b/src-migrate/modules/product-detail/styles/information.module.css index c9b29020..5aa64fe5 100644 --- a/src-migrate/modules/product-detail/styles/information.module.css +++ b/src-migrate/modules/product-detail/styles/information.module.css @@ -3,11 +3,11 @@ } .row { - @apply flex p-3 rounded; + @apply flex p-4 rounded-sm bg-gray-100; } .row:nth-child(odd) { - @apply bg-gray-100; + @apply bg-white; } .label { diff --git a/src-migrate/modules/product-detail/styles/price-action.module.css b/src-migrate/modules/product-detail/styles/price-action.module.css index 651de958..cea50bff 100644 --- a/src-migrate/modules/product-detail/styles/price-action.module.css +++ b/src-migrate/modules/product-detail/styles/price-action.module.css @@ -8,7 +8,10 @@ @apply flex gap-x-2.5; } .quantity-input { - @apply px-2 rounded text-center border border-gray-300 w-14 h-10 focus:outline-none; + @apply w-24 h-10 text-center border border-gray-300 rounded focus:outline-none; + /* Padding di kiri dan kanan untuk memberi ruang bagi tombol */ + padding-left: 2rem; + padding-right: 2rem; } .contact-us { diff --git a/src-migrate/pages/shop/cart/index.tsx b/src-migrate/pages/shop/cart/index.tsx index c5386c91..70a28073 100644 --- a/src-migrate/pages/shop/cart/index.tsx +++ b/src-migrate/pages/shop/cart/index.tsx @@ -35,6 +35,8 @@ const CartPage = () => { const [hasChanged, setHasChanged] = useState(false); const prevCartRef = useRef<CartItem[] | null>(null); + console.log('ini cart', cart); + useEffect(() => { const handleScroll = () => { setIsTop(window.scrollY < 200); @@ -84,19 +86,19 @@ const CartPage = () => { const hasSelectedPromo = useMemo(() => { if (!cart) return false; - return cart.products.some( + return cart?.products?.some( (item) => item.cart_type === 'promotion' && item.selected ); }, [cart]); const hasSelected = useMemo(() => { if (!cart) return false; - return cart.products.some((item) => item.selected); + return cart?.products?.some((item) => item.selected); }, [cart]); const hasSelectNoPrice = useMemo(() => { if (!cart) return false; - return cart.products.some( + return cart?.products?.some( (item) => item.selected && item.price.price_discount === 0 ); }, [cart]); @@ -230,7 +232,7 @@ const CartPage = () => { </div> <div className={style['items']}> - {cart?.products.map((item) => ( + {cart?.products?.map((item) => ( <CartItemModule key={item.id} item={item} /> ))} diff --git a/src-migrate/types/cart.ts b/src-migrate/types/cart.ts index a3115103..05fdcadb 100644 --- a/src-migrate/types/cart.ts +++ b/src-migrate/types/cart.ts @@ -34,6 +34,7 @@ export type CartItem = { stock: number; is_in_bu: boolean; on_hand_qty: number; + available_quantity: number; weight: number; attributes: string[]; parent: { diff --git a/src-migrate/types/product.ts b/src-migrate/types/product.ts index 31ea0ce1..fb9c888c 100644 --- a/src-migrate/types/product.ts +++ b/src-migrate/types/product.ts @@ -31,7 +31,9 @@ export interface IProduct { manufacture: { id: number; name: string; + logo: string; }; + voucher_pasti_hemat : any; } export interface IProductDetail extends IProduct { diff --git a/src/core/components/layouts/BasicLayout.jsx b/src/core/components/layouts/BasicLayout.jsx index c4674344..1b62bf05 100644 --- a/src/core/components/layouts/BasicLayout.jsx +++ b/src/core/components/layouts/BasicLayout.jsx @@ -8,6 +8,7 @@ import odooApi from '@/core/api/odooApi'; import whatsappUrl from '@/core/utils/whatsappUrl'; import Navbar from '../elements/Navbar/Navbar'; import styles from './BasicLayout.module.css'; // Import modul CSS +import useDevice from '@/core/hooks/useDevice'; const AnimationLayout = dynamic(() => import('./AnimationLayout'), { ssr: false, @@ -23,6 +24,9 @@ const BasicLayout = ({ children }) => { const [highlight, setHighlight] = useState(false); const [buttonPosition, setButtonPosition] = useState(null); const [wobble, setWobble] = useState(false); + const [isProductPage, setIsProductPage] = useState(false); + + const { isDesktop, isMobile } = useDevice(); const router = useRouter(); const buttonRef = useRef(null); @@ -43,13 +47,16 @@ const BasicLayout = ({ children }) => { setUrlPath(router.asPath); } + if (router.pathname.includes('/shop/product/')) { + setIsProductPage(true); + } }, [product, router]); useEffect(() => { const handleMouseOut = (event) => { const rect = buttonRef.current.getBoundingClientRect(); if (event.clientY <= 0) { - setButtonPosition(rect) + setButtonPosition(rect); setHighlight(true); } else { setHighlight(false); @@ -92,13 +99,15 @@ const BasicLayout = ({ children }) => { return ( <> - {highlight && buttonPosition && ( + {highlight && buttonPosition && ( <div className={styles['overlay-highlight']} style={{ - '--button-x': `${buttonPosition.x + buttonPosition.width / 2}px`, + '--button-x': `${buttonPosition.x + buttonPosition.width / 2}px`, '--button-y': `${buttonPosition.y + buttonPosition.height / 2}px`, - '--button-radius': `${Math.max(buttonPosition.width, buttonPosition.height) / 2}px` + '--button-radius': `${ + Math.max(buttonPosition.width, buttonPosition.height) / 2 + }px`, }} onAnimationEnd={() => setHighlight(false)} /> @@ -106,11 +115,25 @@ const BasicLayout = ({ children }) => { <Navbar /> <AnimationLayout> {children} - <div className='fixed bottom-4 right-4 sm:bottom-14 sm:right-10 z-50'> - <div className='flex flex-row items-center'> - <a href={whatsappUrl(templateWA, payloadWA, urlPath)} className='flex flex-row items-center' rel='noopener noreferrer' target='_blank'> - <span className={`text-green-300 text-lg font-bold mr-4 ${wobble ? 'animate-wobble' : ''}`} onAnimationEnd={() => setWobble(false)}> - Whatsapp + <div + className={`fixed ${ + isMobile && isProductPage ? 'bottom-40' : 'bottom-16' + } right-4 sm:bottom-14 sm:right-10 z-50`} + > + <div className='flex flex-row items-center'> + <a + href={whatsappUrl(templateWA, payloadWA, urlPath)} + className='flex flex-row items-center' + rel='noopener noreferrer' + target='_blank' + > + <span + className={`text-green-300 text-lg font-bold mr-4 ${ + wobble ? 'animate-wobble' : '' + }`} + onAnimationEnd={() => setWobble(false)} + > + {isDesktop && 'Whatsapp'} </span> </a> <a diff --git a/src/lib/cart/components/Cartheader.jsx b/src/lib/cart/components/Cartheader.jsx index ddb77c1f..1c30bb13 100644 --- a/src/lib/cart/components/Cartheader.jsx +++ b/src/lib/cart/components/Cartheader.jsx @@ -1,105 +1,115 @@ -import { useCallback, useEffect, useMemo, useState } from 'react' -import { getCartApi } from '../api/CartApi' -import currencyFormat from '@/core/utils/currencyFormat' -import { createSlug } from '@/core/utils/slug' -import useAuth from '@/core/hooks/useAuth' -import { useRouter } from 'next/router' -import odooApi from '@/core/api/odooApi' -import { useProductCartContext } from '@/contexts/ProductCartContext' -import Image from '@/core/components/elements/Image/Image' -import whatsappUrl from '@/core/utils/whatsappUrl' -import { AnimatePresence, motion } from 'framer-motion' -import style from '../../../../src-migrate/modules/cart/styles/item-promo.module.css' -const { ShoppingCartIcon, PhotoIcon } = require('@heroicons/react/24/outline') -const { default: Link } = require('next/link') +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { getCartApi } from '../api/CartApi'; +import currencyFormat from '@/core/utils/currencyFormat'; +import { createSlug } from '@/core/utils/slug'; +import useAuth from '@/core/hooks/useAuth'; +import { useRouter } from 'next/router'; +import odooApi from '@/core/api/odooApi'; +import { useProductCartContext } from '@/contexts/ProductCartContext'; +import Image from '@/core/components/elements/Image/Image'; +import whatsappUrl from '@/core/utils/whatsappUrl'; +import { AnimatePresence, motion } from 'framer-motion'; +import style from '../../../../src-migrate/modules/cart/styles/item-promo.module.css'; +const { ShoppingCartIcon, PhotoIcon } = require('@heroicons/react/24/outline'); +const { default: Link } = require('next/link'); const Cardheader = (cartCount) => { - - const router = useRouter() - const [subTotal, setSubTotal] = useState(null) - const [buttonLoading, SetButtonTerapkan] = useState(false) - const itemLoading = [1, 2, 3] - const auth = useAuth() - const [countCart, setCountCart] = useState(null) - const { productCart, setRefreshCart, setProductCart, refreshCart, isLoading, setIsloading } = - useProductCartContext() + const router = useRouter(); + const [subTotal, setSubTotal] = useState(null); + const [buttonLoading, SetButtonTerapkan] = useState(false); + const itemLoading = [1, 2, 3]; + const auth = useAuth(); + const [countCart, setCountCart] = useState(null); + const { + productCart, + setRefreshCart, + setProductCart, + refreshCart, + isLoading, + setIsloading, + } = useProductCartContext(); - const [isHovered, setIsHovered] = useState(false) - const [isTop, setIsTop] = useState(true) + const [isHovered, setIsHovered] = useState(false); + const [isTop, setIsTop] = useState(true); const products = useMemo(() => { - return productCart?.products || [] - }, [productCart]) + return productCart?.products || []; + }, [productCart]); const handleMouseEnter = () => { - setIsHovered(true) - getCart() - } + setIsHovered(true); + getCart(); + }; const handleMouseLeave = () => { - setIsHovered(false) - } + setIsHovered(false); + }; const getCart = () => { if (!productCart && auth) { - refreshCartf() + refreshCartf(); } - } + }; const refreshCartf = useCallback(async () => { - setIsloading(true) - let cart = await getCartApi() - setProductCart(cart) - setCountCart(cart?.productTotal) - setIsloading(false) - }, [setProductCart, setIsloading]) + setIsloading(true); + let cart = await getCartApi(); + setProductCart(cart); + setCountCart(cart?.products?.length); + setIsloading(false); + }, [setProductCart, setIsloading]); useEffect(() => { - if (!products) return + if (!products) return; - let calculateTotalPriceBeforeTax = 0 - let calculateTotalTaxAmount = 0 - let calculateTotalDiscountAmount = 0 + let calculateTotalPriceBeforeTax = 0; + let calculateTotalTaxAmount = 0; + let calculateTotalDiscountAmount = 0; for (const product of products) { - if (product.quantity == '') continue + if (product.quantity == '') continue; - let priceBeforeTax = product.price.price / 1.11 - calculateTotalPriceBeforeTax += priceBeforeTax * product.quantity - calculateTotalTaxAmount += (product.price.price - priceBeforeTax) * product.quantity + let priceBeforeTax = product.price.price / 1.11; + calculateTotalPriceBeforeTax += priceBeforeTax * product.quantity; + calculateTotalTaxAmount += + (product.price.price - priceBeforeTax) * product.quantity; calculateTotalDiscountAmount += - (product.price.price - product.price.priceDiscount) * product.quantity + (product.price.price - product.price.priceDiscount) * product.quantity; } let subTotal = - calculateTotalPriceBeforeTax - calculateTotalDiscountAmount + calculateTotalTaxAmount - setSubTotal(subTotal) - }, [products]) + calculateTotalPriceBeforeTax - + calculateTotalDiscountAmount + + calculateTotalTaxAmount; + setSubTotal(subTotal); + }, [products]); useEffect(() => { if (refreshCart) { - refreshCartf() + refreshCartf(); } - setRefreshCart(false) - }, [refreshCart, refreshCartf, setRefreshCart]) + setRefreshCart(false); + }, [refreshCart, refreshCartf, setRefreshCart]); useEffect(() => { - setCountCart(cartCount.cartCount) - setRefreshCart(false) - }, [cartCount]) + setCountCart(cartCount.cartCount); + setRefreshCart(false); + }, [cartCount]); useEffect(() => { const handleScroll = () => { - setIsTop(window.scrollY === 0) - } - window.addEventListener('scroll', handleScroll) + setIsTop(window.scrollY === 0); + }; + window.addEventListener('scroll', handleScroll); return () => { - window.removeEventListener('scroll', handleScroll) - } - }, []) + window.removeEventListener('scroll', handleScroll); + }; + }, []); const handleCheckout = async () => { - SetButtonTerapkan(true) - let checkoutAll = await odooApi('POST', `/api/v1/user/${auth.id}/cart/select-all`) - router.push('/shop/checkout') - } - + SetButtonTerapkan(true); + let checkoutAll = await odooApi( + 'POST', + `/api/v1/user/${auth.id}/cart/select-all` + ); + router.push('/shop/checkout'); + }; return ( <div className='relative group'> @@ -152,8 +162,13 @@ const Cardheader = (cartCount) => { className='w-full max-w-md p-2 bg-white border border-gray-200 rounded-lg shadow overflow-hidden' > <div className='p-2 flex justify-between items-center'> - <h5 className='text-base font-semibold leading-none'>Keranjang Belanja</h5> - <Link href='/shop/cart' class='text-sm font-medium text-red-600 underline'> + <h5 className='text-base font-semibold leading-none'> + Keranjang Belanja + </h5> + <Link + href='/shop/cart' + class='text-sm font-medium text-red-600 underline' + > Lihat Semua </Link> </div> @@ -163,7 +178,10 @@ const Cardheader = (cartCount) => { <div className='justify-center p-4'> <p className='text-gray-500 text-center '> Silahkan{' '} - <Link href='/login' className='text-red-600 underline leading-6'> + <Link + href='/login' + className='text-red-600 underline leading-6' + > Login </Link>{' '} Untuk Melihat Daftar Keranjang Belanja Anda @@ -172,7 +190,11 @@ const Cardheader = (cartCount) => { )} {isLoading && itemLoading.map((item) => ( - <div key={item} role='status' className='max-w-sm animate-pulse'> + <div + key={item} + role='status' + className='max-w-sm animate-pulse' + > <div className='flex items-center space-x-4 mb- 2'> <div className='flex-shrink-0'> <PhotoIcon className='h-16 w-16 text-gray-500' /> @@ -194,14 +216,17 @@ const Cardheader = (cartCount) => { )} {auth && products.length > 0 && !isLoading && ( <> - <ul role='list' className='divide-y divide-gray-200 dark:divide-gray-700'> + <ul + role='list' + className='divide-y divide-gray-200 dark:divide-gray-700' + > {products && products?.map((product, index) => ( <> <li className='py-1 sm:py-2'> <div className='flex items-center space-x-4'> <div className='bagian gambar flex-shrink-0'> - {product.cartType === 'promotion' && ( + {product.cartType === 'promotion' && ( <Image src={product.imageProgram[0]} alt={product.name} @@ -227,10 +252,10 @@ const Cardheader = (cartCount) => { </div> <div className='bagian tulisan dan harga flex-1 min-w-0'> {product.cartType === 'promotion' && ( - <p className='text-caption-2 font-medium text-gray-900 truncate dark:text-white'> - {product.name} - </p> - )} + <p className='text-caption-2 font-medium text-gray-900 truncate dark:text-white'> + {product.name} + </p> + )} {product.cartType === 'product' && ( <Link href={createSlug( @@ -252,27 +277,32 @@ const Cardheader = (cartCount) => { {product?.price?.discountPercentage}% </div> <div className='text-gray_r-11 line-through text-caption-2'> - {currencyFormat(product?.price?.price)} + {currencyFormat( + product?.price?.price + )} </div> </div> )} - + <div className='flex justify-between items-center'> <div className='font-semibold text-sm text-red-600'> {product?.price?.priceDiscount > 0 ? ( - currencyFormat(product?.price?.priceDiscount) + currencyFormat( + product?.price?.priceDiscount + ) ) : ( <span className='text-gray_r-12/90 font-normal text-caption-1'> <a href={whatsappUrl('product', { name: product.name, - manufacture: product.manufacture?.name, + manufacture: + product.manufacture?.name, url: createSlug( '/shop/product/', product.name, product.id, true - ) + ), })} className='text-danger-500 underline' rel='noopener noreferrer' @@ -286,56 +316,112 @@ const Cardheader = (cartCount) => { </div> </div> </div> - <div className="flex flex-col w-3/4"> - {product.products?.map((product) => - <div key={product.id} className='md:ml-8 ml-4 mt-2 flex'> - <Link href={createSlug('/shop/product/', product.parent.name, product.parent.id.toString())} className='md:h-12 md:w-12 md:min-w-[48px] h-10 w-10 min-w-[40px] border border-gray-300 rounded '> - {product?.image && <Image src={product.image} alt={product.name} width={40} height={40} className='w-full h-full object-fill' />} - </Link> - - <div className="ml-4 w-full flex flex-col gap-y-1"> - <Link href={createSlug('/shop/product/', product.parent.name, product.parent.id.toString())} className="text-caption-2 font-medium text-gray-900 truncate dark:text-white"> - {product.displayName} - </Link> - - <div className='flex w-full'> - <div className="flex flex-col"> - {/* <div className="text-gray-500 text-caption-1">{product.code}</div> */} - <div> - <span className="text-gray-500 text-caption-1">Berat Barang: </span> - <span className="text-gray-500 text-caption-1">{product.packageWeight} Kg</span> - </div> - </div> + <div className='flex flex-col w-3/4'> + {product.products?.map((product) => ( + <div + key={product.id} + className='md:ml-8 ml-4 mt-2 flex' + > + <Link + href={createSlug( + '/shop/product/', + product.parent.name, + product.parent.id.toString() + )} + className='md:h-12 md:w-12 md:min-w-[48px] h-10 w-10 min-w-[40px] border border-gray-300 rounded ' + > + {product?.image && ( + <Image + src={product.image} + alt={product.name} + width={40} + height={40} + className='w-full h-full object-fill' + /> + )} + </Link> + + <div className='ml-4 w-full flex flex-col gap-y-1'> + <Link + href={createSlug( + '/shop/product/', + product.parent.name, + product.parent.id.toString() + )} + className='text-caption-2 font-medium text-gray-900 truncate dark:text-white' + > + {product.displayName} + </Link> + + <div className='flex w-full'> + <div className='flex flex-col'> + {/* <div className="text-gray-500 text-caption-1">{product.code}</div> */} + <div> + <span className='text-gray-500 text-caption-1'> + Berat Barang:{' '} + </span> + <span className='text-gray-500 text-caption-1'> + {product.packageWeight} Kg + </span> </div> </div> - </div> + </div> + </div> + ))} + {product.freeProducts?.map((product) => ( + <div + key={product.id} + className='md:ml-8 ml-4 mt-2 flex' + > + <Link + href={createSlug( + '/shop/product/', + product.parent.name, + product.parent.id.toString() )} - {product.freeProducts?.map((product) => - <div key={product.id} className='md:ml-8 ml-4 mt-2 flex'> - <Link href={createSlug('/shop/product/', product.parent.name, product.parent.id.toString())} className='md:h-12 md:w-12 md:min-w-[48px] h-10 w-10 min-w-[40px] border border-gray-300 rounded '> - {product?.image && <Image src={product.image} alt={product.name} width={40} height={40} className='w-full h-full object-fill' />} + className='md:h-12 md:w-12 md:min-w-[48px] h-10 w-10 min-w-[40px] border border-gray-300 rounded ' + > + {product?.image && ( + <Image + src={product.image} + alt={product.name} + width={40} + height={40} + className='w-full h-full object-fill' + /> + )} + </Link> + + <div className='ml-4 w-full flex flex-col gap-y-1'> + <Link + href={createSlug( + '/shop/product/', + product.parent.name, + product.parent.id.toString() + )} + className='text-caption-2 font-medium text-gray-900 truncate dark:text-white' + > + {product.displayName} </Link> - - <div className="ml-4 w-full flex flex-col gap-y-1"> - <Link href={createSlug('/shop/product/', product.parent.name, product.parent.id.toString())} className="text-caption-2 font-medium text-gray-900 truncate dark:text-white"> - {product.displayName} - </Link> - - <div className='flex w-full'> - <div className="flex flex-col"> - {/* <div className="text-gray-500 text-caption-1">{product.code}</div> */} - <div> - <span className="text-gray-500 text-caption-1">Berat Barang: </span> - <span className="text-gray-500 text-caption-1">{product.packageWeight} Kg</span> - </div> - </div> + + <div className='flex w-full'> + <div className='flex flex-col'> + {/* <div className="text-gray-500 text-caption-1">{product.code}</div> */} + <div> + <span className='text-gray-500 text-caption-1'> + Berat Barang:{' '} + </span> + <span className='text-gray-500 text-caption-1'> + {product.packageWeight} Kg + </span> </div> </div> - </div> - )} + </div> </div> + ))} + </div> </li> </> ))} @@ -347,8 +433,12 @@ const Cardheader = (cartCount) => { {auth && products.length > 0 && !isLoading && ( <> <div className='mt-3'> - <span className='text-gray-400 text-caption-2'>Subtotal Sebelum PPN : </span> - <span className='font-semibold text-red-600'>{currencyFormat(subTotal)}</span> + <span className='text-gray-400 text-caption-2'> + Subtotal Sebelum PPN :{' '} + </span> + <span className='font-semibold text-red-600'> + {currencyFormat(subTotal)} + </span> </div> <div className='mt-5 mb-2'> <button @@ -357,7 +447,9 @@ const Cardheader = (cartCount) => { onClick={handleCheckout} disabled={buttonLoading} > - {buttonLoading ? 'Loading...' : 'Lanjutkan Ke Pembayaran'} + {buttonLoading + ? 'Loading...' + : 'Lanjutkan Ke Pembayaran'} </button> </div> </> @@ -368,7 +460,7 @@ const Cardheader = (cartCount) => { )} </AnimatePresence> </div> - ) -} + ); +}; -export default Cardheader +export default Cardheader; diff --git a/src/lib/checkout/components/Checkout.jsx b/src/lib/checkout/components/Checkout.jsx index a1b0116a..e83e719c 100644 --- a/src/lib/checkout/components/Checkout.jsx +++ b/src/lib/checkout/components/Checkout.jsx @@ -67,7 +67,6 @@ const Checkout = () => { const getAddresses = async () => { const dataAddresses = await addressesApi(); - console.log('ini adalah adress',dataAddresses); setAddresses(dataAddresses); }; @@ -443,6 +442,7 @@ const Checkout = () => { const productOrder = products.map((product) => ({ product_id: product.id, quantity: product.quantity, + available_quantity: product?.availableQuantity, })); let data = { // partner_shipping_id: auth.partnerId, @@ -1665,7 +1665,7 @@ const SectionAddress = ({ address, label, url }) => ( ); const SectionValidation = ({ address }) => - address?.stateId == null && ( + address?.stateId == 0 && ( <BottomPopup active={true} title='Update Alamat'> <div className='leading-7 text-gray_r-12/80'> Mohon untuk memperbarui alamat Anda dengan mengklik tombol di bawah ini.{' '} diff --git a/src/lib/home/components/ServiceList.jsx b/src/lib/home/components/ServiceList.jsx index 5b16915d..b3cc8fe5 100644 --- a/src/lib/home/components/ServiceList.jsx +++ b/src/lib/home/components/ServiceList.jsx @@ -32,7 +32,7 @@ const ServiceList = () => { </div> <div className='w-full'> <Link - href='/tentang-kami' + href='/garansi-resmi' className='border border-gray-200 p-2 flex items-center gap-x-2 rounded-lg' > <div className=''> @@ -57,7 +57,7 @@ const ServiceList = () => { </div> <div className='w-full '> <Link - href='/tentang-kami' + href='/pembayaran-tempo' className='border border-gray-200 p-2 flex items-center gap-x-2 rounded-lg' > <div className=''> diff --git a/src/lib/product/components/Product/ProductDesktopVariant.jsx b/src/lib/product/components/Product/ProductDesktopVariant.jsx index 09b30a44..f4569574 100644 --- a/src/lib/product/components/Product/ProductDesktopVariant.jsx +++ b/src/lib/product/components/Product/ProductDesktopVariant.jsx @@ -1,12 +1,12 @@ - -import { Box, Skeleton, Tooltip } from '@chakra-ui/react'; +import { Box, Button, Skeleton, Tooltip } from '@chakra-ui/react'; import { HeartIcon } from '@heroicons/react/24/outline'; -import { Info } from 'lucide-react'; +import { Info, MessageCircleIcon, Share2Icon } from 'lucide-react'; import { useRouter } from 'next/router'; import { useCallback, useEffect, useRef, useState } from 'react'; import { toast } from 'react-hot-toast'; +import AddToWishlist from '../../../../../src-migrate/modules/product-detail/components/AddToWishlist'; +import { RWebShare } from 'react-web-share'; import LazyLoad from 'react-lazy-load'; - import { useProductCartContext } from '@/contexts/ProductCartContext'; import odooApi from '@/core/api/odooApi'; import Image from '@/core/components/elements/Image/Image'; @@ -18,10 +18,16 @@ import { updateItemCart } from '@/core/utils/cart'; import currencyFormat from '@/core/utils/currencyFormat'; import { createSlug } from '@/core/utils/slug'; import whatsappUrl from '@/core/utils/whatsappUrl'; +import { getAuth } from '~/libs/auth'; +import ImageNext from 'next/image'; import productSimilarApi from '../../api/productSimilarApi'; import ProductCard from '../ProductCard'; import ProductSimilar from '../ProductSimilar'; +import ProductPromoSection from '~/modules/product-promo/components/Section'; +import SimilarBottom from '~/modules/product-detail/components/SimilarBottom'; + +const SELF_HOST = process.env.NEXT_PUBLIC_SELF_HOST; const ProductDesktopVariant = ({ product, @@ -30,9 +36,10 @@ const ProductDesktopVariant = ({ isVariant, }) => { const router = useRouter(); - const auth = useAuth(); + let auth = useAuth(); const { slug } = router.query; - + const { srsltid } = router.query; + const [askAdminUrl, setAskAdminUrl, isApproval] = useState(); const [lowestPrice, setLowestPrice] = useState(null); const [addCartAlert, setAddCartAlert] = useState(false); @@ -40,11 +47,20 @@ const ProductDesktopVariant = ({ const { setRefreshCart } = useProductCartContext(); + const [quantityInput, setQuantityInput] = useState(1); + + const createdAskUrl = whatsappUrl({ + template: 'product', + payload: { + manufacture: product.manufacture.name, + productName: product.name, + url: process.env.NEXT_PUBLIC_SELF_HOST + router.asPath, + }, + fallbackUrl: router.asPath, + }); + const getLowestPrice = useCallback(() => { const lowest = product.price; - /* const lowest = prices.reduce((lowest, price) => { - return price.priceDiscount < lowest.priceDiscount ? price : lowest - }, prices[0])*/ return lowest; }, [product]); @@ -74,10 +90,10 @@ const ProductDesktopVariant = ({ const handleAddToCart = (variant) => { if (!auth) { - router.push(`/login?next=/shop/product/${slug}`); + router.push(`/login?next=/shop/product/${slug}?srsltid=${srsltid}`); return; } - const quantity = variantQuantityRefs.current[product.id].value; + const quantity = quantityInput; if (!validQuantity(quantity)) return; updateItemCart({ productId: product.id, @@ -91,8 +107,34 @@ const ProductDesktopVariant = ({ setAddCartAlert(true); }; - const handleBuy = (variant) => { - const quantity = variantQuantityRefs.current[product.id].value; + const handleBuy = async (variant) => { + const quantity = variantQuantityRefs?.current[product.id]?.value; + let isLoggedIn = typeof auth === 'object'; + + if (!isLoggedIn) { + const currentUrl = encodeURIComponent(router.asPath); + await router.push(`/login?next=${currentUrl}`); + + // Tunggu login berhasil, misalnya dengan memantau perubahan status auth. + const authCheckInterval = setInterval(() => { + const newAuth = getAuth(); + if (typeof newAuth === 'object') { + isLoggedIn = true; + auth = newAuth; // Update nilai auth setelah login + clearInterval(authCheckInterval); + } + }, 500); // Periksa status login setiap 500ms + + await new Promise((resolve) => { + const checkLogin = setInterval(() => { + if (isLoggedIn) { + clearInterval(checkLogin); + resolve(null); + } + }, 500); + }); + } + if (!validQuantity(quantity)) return; updateItemCart({ @@ -105,6 +147,45 @@ const ProductDesktopVariant = ({ router.push(`/shop/checkout?source=buy`); }; + const handleButton = async (variant) => { + const quantity = quantityInput; + let isLoggedIn = typeof auth === 'object'; + + if (!isLoggedIn) { + const currentUrl = encodeURIComponent(router.asPath); + await router.push(`/login?next=${currentUrl}`); + + // Tunggu login berhasil, misalnya dengan memantau perubahan status auth. + const authCheckInterval = setInterval(() => { + const newAuth = getAuth(); + if (typeof newAuth === 'object') { + isLoggedIn = true; + auth = newAuth; // Update nilai auth setelah login + clearInterval(authCheckInterval); + } + }, 500); // Periksa status login setiap 500ms + + await new Promise((resolve) => { + const checkLogin = setInterval(() => { + if (isLoggedIn) { + clearInterval(checkLogin); + resolve(null); + } + }, 500); + }); + } + if (!validQuantity(quantity)) return; + + updateItemCart({ + productId: variant, + quantity, + programLineId: null, + selected: true, + source: 'buy', + }); + router.push('/shop/quotation?source=buy'); + }; + const variantSectionRef = useRef(null); const goToVariantSection = () => { if (variantSectionRef.current) { @@ -160,87 +241,39 @@ const ProductDesktopVariant = ({ <Image src={product.image + '?variant=True'} alt={product.name} - className='h-[430px] object-contain object-center w-full border border-gray_r-4' + className='w-full h-[350px]' /> </div> - <div className='w-7/12 px-4'> + <div className='w-7/12 px-6'> <h1 className='text-title-md leading-10 font-medium'> {product?.name} </h1> <div className='mt-10'> - <div className='flex p-3'> - <div className='w-4/12 text-gray_r-12/70'>Nomor SKU</div> - <div className='w-8/12'>SKU-{product.id}</div> - </div> <div className='flex p-3 bg-gray_r-4'> - <div className='w-4/12 text-gray_r-12/70'>Part Number</div> - <div className='w-8/12'>{product.code || '-'}</div> + <div className='w-4/12 text-gray_r-12/70'>Item Code</div> + <div className='w-8/12'>{product.code}</div> </div> - <div className='flex p-3'> + <div className='flex p-3 items-center '> <div className='w-4/12 text-gray_r-12/70'>Manufacture</div> <div className='w-8/12'> - {product.manufacture?.name ? ( - <Link - href={createSlug( - '/shop/brands/', - product.manufacture?.name, - product.manufacture?.id - )} - > - {product.manufacture?.name} - </Link> - ) : ( - <div>-</div> - )} - </div> - </div> - - <div className='flex p-3 items-center bg-gray_r-4'> - <div className='w-4/12 text-gray_r-12/70'> - Persiapan Barang - </div> - <div className='w-8/12'> - {!product?.sla && <Skeleton width='20%' height='16px' />} - {product?.sla && ( - <Tooltip - placement='top' - label={`Masa Persiapan Barang ${product?.sla?.slaDate}`} - > - <Box className='w-fit flex items-center gap-x-2'> - {product?.sla?.slaDate} - <Info size={16} /> - </Box> - </Tooltip> - )} + <Link + href={createSlug( + '/shop/brands/', + product.manufacture.name, + product.manufacture.id.toString() + )} + > + <Image + width={100} + src={product.manufacture.logo} + alt={product.manufacture.name} + /> + </Link> </div> </div> - <div className='flex p-3'> - <div className='w-4/12 text-gray_r-12/70'>Stock</div> - <div className='w-8/12'> - {!product?.sla && <Skeleton width='10%' height='16px' />} - {product?.sla?.qty > 0 && <span>{product?.sla?.qty}</span>} - {product?.sla?.qty == 0 && ( - <a - href={whatsappUrl('product', { - name: product.name, - manufacture: product?.manufacture?.name, - url: createSlug( - '/shop/product/', - product.name, - product.id, - true - ), - })} - className='text-danger-500 font-medium' - > - Tanya Admin - </a> - )} - </div> - </div> - <div className='flex p-3 bg-gray_r-4'> + <div className='flex p-3 bg-gray_r-4 '> <div className='w-4/12 text-gray_r-12/70'>Berat Barang</div> <div className='w-8/12'> {product?.weight > 0 && <span>{product?.weight} KG</span>} @@ -262,24 +295,55 @@ const ProductDesktopVariant = ({ )} </div> </div> + <div className='flex p-3 items-center '> + <div className='w-4/12 text-gray_r-12/70'>Terjual</div> + <div className='w-8/12'>-</div> + </div> + + <div className='flex p-3 items-center bg-gray_r-4 '> + <div className='w-4/12 text-gray_r-12/70'> + Persiapan Barang + </div> + <div className='w-8/12'> + {!product?.sla && <Skeleton width='20%' height='16px' />} + {product?.sla && ( + <Tooltip + placement='top' + label={`Masa Persiapan Barang ${product?.sla?.slaDate}`} + > + <Box className='w-fit flex items-center gap-x-2'> + {product?.sla?.slaDate} + <Info size={16} /> + </Box> + </Tooltip> + )} + </div> + </div> </div> </div> - <div className='p-4 md:p-6 md:bg-gray-50 rounded-xl'> - <h2 className='text-h-md md:text-h-lg font-medium'>Informasi Produk</h2> - <div className='h-4' /> - <div - className='leading-relaxed text-gray-700' - dangerouslySetInnerHTML={{ - __html: - !product.parent.description || product.parent.description == '<p><br></p>' - ? 'Belum ada deskripsi' - : product.parent.description, - }} - /> + <div className='p-4 md:p-6 w-full'> + <ProductPromoSection product={product} productId={product.id} /> + + <div className='p-4 md:p-6 md:bg-gray-50 rounded-xl'> + <h2 className='text-h-md md:text-h-lg font-medium'> + Informasi Produk + </h2> + <div className='h-4' /> + <div + className='leading-relaxed text-gray-700' + dangerouslySetInnerHTML={{ + __html: + !product.parent.description || + product.parent.description == '<p><br></p>' + ? 'Belum ada deskripsi' + : product.parent.description, + }} + /> + </div> </div> </div> - <div className='w-[25%]'> + <div className='w-[33%]'> {product?.isFlashsale > 0 && product?.price?.discountPercentage > 0 ? ( <> @@ -337,46 +401,143 @@ const ProductDesktopVariant = ({ )} </h3> )} - <div className='flex gap-x-3 mt-4'> - <input - type='number' - className='form-input w-16 py-2 text-center bg-gray_r-1' - ref={setVariantQuantityRef(product.id)} - defaultValue={1} - /> - <button - type='button' + <div className='flex justify-between items-center py-5 px-3'> + <div className='relative flex items-center'> + <button + type='button' + className='absolute left-0 px-2 py-1 h-full text-gray-500' + onClick={() => + setQuantityInput( + String(Math.max(1, Number(quantityInput) - 1)) + ) + } + > + - + </button> + <input + type='number' + id='quantity' + min={1} + value={quantityInput} + onChange={(e) => setQuantityInput(e.target.value)} + className=' w-24 h-10 text-center border border-gray-300 rounded focus:outline-none' + /> + <button + type='button' + className='absolute right-0 px-2 py-1 h-full text-gray-500' + onClick={() => + setQuantityInput(String(Number(quantityInput) + 1)) + } + > + + + </button> + </div> + <div> + <Skeleton + isLoaded={sla} + h='21px' + // w={16} + className={ + product?.sla?.qty < 10 ? 'text-red-600 font-medium' : '' + } + > + Stock : {product?.sla?.qty}{' '} + </Skeleton> + </div> + <div> + {product?.sla?.qty > 0 && ( + <Link href='/panduan-pick-up-service' className='group'> + <Image + src='/images/PICKUP-NOW.png' + className='group-hover:scale-105 transition-transform duration-200 w-28' + alt='pickup now' + /> + </Link> + )} + </div> + </div> + <div className='flex gap-x-3'> + <Button onClick={() => handleAddToCart(product.id)} - className='flex-1 py-2 btn-yellow' + className='w-full' + colorScheme='yellow' > Keranjang - </button> - <button - type='button' + </Button> + <Button onClick={() => handleBuy(product.id)} - className='flex-1 py-2 btn-solid-red' + className='w-full' + colorScheme='red' > Beli - </button> + </Button> </div> - <div className='flex mt-4'> - <button - className='flex items-center gap-x-1' - onClick={toggleWishlist} - > - {wishlist.data?.productTotal > 0 ? ( - <HeartIcon className='w-6 fill-danger-500 text-danger-500' /> - ) : ( - <HeartIcon className='w-6' /> - )} - Wishlist - </button> + <Button + onClick={() => handleButton(product.id)} + color={'red'} + colorScheme='white' + className='w-full border-2 p-2 gap-1 mt-2 hover:bg-slate-100 flex items-center' + > + <ImageNext + src='/images/writing.png' + alt='penawaran instan' + className='' + width={25} + height={25} + /> + Penawaran Harga Instan + </Button> + <div className='flex py-5'> + <div className='flex gap-x-5 items-center justify-center'> + <Button + as={Link} + href={createdAskUrl} + variant='link' + target='_blank' + colorScheme='gray' + leftIcon={<MessageCircleIcon size={18} />} + > + Ask Admin + </Button> + + <span>|</span> + + <button + className='flex items-center gap-x-1' + onClick={toggleWishlist} + > + {wishlist.data?.productTotal > 0 ? ( + <HeartIcon className='w-6 fill-danger-500 text-danger-500' /> + ) : ( + <HeartIcon className='w-6' /> + )} + Wishlist + </button> + + <span>|</span> + + <RWebShare + data={{ + text: 'Check out this product', + title: `${product.name} - Indoteknik.com`, + url: SELF_HOST + router.asPath, + }} + > + <Button + variant='link' + colorScheme='gray' + leftIcon={<Share2Icon size={18} />} + > + Share + </Button> + </RWebShare> + </div> </div> <div className='border border-gray_r-6 overflow-auto mt-4'> <div className='font-medium text-center p-4 bg-gray_r-1 border-b border-gray_r-6 sticky top-0 z-10'> Produk Serupa </div> - <div className='h-full divide-y divide-gray_r-6 max-h-96'> + <div className='h-full divide-y divide-gray_r-6 max-h-[500px]'> {productSimilarInBrand && productSimilarInBrand?.map((product) => ( <div className='py-2' key={product.id}> @@ -393,8 +554,11 @@ const ProductDesktopVariant = ({ Kamu Mungkin Juga Suka </div> <LazyLoad> - <ProductSimilar query={productSimilarQuery} /> + <SimilarBottom product={product} /> </LazyLoad> + {/* <LazyLoad> + <ProductSimilar query={productSimilarQuery} /> + </LazyLoad> */} </div> <BottomPopup @@ -429,8 +593,11 @@ const ProductDesktopVariant = ({ Kamu Mungkin Juga Suka </div> <LazyLoad> - <ProductSimilar query={productSimilarQuery} /> + <SimilarBottom product={product} /> </LazyLoad> + {/* <LazyLoad> + <ProductSimilar query={productSimilarQuery} /> + </LazyLoad> */} </div> </BottomPopup> </div> diff --git a/src/lib/product/components/Product/ProductMobileVariant.jsx b/src/lib/product/components/Product/ProductMobileVariant.jsx index af9e52bb..b87bcbc8 100644 --- a/src/lib/product/components/Product/ProductMobileVariant.jsx +++ b/src/lib/product/components/Product/ProductMobileVariant.jsx @@ -1,10 +1,10 @@ -import { Skeleton } from '@chakra-ui/react'; +import { Button, Skeleton } from '@chakra-ui/react'; import { HeartIcon } from '@heroicons/react/24/outline'; import { useRouter } from 'next/router'; import { useEffect, useState } from 'react'; import { toast } from 'react-hot-toast'; import LazyLoad from 'react-lazy-load'; - +import ImageNext from 'next/image'; import odooApi from '@/core/api/odooApi'; import Divider from '@/core/components/elements/Divider/Divider'; import Image from '@/core/components/elements/Image/Image'; @@ -16,12 +16,15 @@ import currencyFormat from '@/core/utils/currencyFormat'; import { gtagAddToCart } from '@/core/utils/googleTag'; import { createSlug } from '@/core/utils/slug'; import whatsappUrl from '@/core/utils/whatsappUrl'; - +import { getAuth } from '~/libs/auth'; +import SimilarBottom from '~/modules/product-detail/components/SimilarBottom'; import ProductSimilar from '../ProductSimilar'; const ProductMobileVariant = ({ product, wishlist, toggleWishlist }) => { const router = useRouter(); - + const { slug } = router.query; + const { srsltid } = router.query; + let auth = getAuth(); const [quantity, setQuantity] = useState('1'); const [selectedVariant, setSelectedVariant] = useState(product.id); const [informationTab, setInformationTab] = useState( @@ -73,11 +76,16 @@ const ProductMobileVariant = ({ product, wishlist, toggleWishlist }) => { return isValid; }; - const handleClickCart = () => { + const handleClickCart = async () => { + if (!auth) { + router.push(`/login?next=/shop/product/${slug}?srsltid=${srsltid}`); + return; + } + if (!validAction()) return; gtagAddToCart(activeVariant, quantity); updateItemCart({ - productId: variant, + productId: product.id, quantity, programLineId: null, selected: true, @@ -86,7 +94,33 @@ const ProductMobileVariant = ({ product, wishlist, toggleWishlist }) => { setAddCartAlert(true); }; - const handleClickBuy = () => { + const handleClickBuy = async () => { + let isLoggedIn = typeof auth === 'object'; + + if (!isLoggedIn) { + const currentUrl = encodeURIComponent(router.asPath); + await router.push(`/login?next=${currentUrl}`); + + // Tunggu login berhasil, misalnya dengan memantau perubahan status auth. + const authCheckInterval = setInterval(() => { + const newAuth = getAuth(); + if (typeof newAuth === 'object') { + isLoggedIn = true; + auth = newAuth; // Update nilai auth setelah login + clearInterval(authCheckInterval); + } + }, 500); // Periksa status login setiap 500ms + + await new Promise((resolve) => { + const checkLogin = setInterval(() => { + if (isLoggedIn) { + clearInterval(checkLogin); + resolve(null); + } + }, 500); + }); + } + if (!validAction()) return; updateItemCart({ @@ -99,6 +133,20 @@ const ProductMobileVariant = ({ product, wishlist, toggleWishlist }) => { router.push(`/shop/checkout?source=buy`); }; + const handleButton = (variant) => { + const quantity = quantityInput; + if (!validQuantity(quantity)) return; + + updateItemCart({ + productId: variant, + quantity, + programLineId: null, + selected: true, + source: 'buy', + }); + router.push('/shop/quotation?source=buy'); + }; + const productSimilarQuery = [ product?.name, `fq=-product_id_i:${product.id}`, @@ -149,7 +197,9 @@ const ProductMobileVariant = ({ product, wishlist, toggleWishlist }) => { )} </button> </div> - <h1 className='leading-6 font-medium mb-3'>{activeVariant?.name}</h1> + <h1 className='font-medium text-h-lg leading-8 md:text-title-md md:leading-10 mb-3'> + {activeVariant?.name} + </h1> {activeVariant.isFlashSale && activeVariant?.price?.discountPercentage > 0 ? ( @@ -236,6 +286,21 @@ const ProductMobileVariant = ({ product, wishlist, toggleWishlist }) => { Beli </button> </div> + <Button + onClick={() => handleButton(product.id)} + color={'red'} + colorScheme='white' + className='w-full border-2 p-2 gap-1 mt-2 hover:bg-slate-100 flex items-center' + > + <ImageNext + src='/images/writing.png' + alt='penawaran instan' + className='' + width={25} + height={25} + /> + Penawaran Harga Instan + </Button> </div> <Divider /> @@ -375,8 +440,11 @@ const ProductMobileVariant = ({ product, wishlist, toggleWishlist }) => { <div className='p-4'> <h2 className='font-semibold mb-4'>Kamu Mungkin Juga Suka</h2> <LazyLoad> - <ProductSimilar query={productSimilarQuery} /> + <SimilarBottom product={product} /> </LazyLoad> + {/* <LazyLoad> + <ProductSimilar query={productSimilarQuery} /> + </LazyLoad> */} </div> <BottomPopup @@ -409,8 +477,11 @@ const ProductMobileVariant = ({ product, wishlist, toggleWishlist }) => { Kamu Mungkin Juga Suka </div> <LazyLoad> - <ProductSimilar query={productSimilarQuery} /> + <SimilarBottom product={product} /> </LazyLoad> + {/* <LazyLoad> + <ProductSimilar query={productSimilarQuery} /> + </LazyLoad> */} </div> </BottomPopup> </MobileView> diff --git a/src/lib/quotation/components/Quotation.jsx b/src/lib/quotation/components/Quotation.jsx index cf0ad41f..5a2f63a5 100644 --- a/src/lib/quotation/components/Quotation.jsx +++ b/src/lib/quotation/components/Quotation.jsx @@ -39,9 +39,12 @@ const { getProductsCheckout } = require('@/lib/checkout/api/checkoutApi'); const Quotation = () => { const router = useRouter(); const auth = useAuth(); + const query = router.query.source ?? null; const { data: cartCheckout } = useQuery('cartCheckout', () => - getProductsCheckout() + getProductsCheckout({ + source: query, + }) ); const { setRefreshCart } = useProductCartContext(); diff --git a/src/lib/shipment/components/Shipments.jsx b/src/lib/shipment/components/Shipments.jsx index 115bbd3a..20dbb013 100644 --- a/src/lib/shipment/components/Shipments.jsx +++ b/src/lib/shipment/components/Shipments.jsx @@ -1,62 +1,83 @@ -import DesktopView from '@/core/components/views/DesktopView' -import MobileView from '@/core/components/views/MobileView' -import Menu from '@/lib/auth/components/Menu' -import { EllipsisVerticalIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline' -import ImageNext from 'next/image' -import { useRouter } from 'next/router' -import { useQuery } from 'react-query' -import _, { forEach } from 'lodash-contrib' -import Spinner from '@/core/components/elements/Spinner/Spinner' -import Manifest from '@/lib/treckingAwb/component/Manifest' -import { useState } from 'react' -import Pagination from '@/core/components/elements/Pagination/Pagination' -import Link from 'next/link' -import TransactionStatusBadge from '@/lib/transaction/components/TransactionStatusBadge' +import DesktopView from '@/core/components/views/DesktopView'; +import MobileView from '@/core/components/views/MobileView'; +import Menu from '@/lib/auth/components/Menu'; +import { + EllipsisVerticalIcon, + MagnifyingGlassIcon, +} from '@heroicons/react/24/outline'; +import ImageNext from 'next/image'; +import { useEffect } from 'react'; +import { useRouter } from 'next/router'; +import { useQuery } from 'react-query'; +import _, { forEach } from 'lodash-contrib'; +import Spinner from '@/core/components/elements/Spinner/Spinner'; +import Manifest from '@/lib/treckingAwb/component/Manifest'; +import { useState } from 'react'; +import Pagination from '@/core/components/elements/Pagination/Pagination'; +import Link from 'next/link'; +import TransactionStatusBadge from '@/lib/transaction/components/TransactionStatusBadge'; -const { listShipments } = require('../api/listShipment') +const { listShipments } = require('../api/listShipment'); const Shipments = () => { - const router = useRouter() - const { q = '', page = 1 } = router.query - const [paramStatus, setParamStatus] = useState(null) - - const limit = 15 + const router = useRouter(); + const { q = '', page = 1, status = null } = router.query; + const [paramStatus, setParamStatus] = useState(status); + const limit = 15; const query = { q: q, status: paramStatus, offset: (page - 1) * limit, - limit - } - const [inputQuery, setInputQuery] = useState(q) - const queryString = _.toQuery(query) + limit, + }; + const [inputQuery, setInputQuery] = useState(q); + const queryString = _.toQuery(query); const { data: shipments } = useQuery('shipments' + queryString, () => listShipments({ query: queryString }) - ) - const [idAWB, setIdAWB] = useState(null) + ); + const [idAWB, setIdAWB] = useState(null); - const pageCount = Math.ceil(shipments?.pickingTotal / limit) - let pageQuery = _.omit(query, ['limit', 'offset', 'context']) - pageQuery = _.pickBy(pageQuery, _.identity) - pageQuery = _.toQuery(pageQuery) + const pageCount = Math.ceil(shipments?.pickingTotal / limit); + let pageQuery = _.omit(query, ['limit', 'offset', 'context']); + pageQuery = _.pickBy(pageQuery, _.identity); + pageQuery = _.toQuery(pageQuery); const closePopup = () => { - setIdAWB(null) - } + setIdAWB(null); + }; const handleSubmit = async (e) => { - e.preventDefault() - router.push(`${router.pathname}?q=${inputQuery}`) - } + e.preventDefault(); + router.push(`${router.pathname}?q=${inputQuery}`); + }; const filterStatus = async (status) => { if (status === paramStatus) { - setParamStatus(null) + setParamStatus(null); } else { - setParamStatus(status) + setParamStatus(status); } - } + }; + + useEffect(() => { + const resetQuery = () => { + const newQuery = { + status: paramStatus || undefined, + q: '', + page: 1, + }; + router.push({ + pathname: router.pathname, + query: newQuery, + }); + }; + + if (paramStatus !== status) { + resetQuery(); + } + }, [paramStatus]); return ( <> <MobileView> @@ -84,7 +105,10 @@ const Shipments = () => { </form> {shipments?.pickings.map((shipment) => ( - <div className='p-4 shadow border border-gray_r-3 rounded-md' key={shipment.id}> + <div + className='p-4 shadow border border-gray_r-3 rounded-md' + key={shipment.id} + > <div className='flex justify-between items-center mb-3'> <div className='text-caption-2 text-gray_r-11'> <p> @@ -93,7 +117,9 @@ const Shipments = () => { {shipment.carrierName || '-'} </span> </p> - <p className='mt-2'>No. Resi : {shipment.trackingNumber || '-'}</p> + <p className='mt-2'> + No. Resi : {shipment.trackingNumber || '-'} + </p> </div> <div className='flex justify-between'> {shipment?.status === 'completed' && ( @@ -116,11 +142,17 @@ const Shipments = () => { <hr /> <div className='flex justify-between mt-2 items-center mb-5'> <div> - <span className='text-caption-2 text-gray_r-11'>No. Transaksi</span> + <span className='text-caption-2 text-gray_r-11'> + No. Transaksi + </span> <Link href={`/my/transactions/${shipment.saleOrder.id}`}> - <h2 className='text-danger-500 mt-1 mb-2'>{shipment.saleOrder.name}</h2> + <h2 className='text-danger-500 mt-1 mb-2'> + {shipment.saleOrder.name} + </h2> </Link> - <span className='text-caption-2 text-gray_r-11'>{shipment.date}</span> + <span className='text-caption-2 text-gray_r-11'> + {shipment.date} + </span> </div> <div> <button @@ -136,7 +168,11 @@ const Shipments = () => { onClick={() => setIdAWB(shipment.id)} className='flex items-center mt-1 gap-x-1 min-w-full' > - <ImageNext src={`/images/BOX_DELIVERY_GREEN.svg`} width={20} height={20} /> + <ImageNext + src={`/images/BOX_DELIVERY_GREEN.svg`} + width={20} + height={20} + /> <p className='text-sm text-green-700 truncate'> {shipment.lastManifest.description} </p> @@ -148,7 +184,7 @@ const Shipments = () => { <Pagination pageCount={pageCount} currentPage={parseInt(page)} - url={router.pathname + pageQuery} + url={`${router.pathname}${pageQuery ? '?' + pageQuery : ''}`} className='mt-2 mb-2' /> </div> @@ -176,7 +212,8 @@ const Shipments = () => { <path d='M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z' /> </svg> <div> - Lacak pengiriman untuk setiap transaksi anda semakin mudah di Indoteknik.com + Lacak pengiriman untuk setiap transaksi anda semakin mudah di + Indoteknik.com </div> </div> <div className='flex justify-between gap-x-5'> @@ -190,7 +227,9 @@ const Shipments = () => { </div> <div className='p-4 bg-white border border-gray_r-6 rounded'> <div className='flex mb-6 items-center justify-between'> - <h1 className='text-title-sm font-semibold'>Detail Pengiriman</h1> + <h1 className='text-title-sm font-semibold'> + Detail Pengiriman + </h1> <form className='flex gap-x-2' onSubmit={handleSubmit}> <input type='text' @@ -199,7 +238,10 @@ const Shipments = () => { value={inputQuery} onChange={(e) => setInputQuery(e.target.value)} /> - <button className='btn-light bg-transparent px-3' type='submit'> + <button + className='btn-light bg-transparent px-3' + type='submit' + > <MagnifyingGlassIcon className='w-6' /> </button> </form> @@ -254,7 +296,7 @@ const Shipments = () => { <Pagination pageCount={pageCount} currentPage={parseInt(page)} - url={router.pathname + pageQuery} + url={`${router.pathname}${pageQuery ? '?' + pageQuery : ''}`} className='mt-2 mb-2' /> </div> @@ -263,16 +305,16 @@ const Shipments = () => { <Manifest idAWB={idAWB} closePopup={closePopup} /> </DesktopView> </> - ) -} + ); +}; const CardStatus = ({ device, paramStatus, shipments, filterStatus }) => { - const status = [`pending`, `shipment`, `completed`] + const status = [`pending`, `shipment`, `completed`]; return ( <> {status.map((value) => { - const statusData = getStatusLabel(device, value, shipments) + const statusData = getStatusLabel(device, value, shipments); if (device === 'desktop') { return ( <div @@ -282,13 +324,15 @@ const CardStatus = ({ device, paramStatus, shipments, filterStatus }) => { }`} onClick={() => filterStatus(value)} > - <h2 className='mb-2 text-lg font-bold tracking-tight'>{statusData.label}</h2> + <h2 className='mb-2 text-lg font-bold tracking-tight'> + {statusData.label} + </h2> {statusData.image} <h1 className='text-xl font-bold'> {statusData.shipCount} <span className='text-sm'>Pesanan</span> </h1> </div> - ) + ); } else { return ( <div @@ -305,15 +349,15 @@ const CardStatus = ({ device, paramStatus, shipments, filterStatus }) => { <span className='truncate'>{statusData.shipCount}</span> {'>'} </h1> </div> - ) + ); } })} </> - ) -} + ); +}; const getStatusLabel = (device, status, shipments) => { - let images = null + let images = null; switch (status) { case 'pending': if (device === 'desktop') { @@ -328,40 +372,48 @@ const getStatusLabel = (device, status, shipments) => { /> </div> </div> - ) + ); } else { images = ( <div> <ImageNext src='/images/BOX(1).svg' width={15} height={20} /> </div> - ) + ); } return { label: 'Pending', shipCount: shipments?.summary?.pendingCount, - image: images - } + image: images, + }; case 'shipment': if (device === 'desktop') { images = ( <div className='bg-yellow-100 border border-yellow-200 rounded-sm p-1 w-20 mb-2'> <div> - <ImageNext src='/images/BOX_DELIVER_(1).svg' width={30} height={20} /> + <ImageNext + src='/images/BOX_DELIVER_(1).svg' + width={30} + height={20} + /> </div> </div> - ) + ); } else { images = ( <div> - <ImageNext src='/images/BOX_DELIVER_(1).svg' width={18} height={20} /> + <ImageNext + src='/images/BOX_DELIVER_(1).svg' + width={18} + height={20} + /> </div> - ) + ); } return { label: 'Pengiriman', shipCount: shipments?.summary?.shipmentCount, - image: images - } + image: images, + }; case 'completed': if (device === 'desktop') { images = ( @@ -375,22 +427,22 @@ const getStatusLabel = (device, status, shipments) => { /> </div> </div> - ) + ); } else { images = ( <div> <ImageNext src='/images/open-box(1).svg' width={16} height={20} /> </div> - ) + ); } return { label: 'Pesanan Tiba', shipCount: shipments?.summary?.completedCount, - image: images - } + image: images, + }; default: - return 'Status Tidak Dikenal' + return 'Status Tidak Dikenal'; } -} +}; -export default Shipments +export default Shipments; diff --git a/src/lib/transaction/components/Transaction.jsx b/src/lib/transaction/components/Transaction.jsx index 4d401037..d001c7f4 100644 --- a/src/lib/transaction/components/Transaction.jsx +++ b/src/lib/transaction/components/Transaction.jsx @@ -778,6 +778,10 @@ const Transaction = ({ id }) => { ? `| ${product?.attributes.join(', ')}` : ''} </div> + <div className='text-[10px] text-red-500 italic mt-2'> + {product.availableQuantity} barang ini bisa di + pickup maksimal pukul 16.00 + </div> </div> </td> {/* <td> @@ -879,7 +883,7 @@ const Transaction = ({ id }) => { </div> </div> </div> - )} + )} {transaction?.data?.productsRejectLine.length > 0 && ( <div className='text-h-sm font-semibold mt-10 mb-4'> diff --git a/src/lib/variant/components/VariantCard.jsx b/src/lib/variant/components/VariantCard.jsx index 68cdf54f..08b7a97e 100644 --- a/src/lib/variant/components/VariantCard.jsx +++ b/src/lib/variant/components/VariantCard.jsx @@ -103,30 +103,42 @@ const VariantCard = ({ product, openOnClick = true, buyMore = false }) => { </div> </div> </div> - </div> <div className='w-8/12 flex flex-col'> - <p className='product-card__title wrap-line-ellipsis-2'>{product.parent.name}</p> + <p className='product-card__title wrap-line-ellipsis-2'> + {product.parent.name} + </p> <p className='text-caption-2 text-gray_r-11 mt-1'> {product.code || '-'} - {product.attributes.length > 0 ? ` ・ ${product.attributes.join(', ')}` : ''} + {product.attributes.length > 0 + ? ` ・ ${product.attributes.join(', ')}` + : ''} </p> <p className='text-caption-2 text-gray_r-11 mt-1'> Berat Item : {product?.weight} Kg x {product?.quantity} Barang </p> + <p className='text-[10px] text-red-500 italic mt-2'> + {product.availableQuantity} barang ini bisa di pickup maksimal pukul + 16.00 + </p> <div className='flex flex-wrap gap-x-1 items-center mt-auto'> {product.hasFlashsale && ( <> <p className='text-caption-2 text-gray_r-11 line-through'> {currencyFormat(product.price.price)} </p> - <span className='badge-red'>{product.price.discountPercentage}%</span> + <span className='badge-red'> + {product.price.discountPercentage}% + </span> </> )} </div> <p className='text-caption-2 text-gray_r-11 mt-1'> {product.price.priceDiscount > 0 - ? currencyFormat(product.price.priceDiscount) + ' × ' + product.quantity + ' Barang' + ? currencyFormat(product.price.priceDiscount) + + ' × ' + + product.quantity + + ' Barang' : ''} </p> <p className='text-caption-2 text-gray_r-12 font-bold mt-2'> diff --git a/src/pages/_app.jsx b/src/pages/_app.jsx index bcb41dd6..f52aa5f7 100644 --- a/src/pages/_app.jsx +++ b/src/pages/_app.jsx @@ -85,7 +85,7 @@ function MyApp({ Component, pageProps: { session, ...pageProps } }) { return ( <SessionProvider session={session}> <ScrollToTop /> - + <AnimatePresence> {animateLoader && ( <motion.div diff --git a/src/pages/api/shop/search.js b/src/pages/api/shop/search.js index 49a5fe69..ace281f7 100644 --- a/src/pages/api/shop/search.js +++ b/src/pages/api/shop/search.js @@ -88,7 +88,10 @@ export default async function handler(req, res) { 'price_tier1_v2_f:[1 TO *]', ]; - const fq_ = filterQueries.join('AND '); + if (fq && source != 'similar') { + filterQueries.push(fq); + } + const fq_ = filterQueries.join(' AND '); let offset = (page - 1) * limit; let parameter = [ @@ -106,7 +109,7 @@ export default async function handler(req, res) { : formattedQuery }`, `defType=edismax`, - 'qf=name_s description_clean_t category_name manufacture_name_s variants_code_t variants_name_t category_id_ids default_code_s', + 'qf=name_s description_clean_t category_name manufacture_name_s variants_code_t variants_name_t category_id_ids default_code_s manufacture_id_i category_id_i ', `start=${parseInt(offset)}`, `rows=${limit}`, `sort=${paramOrderBy}`, @@ -149,7 +152,7 @@ export default async function handler(req, res) { if (stock) parameter.push(`fq=stock_total_f:{1 TO *}`); // Single fq in url params - if (typeof fq === 'string') parameter.push(`fq=${encodeURIComponent(fq)}`); + // if (typeof fq === 'string') parameter.push(`fq=${encodeURIComponent(fq)}`); // Multi fq in url params if (Array.isArray(fq)) parameter = parameter.concat( diff --git a/src/pages/api/shop/url-category_brand.js b/src/pages/api/shop/url-category_brand.js new file mode 100644 index 00000000..160aa166 --- /dev/null +++ b/src/pages/api/shop/url-category_brand.js @@ -0,0 +1,20 @@ +import axios from 'axios'; + +export default async function handler(req, res) { + const { url = '', page = 1, limit = 30 } = req.query; + + let offset = (page - 1) * limit; + + const params = [`q.op=AND`, `q=${url ? `"${url}"` : '*'}`, `indent=true`, `rows=${limit}`, `start=${offset}`]; + + try { + let result = await axios( + process.env.SOLR_HOST + + `/solr/url_category_brand/select?` + + params.join('&') + ); + res.status(200).json(result.data); + } catch (error) { + res.status(500).json({ error: 'Internal Server Error' }); + } +} diff --git a/src/pages/api/shop/variant-detail.js b/src/pages/api/shop/variant-detail.js index 08ce75b8..af3525b3 100644 --- a/src/pages/api/shop/variant-detail.js +++ b/src/pages/api/shop/variant-detail.js @@ -1,21 +1,28 @@ -import { productMappingSolr, variantsMappingSolr } from '@/utils/solrMapping' -import axios from 'axios' +import { productMappingSolr, variantsMappingSolr } from '@/utils/solrMapping'; +import axios from 'axios'; export default async function handler(req, res) { try { let productVariants = await axios( process.env.SOLR_HOST + `/solr/variants/select?q=id:${req.query.id}&q.op=OR&indent=true` - ) - let auth = req.query.auth === 'false' ? JSON.parse(req.query.auth) : req.query.auth + ); + let template_id = productVariants.data.response.docs[0].template_id_i; + let auth = + req.query.auth === 'false' ? JSON.parse(req.query.auth) : req.query.auth; let productTemplate = await axios( - process.env.SOLR_HOST + `/solr/product/select?q=id:${req.query.id}&q.op=OR&indent=true` - ) - let result = variantsMappingSolr(productTemplate.data.response.docs, productVariants.data.response.docs, auth || false) - - res.status(200).json(result) + process.env.SOLR_HOST + + `/solr/product/select?q=id:${template_id}&q.op=OR&indent=true` + ); + let result = variantsMappingSolr( + productTemplate.data.response.docs, + productVariants.data.response.docs, + auth || false + ); + + res.status(200).json(result); } catch (error) { - console.error('Error fetching data from Solr:', error) - res.status(500).json({ error: 'Internal Server Error' }) + console.error('Error fetching data from Solr:', error); + res.status(500).json({ error: 'Internal Server Error' }); } -}
\ No newline at end of file +} diff --git a/src/pages/garansi-resmi.jsx b/src/pages/garansi-resmi.jsx new file mode 100644 index 00000000..7384a89d --- /dev/null +++ b/src/pages/garansi-resmi.jsx @@ -0,0 +1,13 @@ +import Seo from '@/core/components/Seo' +import BasicLayout from '@/core/components/layouts/BasicLayout' +import IframeContent from '@/lib/iframe/components/IframeContent' + +export default function GaransiResmi() { + return ( + <BasicLayout> + <Seo title='Garansi Resmi - Indoteknik.com' /> + + <IframeContent url={`${process.env.NEXT_PUBLIC_ODOO_HOST}/content?url=garansi-resmi`} /> + </BasicLayout> + ) +} diff --git a/src/pages/my/address/[id]/edit.jsx b/src/pages/my/address/[id]/edit.jsx index c126b290..19d7af41 100644 --- a/src/pages/my/address/[id]/edit.jsx +++ b/src/pages/my/address/[id]/edit.jsx @@ -46,6 +46,6 @@ export async function getServerSideProps(context) { subDistrict: '', business_name: '', }; - console.log('ini default',defaultValues); + // console.log('ini default',defaultValues); return { props: { id, defaultValues } }; } diff --git a/src/pages/pembayaran-tempo.jsx b/src/pages/pembayaran-tempo.jsx new file mode 100644 index 00000000..363e3099 --- /dev/null +++ b/src/pages/pembayaran-tempo.jsx @@ -0,0 +1,13 @@ +import Seo from '@/core/components/Seo' +import BasicLayout from '@/core/components/layouts/BasicLayout' +import IframeContent from '@/lib/iframe/components/IframeContent' + +export default function PembnayaranTempo() { + return ( + <BasicLayout> + <Seo title='Pambayaran Tempo - Indoteknik.com' /> + + <IframeContent url={`${process.env.NEXT_PUBLIC_ODOO_HOST}/content?url=pembayaran-tempo`} /> + </BasicLayout> + ) +} diff --git a/src/pages/shop/find/[slug].jsx b/src/pages/shop/find/[slug].jsx new file mode 100644 index 00000000..268b1e56 --- /dev/null +++ b/src/pages/shop/find/[slug].jsx @@ -0,0 +1,69 @@ +import axios from 'axios'; +import { useRouter } from 'next/router'; +import { useEffect, useState } from 'react'; +import Seo from '@/core/components/Seo'; +import dynamic from 'next/dynamic'; +import { get } from 'lodash-contrib'; +import { getIdFromSlug, getNameFromSlug } from '@/core/utils/slug'; +import { capitalizeEachWord } from '../../../utils/capializeFIrstWord'; + +const BasicLayout = dynamic(() => + import('@/core/components/layouts/BasicLayout') +); +const ProductSearch = dynamic(() => + import('@/lib/product/components/ProductSearch') +); + +const BASE_URL = 'https://indoteknik.com'; +export default function FindPage() { + const route = useRouter(); + const qSlug = route?.query?.slug || null; + const url = BASE_URL + route.asPath.split('?')[0]; + const [result, setResult] = useState(null); + const [query, setQuery] = useState(null); + + const __slug = qSlug ? getNameFromSlug(route?.query?.slug) +' '+ getIdFromSlug(route?.query?.slug) : ''; + const slug = capitalizeEachWord(__slug); + + const getUrls = async (url) => { + try { + let response = await axios( + `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/url-category_brand?url=${url}` + ); + let result = response?.data?.response?.docs[0] || null; + setResult(result); + } catch (error) { + console.error('Error fetching data:', error); + } + }; + + useEffect(() => { + getUrls(url); + }, []); + + useEffect(() => { + if (result) { + let fq = `category_parent_ids:${result.category_id_i} AND manufacture_id_i:${result.brand_id_i}`; + setQuery({ + fq: fq, + }); + } + }, [result]); + + return ( + <BasicLayout> + <Seo + title={`Beli ${slug} Original & Harga Terjangkau - indoteknik.com`} + description={`Beli ${slug} Kirim Jakarta Surabaya Semarang Makassar Manado Denpasar Balikpapan Medan Palembang Lampung Bali Bandung Makassar Manado.`} + additionalMetaTags={[ + { + property: 'keywords', + content: `Beli ${slug}, harga ${slug}, ${slug} murah, toko ${slug}, ${slug} jakarta, ${slug} surabaya`, + + }, + ]} + /> + {query && <ProductSearch query={query} prefixUrl={`${route.asPath}`} />} + </BasicLayout> + ); +} diff --git a/src/pages/shop/product/variant/[slug].jsx b/src/pages/shop/product/variant/[slug].jsx index 42f38774..2c0dd64b 100644 --- a/src/pages/shop/product/variant/[slug].jsx +++ b/src/pages/shop/product/variant/[slug].jsx @@ -32,16 +32,9 @@ export async function getServerSideProps(context) { tier ); let product = response.data; - // let product = await variantApi({ id: getIdFromSlug(slug), headers: { Token: authToken } }) if (product?.length == 1) { product = product[0]; - /* const regexHtmlTags = /(<([^>]+)>)/gi - const regexHtmlTagsExceptP = /<\/?(?!p\b)[^>]*>/g - product.description = product.description - .replace(regexHtmlTagsExceptP, ' ') - .replace(regexHtmlTags, ' ') - .trim()*/ } else { product = null; } diff --git a/src/pages/sitemap/categories-brand.xml.js b/src/pages/sitemap/categories-brand.xml.js new file mode 100644 index 00000000..b23363e9 --- /dev/null +++ b/src/pages/sitemap/categories-brand.xml.js @@ -0,0 +1,35 @@ +import productSearchApi from '@/lib/product/api/productSearchApi' +import { create } from 'xmlbuilder' +import _ from 'lodash-contrib' +import axios from 'axios' + +export async function getServerSideProps({ res }) { + const baseUrl = process.env.SELF_HOST + '/sitemap/categories-brand' + const limit = 500 + const categories = await axios( + `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/url-category_brand?limit=${limit}` + ) + const pageCount = Math.ceil(categories.data.response.numFound / limit) + const pages = Array.from({ length: pageCount }, (_, i) => i + 1) + const sitemapIndex = create('sitemapindex', { encoding: 'UTF-8' }).att( + 'xmlns', + 'http://www.sitemaps.org/schemas/sitemap/0.9' + ) + + const date = new Date() + pages.forEach((page) => { + const sitemap = sitemapIndex.ele('sitemap') + sitemap.ele('loc', `${baseUrl}/${page}.xml`) + sitemap.ele('lastmod', date.toISOString().slice(0, 10)) + }) + + res.setHeader('Content-Type', 'text/xml') + res.write(sitemapIndex.end()) + res.end() + + return { props: {} } +} + +export default function SitemapProducts() { + return null +} diff --git a/src/pages/sitemap/categories-brand/[page].js b/src/pages/sitemap/categories-brand/[page].js new file mode 100644 index 00000000..6b55e426 --- /dev/null +++ b/src/pages/sitemap/categories-brand/[page].js @@ -0,0 +1,43 @@ + +import productSearchApi from '@/lib/product/api/productSearchApi' +import { create } from 'xmlbuilder' +import _ from 'lodash-contrib' +import { createSlug } from '@/core/utils/slug' +import axios from 'axios' + +export async function getServerSideProps({ query, res }) { + const baseUrl = process.env.SELF_HOST + '/shop/product/' + const { page } = query + const limit = 500 + const categories = await axios( + `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/url-category_brand?limit=${limit}&page=${page.replace( + '.xml', + '' + )}` + ) + + const sitemap = create('urlset', { encoding: 'utf-8' }).att( + 'xmlns', + 'http://www.sitemaps.org/schemas/sitemap/0.9' + ) + + const date = new Date() + categories.data.response.docs.forEach((product) => { + const url = sitemap.ele('url') + const loc = product.url_s; + url.ele('loc', loc) + url.ele('lastmod', date.toISOString().slice(0, 10)) + url.ele('changefreq', 'daily') + url.ele('priority', '0.8') + }) + + res.setHeader('Content-Type', 'text/xml') + res.write(sitemap.end()) + res.end() + + return { props: {} } +} + +export default function SitemapProducts() { + return null +} diff --git a/src/utils/capializeFIrstWord.js b/src/utils/capializeFIrstWord.js new file mode 100644 index 00000000..b62d0c06 --- /dev/null +++ b/src/utils/capializeFIrstWord.js @@ -0,0 +1,9 @@ +export const capitalizeEachWord = (str) => { + return str + .split(' ') // Pisahkan string menjadi array kata-kata + .map((word) => // Ubah huruf pertama setiap kata menjadi besar + word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() + ) + .join(' '); // Gabungkan kembali menjadi string + }; +
\ No newline at end of file diff --git a/src/utils/solrMapping.js b/src/utils/solrMapping.js index f73e966a..f896a6a8 100644 --- a/src/utils/solrMapping.js +++ b/src/utils/solrMapping.js @@ -74,6 +74,7 @@ export const productMappingSolr = (products, pricelist) => { name: product.manufacture_name_s || '', imagePromotion1: product.image_promotion_1_s || '', imagePromotion2: product.image_promotion_2_s || '', + logo : product.x_logo_manufacture_s || '', }; } @@ -133,6 +134,7 @@ export const variantsMappingSolr = (parent, products, pricelist) => { productMapped.manufacture = { id: product.manufacture_id_i || '', name: product.manufacture_name_s || '', + logo : parent[0]?.x_logo_manufacture_s }; } productMapped.parent = { |
