import Alert from '@/core/components/elements/Alert/Alert'; import Divider from '@/core/components/elements/Divider/Divider'; import Link from '@/core/components/elements/Link/Link'; import useAuth from '@/core/hooks/useAuth'; import CartApi from '@/lib/cart/api/CartApi'; import { ExclamationCircleIcon } from '@heroicons/react/24/outline'; import { useEffect, useRef, useState } from 'react'; import _ from 'lodash'; import { deleteItemCart, getCart, getItemCart } from '@/core/utils/cart'; import currencyFormat from '@/core/utils/currencyFormat'; import { toast } from 'react-hot-toast'; import { useProductCartContext } from '@/contexts/ProductCartContext'; import { useRouter } from 'next/router'; import VariantGroupCard from '@/lib/variant/components/VariantGroupCard'; import MobileView from '@/core/components/views/MobileView'; import DesktopView from '@/core/components/views/DesktopView'; import Image from '@/core/components/elements/Image/Image'; import { useQuery } from 'react-query'; import CardProdcuctsList from '@/core/components/elements/Product/cartProductsList'; import { Skeleton } from '@chakra-ui/react'; import { useAddress } from '@/lib/checkout/stores/useAdress'; import { useCheckout } from '@/lib/checkout/stores/stateCheckout'; import { PickupAddress, SectionAddress, SectionValidation, calculateEstimatedArrival, splitDuration, } from '../../checkout/components/CheckoutSection'; import addressesApi from '@/lib/address/api/addressesApi'; import { getItemAddress } from '@/core/utils/address'; import ExpedisiList from '../../checkout/api/ExpedisiList'; import SectionQuotationExpedition from '@/lib/checkout/components/SectionQuotationExpedition'; import { useQuotation } from '@/lib/checkout/stores/stateQuotation'; const { checkoutApi } = require('@/lib/checkout/api/checkoutApi'); const { getProductsCheckout } = require('@/lib/checkout/api/checkoutApi'); const Quotation = () => { const PPN = process.env.NEXT_PUBLIC_PPN ? parseFloat(process.env.NEXT_PUBLIC_PPN) : 0; const router = useRouter(); const auth = useAuth(); const query = router.query.source ?? null; const { data: cartCheckout } = useQuery('cartCheckout', () => getProductsCheckout({ source: query, }) ); const { setRefreshCart } = useProductCartContext(); const SELF_PICKUP_ID = 32; const [totalAmount, setTotalAmount] = useState(0); const [totalDiscountAmount, setTotalDiscountAmount] = useState(0); const [isApproval, setIsApproval] = useState(false); const [note_websiteText, setselectedNote_websiteText] = useState(''); const [isLoading, setIsLoading] = useState(false); const [etdFix, setEtdFix] = useState(null); const { selectedAddress, setSelectedAddress, addresses, setAddresses, setAddressMaps, setCoordinate, setPostalCode, } = useAddress(); const { products, setProducts, checkWeigth, setCheckWeight, checkoutValidation, setCheckoutValidation, biayaKirim, etd, unit, selectedCourier, selectedCourierId, selectedService, listExpedisi, setExpedisi, productSla, setProductSla, setBiayaKirim, setUnit, setEtd, setSelectedCourier, setSelectedService, setSelectedCourierId } = useQuotation(); useEffect(() => { if (!auth) return; const getAddresses = async () => { const dataAddresses = await addressesApi(); setAddresses(dataAddresses); }; getAddresses(); setIsApproval(auth?.feature?.soApproval); }, [auth]); useEffect(() => { if (!addresses) return; const matchAddress = (key) => { if (key === 'invoicing') { key = 'invoice'; } const addressToMatch = getItemAddress(key); const foundAddress = addresses.filter( (address) => address.id == addressToMatch ); if (foundAddress.length > 0) { return foundAddress[0]; } return addresses[0]; }; let ship = matchAddress('shipping'); setSelectedAddress({ shipping: matchAddress('shipping'), invoicing: matchAddress('invoicing'), }); setPostalCode(ship?.zip); if (ship?.addressMap) { setAddressMaps(ship?.addressMap); setCoordinate({ destination_latitude: ship?.latitude, destination_longitude: ship?.longtitude, }); } }, [addresses]); useEffect(() => { const loadExpedisi = async () => { let dataExpedisi = await ExpedisiList(); dataExpedisi = dataExpedisi.map((expedisi) => ({ value: expedisi.id, label: expedisi.name, carrierId: expedisi.deliveryCarrierId, logo: expedisi.image, })); setExpedisi(dataExpedisi); }; loadExpedisi(); const handlePopState = () => { router.push('/shop/cart'); }; window.onpopstate = handlePopState; return () => { window.onpopstate = null; }; }, []); useEffect(() => { if (isApproval) { setSelectedCourierId(1); setSelectedCourier('indoteknik'); } }, [isApproval]); useEffect(() => { if (cartCheckout) { setProducts(cartCheckout?.products); setCheckWeight(cartCheckout?.hasProductWithoutWeight); } }, [cartCheckout]); useEffect(() => { if (products) { const calculateTotals = () => { let calculateTotalAmount = 0; let calculateTotalDiscountAmount = 0; products.forEach((product) => { calculateTotalAmount += product.price.price * product.quantity; calculateTotalDiscountAmount += (product.price.price - product.price.priceDiscount) * product.quantity; }); setTotalAmount(calculateTotalAmount); setTotalDiscountAmount(calculateTotalDiscountAmount); }; calculateTotals(); } }, [products]); useEffect(() => { if (etd) { setEtdFix(calculateEstimatedArrival(etd)); } }, [etd]); const checkout = async () => { // Validation if (!selectedCourierId && !isApproval) { setCheckoutValidation(true); toast.error('Silahkan pilih ekspedisi'); return; } if (selectedCourierId !== SELF_PICKUP_ID && biayaKirim === 0 && !isApproval) { toast.error('Maaf, layanan tidak tersedia. Mohon pilih expedisi lain.'); return; } if (!products || products.length === 0) return; if (isApproval && note_websiteText === '') { toast.error('Maaf, Note wajib dimasukkan.'); return; } setIsLoading(true); try { const productOrder = products.map((product) => ({ product_id: product.id, quantity: product.quantity, })); const data = { partner_shipping_id: selectedAddress.shipping.id, partner_invoice_id: selectedAddress.invoicing.id, user_id: auth.id, order_line: JSON.stringify(productOrder), delivery_amount: biayaKirim, carrier_id: selectedCourierId, estimated_arrival_days: splitDuration(etd), delivery_service_type: selectedService?.service_type || selectedCourier, note_website: note_websiteText, }; const isSuccess = await checkoutApi({ data }); if (isSuccess?.id) { for (const product of products) { deleteItemCart({ productId: product.id }); } router.push(`/shop/quotation/finish?id=${isSuccess.id}`); setRefreshCart(true); } else { toast.error('Gagal melakukan transaksi, terjadi kesalahan internal'); } } catch (error) { toast.error('Terjadi kesalahan saat memproses quotation'); } finally { setIsLoading(false); } }; const taxTotal = (totalAmount - totalDiscountAmount) * (PPN - 1); return ( <>
Jika mengalami kesulitan dalam melakukan pembelian di website Indoteknik. Hubungi kami disini
{selectedCourierId == SELF_PICKUP_ID && (
Info
Fitur Self Pickup, hanya berlaku untuk customer di area jakarta. Apa bila memilih fitur ini, anda akan dihubungi setelah barang siap diambil.
)} {selectedCourierId == SELF_PICKUP_ID && ( )} {selectedCourierId != SELF_PICKUP_ID && ( )}
{products && ( )}
Ringkasan Penawaran
{products?.length} Barang

Total Belanja
{currencyFormat(cartCheckout?.totalPurchase)}
Diskon Produk
- {currencyFormat(cartCheckout?.totalDiscount)}
Subtotal
{currencyFormat(cartCheckout?.subtotal)}
PPN {((PPN - 1) * 100).toFixed(0)}%
{currencyFormat(cartCheckout?.tax)}
Biaya Kirim

{etdFix}

{currencyFormat( Math.round(parseInt(biayaKirim * 1.1) / 1000) * 1000 )}

Grand Total
{currencyFormat( cartCheckout?.grandTotal + Math.round(parseInt(biayaKirim * 1.1) / 1000) * 1000 )}

*) Belum termasuk biaya pengiriman

Dengan melakukan pembelian melalui website Indoteknik, saya menyetujui{' '} Syarat & Ketentuan {' '} yang berlaku


Note
{isApproval && (
*harus diisi
)}