import Link from '@/core/components/elements/Link/Link' import useCart from '../hooks/useCart' import Image from '@/core/components/elements/Image/Image' import NextImage from 'next/image' import currencyFormat from '@/core/utils/currencyFormat' import { useEffect, useState } from 'react' import { addCart, deleteItemCart, getCartApi, updateItemCart } from '@/core/utils/cart' import { CheckIcon, TrashIcon } from '@heroicons/react/24/outline' import { createSlug } from '@/core/utils/slug' import { useRouter } from 'next/router' import BottomPopup from '@/core/components/elements/Popup/BottomPopup' import { toast } from 'react-hot-toast' import Spinner from '@/core/components/elements/Spinner/Spinner' import Alert from '@/core/components/elements/Alert/Alert' import MobileView from '@/core/components/views/MobileView' import DesktopView from '@/core/components/views/DesktopView' import ProductCard from '@/lib/product/components/ProductCard' import productSearchApi from '@/lib/product/api/productSearchApi' import whatsappUrl from '@/core/utils/whatsappUrl' import useAuth from '@/core/hooks/useAuth' import LogoSpinner from '@/core/components/elements/Spinner/LogoSpinner' import { getPromotionProgram } from '@/lib/promotinProgram/api/homepageApi' import PromotionType from '@/lib/promotinProgram/components/PromotionType' import { gtagBeginCheckout } from '@/core/utils/googleTag' import { useProductCartContext } from '@/contexts/ProductCartContext' import CardProdcuctsList from '@/core/components/elements/Product/cartProductsList' // import cardProdcuctsList from '@/core/components/elements/Product/cartProductsList' const Cart = () => { const PPN = process.env.NEXT_PUBLIC_PPN const router = useRouter() const [products, setProducts] = useState(null) const [isLoading, setIsLoading] = useState(true) const auth = useAuth() const [cart, setCart] = useState(null) const { setRefreshCart } = useProductCartContext() useEffect(() => { if (!auth) return }, [auth]) const getCart = async () => { const listCart = await getCartApi() setCart(listCart) } useEffect(() => { getCart() }, []) useEffect(() => { if (cart) { const processProducts = async () => { const updatedProducts = await Promise.all( cart.products.map(async (product) => { const id = product.id const program = await getPromotionProgram({ id }) const isPromo = program.length > 0 ? 1 : 0 return { ...product, isPromo } }) ) setProducts(updatedProducts) } // processProducts() setProducts(cart.products) setIsLoading(false) } }, [cart]) const [totalPriceBeforeTax, setTotalPriceBeforeTax] = useState(0) const [totalTaxAmount, setTotalTaxAmount] = useState(0) const [totalDiscountAmount, setTotalDiscountAmount] = useState(0) const [deleteConfirmation, setDeleteConfirmation] = useState(null) const [productRecomendation, setProductRecomendation] = useState(null) const [promotionType, setPromotionType] = useState(null) const [variantId, setVariantId] = useState(null) const [quantity, setQuantity] = useState(null) const [promotionActiveId, setPromotionActiveId] = useState(null) useEffect(() => { if (!products) return let calculateTotalPriceBeforeTax = 0 let calculateTotalTaxAmount = 0 let calculateTotalDiscountAmount = 0 for (const product of products) { if (product.quantity == '') continue if (!product.selected) continue if (product.canBuy == false) { toggleSelected(product.id) } let priceBeforeTax = product.price.price / PPN calculateTotalPriceBeforeTax += priceBeforeTax * product.quantity calculateTotalTaxAmount += (product.price.price - priceBeforeTax) * product.quantity calculateTotalDiscountAmount += (product.price.price - product.price.priceDiscount) * product.quantity } setTotalPriceBeforeTax(calculateTotalPriceBeforeTax) setTotalTaxAmount(calculateTotalTaxAmount) setTotalDiscountAmount(calculateTotalDiscountAmount) }, [products]) useEffect(() => { const updateData = () => { updateItemCart({ productId: variantId, quantity, programLineId: promotionActiveId, selected: true }).then(() => { getCart().then(() => { if (promotionActiveId) { setPromotionType(false) } }) }) } updateData() }, [promotionActiveId]) useEffect(() => { const LoadProductSimilar = async () => { const randProductIndex = Math.floor(Math.random() * products.length) const productLoad = await productSearchApi({ query: `q=${products?.[randProductIndex].parent.name}&limit=10&operation=OR` }) setProductRecomendation(productLoad) } if (products?.length > 0 && !productRecomendation) LoadProductSimilar() }, [products, productRecomendation]) const updateQuantity = (value, productId, operation = '') => { let productIndex = products.findIndex((product) => product.id == productId) if (productIndex < 0) return let productsToUpdate = products let quantity = productsToUpdate[productIndex].quantity if (value != '' && isNaN(parseInt(value))) return value = value != '' ? parseInt(value) : '' switch (operation) { case 'PLUS': quantity += value break case 'MINUS': if (quantity - value < 1) return quantity -= value break case 'BLUR': if (value != '' && value > 0) return quantity = 1 break default: quantity = value != '' && value < 1 ? 1 : value break } let qty = quantity productsToUpdate[productIndex].quantity = qty setProducts([...productsToUpdate]) addCart( productId, qty, productsToUpdate[productIndex].selected, productsToUpdate[productIndex].program?.id ) } const toggleSelected = (productId) => { let productIndex = products.findIndex((product) => product.id == productId) if (productIndex < 0) return let productsToUpdate = products let isSelected = !productsToUpdate[productIndex].selected productsToUpdate[productIndex].selected = isSelected setProducts([...productsToUpdate]) addCart( productId, productsToUpdate[productIndex].quantity, isSelected, productsToUpdate[productIndex].program?.id ) } const selectedProduct = () => { if (!products) return [] return products?.filter((product) => product?.selected == true) } const deleteProduct = (productId) => { const productsToUpdate = products.filter((product) => product.id != productId) deleteItemCart({ productId }) setDeleteConfirmation(null) setProducts([...productsToUpdate]) setRefreshCart(true) toast.success('Berhasil menghapus barang dari keranjang') } const handlePopUpPromo = (variantId, quantity, promoId = null) => { setPromotionType(true) setVariantId(variantId) setQuantity(quantity) setPromotionActiveId(promoId) } const handleCheckout = () => { gtagBeginCheckout(products) router.push('/shop/checkout') } const totalOrder = totalPriceBeforeTax - totalDiscountAmount + totalTaxAmount const tax = totalOrder * 0.11 const totalPrice = totalOrder + tax return ( <> setDeleteConfirmation(null)} title='Hapus dari Keranjang' >
Apakah anda yakin menghapus barang{' '} {deleteConfirmation?.name} dari keranjang?
setPromotionType(false)} >

