From 337e7a189efacbe696f4512130278952977b2da2 Mon Sep 17 00:00:00 2001 From: Miqdad Date: Wed, 11 Jun 2025 16:37:19 +0700 Subject: fix checkout --- src/lib/checkout/components/Checkout.jsx | 327 ++++++++++--------------------- 1 file changed, 105 insertions(+), 222 deletions(-) (limited to 'src/lib/checkout/components/Checkout.jsx') diff --git a/src/lib/checkout/components/Checkout.jsx b/src/lib/checkout/components/Checkout.jsx index f6889558..668c7ac0 100644 --- a/src/lib/checkout/components/Checkout.jsx +++ b/src/lib/checkout/components/Checkout.jsx @@ -28,9 +28,14 @@ import getFileBase64 from '@/core/utils/getFileBase64'; import { gtagPurchase } from '@/core/utils/googleTag'; import whatsappUrl from '@/core/utils/whatsappUrl'; import addressesApi from '@/lib/address/api/addressesApi'; +import { MapPinIcon } from 'lucide-react'; import CartItem from '~/modules/cart/components/Item.tsx'; import ExpedisiList from '../api/ExpedisiList'; -import { findVoucher, getVoucher, getVoucherNew } from '../api/getVoucher'; +import { getVoucher } from '../api/getVoucher'; +import { useAddress } from '../stores/useAdress'; +import SectionExpedition from './SectionExpedition'; +import { useCheckout } from '../stores/stateCheckout'; +import { formatShipmentRange, getToDate } from '../utils/functionCheckouit'; const SELF_PICKUP_ID = 32; @@ -50,9 +55,7 @@ function convertToInternational(number) { } const Checkout = () => { - const PPN = process.env.NEXT_PUBLIC_PPN - ? parseFloat(process.env.NEXT_PUBLIC_PPN) - : 0; + const PPN = process.env.NEXT_PUBLIC_PPN ? parseFloat(process.env.NEXT_PUBLIC_PPN) : 0; const router = useRouter(); const query = router.query.source ?? null; const qVoucher = router.query.voucher ?? null; @@ -68,14 +71,21 @@ const Checkout = () => { source: query, voucher: activeVoucher, voucher_shipping: activeVoucherShipping, - }) + }), + { + keepPreviousData: true, // Menjaga data sebelumnya sampai data baru tersedia + } ); - const [selectedAddress, setSelectedAddress] = useState({ - shipping: null, - invoicing: null, - }); - const [addresses, setAddresses] = useState(null); + const { + selectedAddress, + setSelectedAddress, + addresses, + setAddresses, + setAddressMaps, + setCoordinate, + setPostalCode, + } = useAddress(); useEffect(() => { if (!auth) return; @@ -105,26 +115,32 @@ const Checkout = () => { 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]); - const [products, setProducts] = useState(null); const [totalWeight, setTotalWeight] = useState(0); const [priceCheck, setPriceCheck] = useState(false); - const [listExpedisi, setExpedisi] = useState([]); const [listserviceExpedisi, setListServiceExpedisi] = useState([]); const [selectedExpedisi, setSelectedExpedisi] = useState(0); const [selectedCarrierId, setselectedCarrierId] = useState(0); const [selectedCarrier, setselectedCarrier] = useState(0); - const [biayaKirim, setBiayaKirim] = useState(0); - const [checkWeigth, setCheckWeight] = useState(false); const [selectedServiceType, setSelectedServiceType] = useState(null); const [selectedExpedisiService, setselectedExpedisiService] = useState(null); - const [etd, setEtd] = useState(null); - const [etdFix, setEtdFix] = useState(null); + // const [etd, setEtd] = useState(null); + // const [etdFix, setEtdFix] = useState(null); const [bottomPopup, SetBottomPopup] = useState(null); const [bottomPopupTnC, SetBottomPopupTnC] = useState(null); const [itemTnC, setItemTnC] = useState(null); @@ -135,11 +151,29 @@ const Checkout = () => { const [findCodeVoucher, SetFindVoucher] = useState(null); const [selisihHargaCode, SetSelisihHargaCode] = useState(null); const [buttonTerapkan, SetButtonTerapkan] = useState(false); - const [checkoutValidation, setCheckoutValidation] = useState(false); const [loadingVoucher, setLoadingVoucher] = useState(true); const [loadingRajaOngkir, setLoadingRajaOngkir] = useState(false); const [grandTotal, setGrandTotal] = useState(0); - const [hasFlashSale, setHasFlashSale] = useState(false); + + const { + checkWeigth, + setCheckWeight, + hasFlashSale, + setHasFlashSale, + checkoutValidation, + setCheckoutValidation, + biayaKirim, + products, + setProducts, + etd, + unit, + selectedCourier, + selectedCourierId, + selectedService, + listExpedisi, + setExpedisi, + productSla + } = useCheckout(); const expedisiValidation = useRef(null); @@ -147,31 +181,16 @@ const Checkout = () => { if (!listVouchers) { try { setLoadingVoucher(true); - const productCategories = products - ?.reduce((categories, product) => { - if (product.categories && Array.isArray(product.categories)) { - product.categories.forEach((category) => { - if (category.id && !categories.includes(category.id)) { - categories.push(category.id); - } - }); - } - return categories; - }, []) - .join(','); - let dataVoucher = await getVoucher(auth?.id, { source: query, type: 'all,brand', - partner_id: auth?.partnerId, - voucher_category: productCategories, // Add the product categories + partner_id : auth?.partnerId, }); SetListVoucher(dataVoucher); let dataVoucherShipping = await getVoucher(auth?.id, { source: query, type: 'shipping', - voucher_category: productCategories, // Add the product categories }); SetListVoucherShipping(dataVoucherShipping); } finally { @@ -181,29 +200,17 @@ const Checkout = () => { }; const VoucherCode = async (code) => { - const productCategories = products - ?.reduce((categories, product) => { - if (product.categories && Array.isArray(product.categories)) { - product.categories.forEach((category) => { - if (category.id && !categories.includes(category.id)) { - categories.push(category.id); - } - }); - } - return categories; - }, []) - .join(','); - + // let dataVoucher = await findVoucher(code, auth.id, query); let dataVoucher = await getVoucher(auth?.id, { source: query, code: code, - voucher_category: productCategories, // Add the product categories }); if (dataVoucher.length <= 0) { SetFindVoucher(1); return; } + dataVoucher.forEach((addNewLine) => { if (addNewLine.applyType !== 'shipping') { // Mencari voucher dalam listVouchers @@ -296,6 +303,7 @@ const Checkout = () => { value: expedisi.id, label: expedisi.name, carrierId: expedisi.deliveryCarrierId, + logo: expedisi.image, })); setExpedisi(dataExpedisi); }; @@ -312,58 +320,6 @@ const Checkout = () => { }; }, []); - const hitungDiscountVoucher = (code, source) => { - let countDiscount = 0; - if (source === 'voucher') { - let dataVoucherIndex = listVouchers.findIndex( - (voucher) => voucher.code == code - ); - let dataActiveVoucher = listVouchers[dataVoucherIndex]; - - countDiscount = dataActiveVoucher.discountVoucher; - } else { - let dataVoucherIndex = listVoucherShippings.findIndex( - (voucher) => voucher.code == code - ); - let dataActiveVoucher = listVoucherShippings[dataVoucherIndex]; - - countDiscount = dataActiveVoucher.discountVoucher; - } - - /*if (dataActiveVoucher.discountType === 'percentage') { - countDiscount = cartCheckout?.subtotal * (dataActiveVoucher.discountAmount / 100) - if ( - dataActiveVoucher.maxDiscountAmount > 0 && - countDiscount > dataActiveVoucher.maxDiscountAmount - ) { - countDiscount = dataActiveVoucher.maxDiscountAmount - } - } else { - countDiscount = dataActiveVoucher.discountAmount - }*/ - - return countDiscount; - }; - - // useEffect(() => { - // if (!listVouchers) return; - // if (!activeVoucher) return; - - // console.log('voucher') - // const countDiscount = hitungDiscountVoucher(activeVoucher, 'voucher'); - - // SetDiscountVoucher(countDiscount); - // }, [activeVoucher, listVouchers]); - - // useEffect(() => { - // if (!listVoucherShippings) return; - // if (!activeVoucherShipping) return; - - // const countDiscount = hitungDiscountVoucher(activeVoucherShipping, 'voucher_shipping'); - - // SetDiscountVoucherOngkir(countDiscount); - // }, [activeVoucherShipping, listVoucherShippings]); - useEffect(() => { if (qVoucher === 'PASTIHEMAT' && listVouchers) { let code = qVoucher; @@ -381,71 +337,6 @@ const Checkout = () => { setHasFlashSale(hasFlashSale); }, [cartCheckout]); - useEffect(() => { - setCheckoutValidation(false); - const loadServiceRajaOngkir = async () => { - setLoadingRajaOngkir(true); - const body = { - origin: 2127, - destination: selectedAddress.shipping.rajaongkirCityId, - weight: totalWeight, - courier: selectedCarrier, - originType: 'subdistrict', - destinationType: 'subdistrict', - }; - setBiayaKirim(0); - const dataService = await axios( - '/api/rajaongkir-service?body=' + JSON.stringify(body) - ); - setLoadingRajaOngkir(false); - setListServiceExpedisi(dataService.data[0].costs); - if (dataService.data[0].costs[0]) { - setBiayaKirim(dataService.data[0].costs[0]?.cost[0].value); - setselectedExpedisiService( - dataService.data[0].costs[0]?.description + - '-' + - dataService.data[0].costs[0]?.service - ); - setEtd(dataService.data[0].costs[0]?.cost[0].etd); - toast.success('Harap pilih tipe layanan pengiriman'); - } else { - toast.error('Maaf, layanan tidak tersedia. Mohon pilih expedisi lain.'); - } - }; - if (selectedCarrier != 0 && selectedCarrier != 1 && totalWeight > 0) { - loadServiceRajaOngkir(); - } else { - setListServiceExpedisi(); - setBiayaKirim(0); - setselectedExpedisiService(); - setEtd(); - } - }, [selectedCarrier, selectedAddress, totalWeight]); - - useEffect(() => { - if (selectedServiceType) { - let serviceType = selectedServiceType.split(','); - setBiayaKirim(serviceType[0]); - setselectedExpedisiService(serviceType[1]); - setEtd(serviceType[2]); - } - }, [selectedServiceType]); - - useEffect(() => { - if (etd) setEtdFix(calculateEstimatedArrival(etd)); - }, [etd]); - - useEffect(() => { - if (selectedExpedisi) { - let serviceType = selectedExpedisi.split(','); - if (serviceType[0] === 0) return; - - setselectedCarrier(serviceType[0]); - setselectedCarrierId(serviceType[1]); - setListServiceExpedisi([]); - } - }, [selectedExpedisi]); - const poNumber = useRef(null); const poFile = useRef(null); @@ -472,7 +363,7 @@ const Checkout = () => { }); return; } - if (selectedExpedisi === 0) { + if (selectedCourier === 0 || !selectedCourier) { setCheckoutValidation(true); if (expedisiValidation.current) { const position = expedisiValidation.current.getBoundingClientRect(); @@ -483,7 +374,11 @@ const Checkout = () => { } return; } - if (selectedCarrier != 1 && biayaKirim == 0) { + if (!selectedService) { + toast.error('Harap pilih tipe layanan pengiriman'); + return; + } + if (selectedCourier != 1 && biayaKirim == 0) { toast.error('Maaf, layanan tidak tersedia. Mohon pilih expedisi lain.'); return; } @@ -493,23 +388,27 @@ const Checkout = () => { quantity: product.quantity, available_quantity: product?.availableQuantity, })); + let estimated_courier = etd.split('-').map(Number); + let eta_courier = Math.max(...estimated_courier); + let eta_courier_start = Math.min(...estimated_courier); + let data = { - // partner_shipping_id: auth.partnerId, + // partner_shipping_id: auth.partnerId,, // partner_invoice_id: auth.partnerId, partner_shipping_id: selectedAddress?.shipping?.id || auth.partnerId, partner_invoice_id: selectedAddress?.invoicing?.id || auth.partnerId, user_id: auth.id, order_line: JSON.stringify(productOrder), delivery_amount: biayaKirim, - carrier_id: selectedCarrierId, - estimated_arrival_days: splitDuration(etd), - delivery_service_type: selectedExpedisiService, + carrier_id: selectedCourierId, + estimated_arrival_days_start : parseInt(eta_courier_start) + parseInt(productSla), + estimated_arrival_days: parseInt(eta_courier) + parseInt(productSla), + delivery_service_type: selectedService?.service_type, flash_sale: hasFlashSale, // dibuat negasi untuk ngetest kebalikan nilai false voucher: activeVoucher, voucher_shipping: activeVoucherShipping, type: 'sale_order', }; - if (query) { data.source = 'buy'; } @@ -570,24 +469,6 @@ const Checkout = () => { )}`; } } - - /* const midtrans = async () => { - for (const product of products) deleteItemCart({ productId: product.id }); - if (grandTotal > 0) { - const payment = await axios.post( - `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/midtrans-payment?transactionId=${isCheckouted.id}` - ); - setIsLoading(false); - window.location.href = payment.data.redirectUrl; - } else { - window.location.href = `${ - process.env.NEXT_PUBLIC_SELF_HOST - }/shop/checkout/success?order_id=${isCheckouted.name.replace( - /\//g, - '-' - )}`; - } - };*/ }; const handlingActivateCode = async () => { @@ -761,19 +642,6 @@ const Checkout = () => { )}
- {/* {!loadingVoucher && - listVouchers?.length === 1 && - listVoucherShippings?.length === 1} - { -
-
-

Tidak ada voucher tersedia

-

- Maaf, saat ini tidak ada voucher yang tersedia. -

-
-
- } */} {listVoucherShippings && listVoucherShippings?.length > 0 && (
@@ -1159,8 +1027,8 @@ const Checkout = () => { )} - - + {/* { + /> */}
{!!products && @@ -1255,14 +1123,15 @@ const Checkout = () => {
{currencyFormat(cartCheckout?.subtotal)}
-
- PPN {((PPN - 1) * 100).toFixed(0)}% -
+
PPN {((PPN - 1) * 100).toFixed(0)}%
{currencyFormat(cartCheckout?.tax)}
- Biaya Kirim

{etdFix}

+ Biaya Kirim{' '} +

+ {formatShipmentRange(etd, unit, productSla)} +

{currencyFormat( @@ -1386,7 +1255,6 @@ const Checkout = () => { className='flex-1 btn-yellow' onClick={checkout} disabled={ - isLoading || !products || products?.length == 0 || priceCheck || @@ -1458,9 +1326,10 @@ const Checkout = () => { /> )} + {products && } - - + {/* { + /> */}
Detail Pesanan
@@ -1561,15 +1430,15 @@ const Checkout = () => {
{currencyFormat(cartCheckout?.subtotal)}
-
- PPN {((PPN - 1) * 100).toFixed(0)}% -
+
PPN {((PPN - 1) * 100).toFixed(0)}%
{currencyFormat(cartCheckout?.tax)}
Biaya Kirim -

{etdFix}

+

+ {formatShipmentRange(etd, unit, productSla)} +

{currencyFormat( @@ -1691,7 +1560,6 @@ const Checkout = () => { className='w-full btn-yellow mt-4' onClick={checkout} disabled={ - isLoading || !products || products?.length == 0 || priceCheck || @@ -1740,14 +1608,29 @@ const SectionAddress = ({ address, label, url }) => (

{address.street}, {address?.city?.name}

+
+ + {address.addressMap ? ( + + ) : ( + + + + )} +
)}
); const SectionValidation = ({ address }) => - address?.stateId == 0 || - (address?.rajaongkirCityId == 0 && ( + address?.stateId == 0 && (
Mohon untuk memperbarui alamat Anda dengan mengklik tombol di bawah ini.{' '} @@ -1761,7 +1644,7 @@ const SectionValidation = ({ address }) =>
- )); + ); const SectionExpedisi = ({ address, -- cgit v1.2.3