From 77a7e36c3ab0dad3c7060d6cef2449e87869c215 Mon Sep 17 00:00:00 2001
From: Rafi Zadanly <zadanlyr@gmail.com>
Date: Wed, 17 May 2023 14:23:54 +0700
Subject: add 3 days on etd checkout

---
 src/lib/checkout/components/Checkout.jsx | 252 +++++++++++++++++--------------
 1 file changed, 141 insertions(+), 111 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 b2f9a866..40f5d8e5 100644
--- a/src/lib/checkout/components/Checkout.jsx
+++ b/src/lib/checkout/components/Checkout.jsx
@@ -25,6 +25,8 @@ import { createSlug } from '@/core/utils/slug'
 import { Button, Modal } from 'flowbite-react'
 import BottomPopup from '@/core/components/elements/Popup/BottomPopup'
 
+const SELF_PICKUP_ID = 32
+
 const Checkout = () => {
   const router = useRouter()
   const auth = useAuth()
@@ -144,12 +146,12 @@ const Checkout = () => {
   useEffect(() => {
     const loadServiceRajaOngkir = async () => {
       const body = {
-        origin: 155,
+        origin: 2127,
         destination: selectedAddress.shipping.rajaongkirCityId,
         weight: totalWeight,
         courier: selectedCarrier,
-        originType: 'city',
-        destinationType: 'city'
+        originType: 'subdistrict',
+        destinationType: 'subdistrict'
       }
       setBiayaKirim(0)
       const dataService = await axios('/api/rajaongkir-service?body=' + JSON.stringify(body))
@@ -160,9 +162,9 @@ const Checkout = () => {
           dataService.data[0].costs[0]?.description + '-' + dataService.data[0].costs[0]?.service
         )
         setEtd(dataService.data[0].costs[0]?.cost[0].etd)
-        toast.success('Silahkan Pilih Service Tipe')
+        toast.success('Harap pilih tipe layanan pengiriman')
       } else {
-        toast.error('Tidak Ada Service, Silahkan Pilih Expedisi lain !')
+        toast.error('Maaf, layanan tidak tersedia. Mohon pilih expedisi lain.')
       }
     }
     if (selectedCarrier != 0 && selectedCarrier != 1 && totalWeight > 0) {
@@ -185,31 +187,7 @@ const Checkout = () => {
   }, [selectedServiceType])
 
   useEffect(() => {
-    if (etd) {
-      let estimationDate = etd.split('-')
-      if (Array.isArray(estimationDate)) {
-        let from = new Date()
-        let to = new Date()
-        from.setDate(from.getDate() + parseInt(estimationDate[0]))
-        to.setDate(to.getDate() + parseInt(estimationDate[1]))
-        setEtdFix(
-          '(' +
-            from.getDate() +
-            ' ' +
-            from.toLocaleString('default', { month: 'short' }) +
-            ' - ' +
-            to.getDate() +
-            ' ' +
-            to.toLocaleString('default', { month: 'short' }) +
-            ')'
-        )
-      } else {
-        let to = new Date()
-        to.setDate(to.getDate() + parseInt(10))
-        setEtdFrom('>')
-        setEtdTo(to.getDate() + ' ' + to.toLocaleString('default', { month: 'short' }))
-      }
-    }
+    if (etd) setEtdFix(calculateEstimatedArrival(etd))
   }, [etd])
 
   useEffect(() => {
@@ -217,6 +195,7 @@ const Checkout = () => {
       let serviceType = selectedExpedisi.split(',')
       setselectedCarrier(serviceType[0])
       setselectedCarrierId(serviceType[1])
+      setListServiceExpedisi([])
     }
   }, [selectedExpedisi])
 
@@ -280,38 +259,35 @@ const Checkout = () => {
 
         <Divider />
 
-        {/* <PickupAddress label='Alamat Pickup' /> */}
-        <SectionAddress
-          address={selectedAddress.shipping}
-          label='Alamat Kirim'
-          url='/my/address?select=shipping'
-        ></SectionAddress>
-        <Divider />
-        <SectionAddress
-          address={selectedAddress.invoicing}
-          label='Alamat Penagihan'
-          url='/my/address?select=invoice'
-        ></SectionAddress>
-        <Divider />
-        <SectionValidation
-          address={selectedAddress.invoicing}
-          checkWeigth={checkWeigth}
-        ></SectionValidation>
+        {selectedCarrierId == SELF_PICKUP_ID && <PickupAddress label='Alamat Pickup' />}
+        {selectedCarrierId != SELF_PICKUP_ID && (
+          <>
+            <SectionAddress
+              address={selectedAddress.shipping}
+              label='Alamat Pengiriman'
+              url='/my/address?select=shipping'
+            />
+            <Divider />
+            <SectionAddress
+              address={selectedAddress.invoicing}
+              label='Alamat Penagihan'
+              url='/my/address?select=invoice'
+            />
+          </>
+        )}
         <Divider />
+        <SectionValidation address={selectedAddress.invoicing} />
         <SectionExpedisi
           address={selectedAddress.shipping}
           listExpedisi={listExpedisi}
           setSelectedExpedisi={setSelectedExpedisi}
           checkWeigth={checkWeigth}
-        ></SectionExpedisi>
+        />
         <Divider />
         <SectionListService
           listserviceExpedisi={listserviceExpedisi}
           setSelectedServiceType={setSelectedServiceType}
-        ></SectionListService>
-        <Divider />
-        <Divider />
-        <Divider />
+        />
 
         <div className='p-4 flex flex-col gap-y-4'>
           {products && <VariantGroupCard openOnClick={false} variants={products} />}
@@ -344,7 +320,7 @@ const Checkout = () => {
             </div>
             <div className='flex gap-x-2 justify-between'>
               <div className='text-gray_r-11'>
-                Biaya Kirim <p className='text-xs'>*Estimasi tiba {etdFix} </p>
+                Biaya Kirim <p className='text-xs mt-3'>{etdFix}</p>
               </div>
               <div>{currencyFormat(Math.round(parseInt(biayaKirim * 1.1) / 1000) * 1000)}</div>
             </div>
@@ -422,36 +398,35 @@ const Checkout = () => {
       <DesktopView>
         <div className='container mx-auto py-10 flex'>
           <div className='w-3/4 border border-gray_r-6 rounded bg-white'>
-            {/* <PickupAddress label='Alamat Pickup' /> */}
-            <SectionAddress
-              address={selectedAddress.shipping}
-              label='Alamat Kirim'
-              url='/my/address?select=shipping'
-            ></SectionAddress>
-            <Divider />
-            <SectionAddress
-              address={selectedAddress.invoicing}
-              label='Alamat Penagihan'
-              url='/my/address?select=invoice'
-            ></SectionAddress>
-            <Divider />
-            <SectionValidation
-              address={selectedAddress.invoicing}
-              checkWeigth={checkWeigth}
-            ></SectionValidation>
+            {selectedCarrierId == SELF_PICKUP_ID && <PickupAddress label='Alamat Pickup' />}
+            {selectedCarrierId != SELF_PICKUP_ID && (
+              <>
+                <SectionAddress
+                  address={selectedAddress.shipping}
+                  label='Alamat Pengiriman'
+                  url='/my/address?select=shipping'
+                />
+                <Divider />
+                <SectionAddress
+                  address={selectedAddress.invoicing}
+                  label='Alamat Penagihan'
+                  url='/my/address?select=invoice'
+                />
+              </>
+            )}
             <Divider />
+            <SectionValidation address={selectedAddress.invoicing} />
             <SectionExpedisi
               address={selectedAddress.shipping}
               listExpedisi={listExpedisi}
               setSelectedExpedisi={setSelectedExpedisi}
               checkWeigth={checkWeigth}
-            ></SectionExpedisi>
+            />
             <Divider />
             <SectionListService
               listserviceExpedisi={listserviceExpedisi}
               setSelectedServiceType={setSelectedServiceType}
-            ></SectionListService>
-            <Divider />
+            />
 
             <div className='p-4'>
               <div className='font-medium'>Detail Pesanan</div>
@@ -568,7 +543,7 @@ const Checkout = () => {
                 <div className='flex gap-x-2 justify-between'>
                   <div className='text-gray_r-11'>
                     Biaya Kirim
-                    <p className='text-xs'>*Estimasi tiba {etdFix} </p>
+                    <p className='text-xs mt-3'>{etdFix}</p>
                   </div>
                   <div>{currencyFormat(Math.round(parseInt(biayaKirim * 1.1) / 1000) * 1000)}</div>
                 </div>
@@ -676,14 +651,17 @@ const SectionAddress = ({ address, label, url }) => (
   </div>
 )
 
-const SectionValidation = ({ address, checkWeigth }) =>
+const SectionValidation = ({ address }) =>
   address?.rajaongkirCityId == 0 && (
     <BottomPopup active={true} title='Update Alamat'>
       <div className='leading-7 text-gray_r-12/80'>
-        Silahkan Update Alamat Anda Melalui Tombol di bawah ini{' '}
+        Mohon untuk memperbarui alamat Anda dengan mengklik tombol di bawah ini.{' '}
       </div>
       <div className='flex justify-center mt-6 gap-x-4'>
-        <Link className='btn-solid-red w-full md:w-fit text-white' href={`/my/address/${address?.id}/edit`}>
+        <Link
+          className='btn-solid-red w-full md:w-fit text-white'
+          href={`/my/address/${address?.id}/edit`}
+        >
           Update Alamat
         </Link>
       </div>
@@ -714,14 +692,15 @@ const SectionExpedisi = ({ address, listExpedisi, setSelectedExpedisi, checkWeig
         </div>
       </div>
       {checkWeigth == true && (
-        <p className='mt-2 text-gray_r-11'>
-          Opsi pengiriman hanya ada self pickup, ada berat item yang belum di setting, silahkan hub
-          admin di{' '}
-          <span>
-            <a className='text-danger-500' href='https://api.whatsapp.com/send?phone=628128080622'>
-              Link InI !
-            </a>
-          </span>
+        <p className='mt-4 text-gray_r-11 leading-6'>
+          Mohon maaf, pengiriman hanya tersedia untuk self pickup karena terdapat barang yang belum
+          diatur beratnya. Mohon atur berat barang dengan menghubungi admin melalui{' '}
+          <a
+            className='text-danger-500 inline'
+            href='https://api.whatsapp.com/send?phone=628128080622'
+          >
+            tautan ini
+          </a>
         </p>
       )}
     </div>
@@ -729,35 +708,87 @@ const SectionExpedisi = ({ address, listExpedisi, setSelectedExpedisi, checkWeig
 
 const SectionListService = ({ listserviceExpedisi, setSelectedServiceType }) =>
   listserviceExpedisi?.length > 0 && (
-    <div className='p-4'>
-      <div className='flex justify-between items-center'>
-        <div className='font-medium'>Service Type Expedisi : </div>
-        <div>
-          <select className='form-input' onChange={(e) => setSelectedServiceType(e.target.value)}>
-            {listserviceExpedisi.map((service) => (
-              <option
-                value={
-                  service.cost[0].value +
-                  ',' +
-                  service.description +
-                  '-' +
-                  service.service +
-                  ',' +
-                  service.cost[0].etd
-                }
-                key={service.service}
-              >
-                {' '}
-                {service.description} - {service.service.toUpperCase()} (Estimasi Tiba{' '}
-                {service.cost[0].etd} Hari)
-              </option>
-            ))}
-          </select>
+    <>
+      <div className='p-4'>
+        <div className='flex justify-between items-center'>
+          <div className='font-medium'>Service Type Expedisi : </div>
+          <div>
+            <select className='form-input' onChange={(e) => setSelectedServiceType(e.target.value)}>
+              {listserviceExpedisi.map((service) => (
+                <option
+                  value={
+                    service.cost[0].value +
+                    ',' +
+                    service.description +
+                    '-' +
+                    service.service +
+                    ',' +
+                    extractDuration(service.cost[0].etd)
+                  }
+                  key={service.service}
+                >
+                  {' '}
+                  {service.description} - {service.service.toUpperCase()}
+                  {extractDuration(service.cost[0].etd) &&
+                    ` (Estimasi Tiba ${extractDuration(service.cost[0].etd)} Hari)`}
+                </option>
+              ))}
+            </select>
+          </div>
         </div>
       </div>
-    </div>
+      <Divider />
+    </>
   )
 
+function addDays(date, days) {
+  const result = new Date(date)
+  result.setDate(result.getDate() + days)
+  return result
+}
+
+function formatDate(date) {
+  const day = date.getDate()
+  const month = date.toLocaleString('default', { month: 'short' })
+  return `${day} ${month}`
+}
+
+function calculateEstimatedArrival(duration) {
+  if (duration) {
+    const estimationDate = duration.split('-')
+    const from = addDays(new Date(), parseInt(estimationDate[0]) + 3)
+    const to = addDays(new Date(), parseInt(estimationDate[1]) + 3)
+
+    let etdText = `*Estimasi tiba ${formatDate(from)}`
+
+    if (estimationDate[1] > estimationDate[0]) {
+      etdText += ` - ${formatDate(to)}`
+    }
+
+    return etdText
+  }
+
+  return ''
+}
+
+const extractDuration = (text) => {
+  const matches = text.match(/\d+(?:-\d+)?/g)
+
+  if (matches && matches.length === 1) {
+    const parts = matches[0].split('-')
+    const min = parseInt(parts[0])
+    const max = parseInt(parts[1])
+
+    if (min === max) {
+      return min.toString()
+    }
+
+    return matches[0]
+  }
+
+  return ''
+}
+
 const PickupAddress = ({ label }) => (
   <div className='p-4'>
     <div className='flex justify-between items-center'>
@@ -771,7 +802,6 @@ const PickupAddress = ({ label }) => (
       </p>
       <p className='mt-1 text-gray_r-11'>Telp : 021-2933 8828/29</p>
       <p className='mt-1 text-gray_r-11'>Mobile : 0813 9000 7430</p>
-      <p className='mt-5 text-caption-2 text-gray_r-11 mb-2'>*) Belum termasuk biaya pengiriman</p>
     </div>
   </div>
 )
-- 
cgit v1.2.3