Keranjang

Cari Produk Lain
{isLoading && (
)} {!isLoading && (!products || products?.length == 0) && (
Keranjang belanja anda masih kosong
)} {products && products?.map((product) => ( <> {product.hasProgram > 0 && (
{product.program ? ( <>
{product.program.type.label}
{product.program.type.value == 'merchandise' ? ( <>Selamat anda mendapatkan merchandise indoteknik.com ) : ( <> Selamat! Pembelian anda hemat {' '} {currencyFormat(product.program?.totalSavings)} )}
) : ( <>
Promo
Pilih Promo Yang Tersedia Bisa lebih Hemat
)}
handlePopUpPromo(product.id, product.quantity, product.program?.id) } className='ml-auto text-red-500 flex gap-x-0 cursor-pointer' >
{' '} Cek Promo
)}
toggleSelected(product.id)} checked={product?.selected} className='mr-2 accent-danger-500 w-4' /> {product?.name}
{product?.parent?.name}
{product?.code}{' '} {product?.attributes.length > 0 ? `| ${product?.attributes.join(', ')}` : ''}
{product?.price?.discountPercentage > 0 && (
{currencyFormat(product?.price?.price)}
{product?.price?.discountPercentage}%
)}
{currencyFormat(product?.price?.priceDiscount)}
{currencyFormat(product?.price?.priceDiscount * product?.quantity)}
updateQuantity(e.target.value, product?.id)} onBlur={(e) => updateQuantity(e.target.value, product?.id, 'BLUR')} />
{product.program && product.program.items && product.program.items.map((item) => (
{item?.name}
{product.program.type.label}
{item.name}
{item.price?.discountPercentage > 0 && (
{currencyFormat(item?.price?.price)}
)}
Gratis
))} ))}
Total Pesanan {currencyFormat(totalOrder)}
PPN 11% {currencyFormat(tax)}

Total Harga: {currencyFormat(totalPrice)}

Keranjang

Tanya stock untuk pembelian anda sebelum melanjutkan pembayaran! {' '} Hubungi Kami

Ringkasan Belanja

Total Pesanan {currencyFormat(totalOrder)}
PPN 11% {currencyFormat(tax)}

Total Harga: {currencyFormat(totalPrice)}

Produk Yang Mungkin Kamu Suka

{productRecomendation && productRecomendation.response.products.map((product) => ( ))}
) } const ComponentCanBuy = ({ canBuy }) => !canBuy &&
export default Cart