From 915dc67e1ce31eab1f2415cc8df95cebb75a137d Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Fri, 13 Dec 2024 14:18:03 +0700
Subject: <iman>update pengajuan tempo request

---
 .../component/informasiPerusahaan.jsx              | 382 ++++++++++++++++-----
 1 file changed, 288 insertions(+), 94 deletions(-)

(limited to 'src/lib/pengajuan-tempo/component/informasiPerusahaan.jsx')

diff --git a/src/lib/pengajuan-tempo/component/informasiPerusahaan.jsx b/src/lib/pengajuan-tempo/component/informasiPerusahaan.jsx
index 6a7eb3cb..f8a0bc55 100644
--- a/src/lib/pengajuan-tempo/component/informasiPerusahaan.jsx
+++ b/src/lib/pengajuan-tempo/component/informasiPerusahaan.jsx
@@ -4,6 +4,8 @@ import HookFormSelect from '@/core/components/elements/Select/HookFormSelect';
 import odooApi from '~/libs/odooApi';
 import stateApi from '@/lib/address/api/stateApi.js';
 import cityApi from '@/lib/address/api/cityApi';
+import districtApi from '@/lib/address/api/districtApi';
+import subDistrictApi from '@/lib/address/api/subDistrictApi';
 import { Radio, RadioGroup, Stack, Checkbox } from '@chakra-ui/react';
 import { usePengajuanTempoStore } from '../../../../src-migrate/modules/register/stores/usePengajuanTempoStore';
 import useDevice from '@/core/hooks/useDevice';
@@ -11,21 +13,28 @@ import Divider from '@/core/components/elements/Divider/Divider';
 import { getAuth } from '~/libs/auth';
 import addressApi from '@/lib/address/api/addressApi';
 import { toast } from 'react-hot-toast';
+import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
+import { useRouter } from 'next/router';
 const InformasiPerusahaan = ({
   chekValid,
   buttonSubmitClick,
   isKonfirmasi,
 }) => {
   const auth = getAuth();
+  const router = useRouter();
   const { isDesktop, isMobile } = useDevice();
   const { control, watch, setValue, getValues } = useForm();
   const { form, errors, validate, updateForm } = usePengajuanTempoStore();
+  const [states, setState] = useState([]);
+  const [cities, setCities] = useState([]);
+  const [districts, setDistricts] = useState([]);
+  const [subDistricts, setSubDistricts] = useState([]);
+  const [zips, setZips] = useState([]);
   const [industries, setIndustries] = useState([]);
   const [paymentTerm, setPaymentTerm] = useState([]);
   const [selectedCategory, setSelectedCategory] = useState('');
-  const [states, setState] = useState([]);
-  const [cities, setCities] = useState([]);
   const [bersedia, setBersedia] = useState(null);
+  const [changeConfirmation, setChangeConfirmation] = useState(false);
   const category_produk = [
     { id: 2040, name: 'Pengaman, Kesehatan & Keamanan' },
     { id: 2097, name: 'Perkakas Tangan, Listrik & Pneumatic' },
@@ -64,7 +73,9 @@ const InformasiPerusahaan = ({
 
   const watchState = watch('state');
   useEffect(() => {
-    // updateForm('city', '');
+    setValue('city', '');
+    setValue('district', '');
+    setValue('subDistrict', '');
     if (watchState) {
       updateForm('state', `${watchState}`);
       validate();
@@ -81,12 +92,79 @@ const InformasiPerusahaan = ({
   }, [watchState]);
 
   const watchCity = watch('city');
+
   useEffect(() => {
     if (watchCity) {
       updateForm('city', `${watchCity}`);
       validate();
+      const loadDistricts = async () => {
+        let dataDistricts = await districtApi({ cityId: watchCity });
+        dataDistricts = dataDistricts.map((district) => ({
+          value: district.id,
+          label: district.name,
+        }));
+        setDistricts(dataDistricts);
+      };
+      loadDistricts();
     }
-  }, [watchCity]);
+  }, [watchCity, setValue]);
+
+  const watchDistrict = watch('district');
+  useEffect(() => {
+    setValue('subDistrict', '');
+    if (watchDistrict) {
+      updateForm('district', `${watchDistrict}`);
+      validate();
+      const loadSubDistricts = async () => {
+        let dataSubDistricts = await subDistrictApi({
+          districtId: watchDistrict,
+        });
+        dataSubDistricts = dataSubDistricts.map((district) => ({
+          value: district.id,
+          label: district.name,
+        }));
+        setSubDistricts(dataSubDistricts);
+      };
+      loadSubDistricts();
+    }
+  }, [watchDistrict, setValue]);
+
+  const watchsubDistrict = watch('subDistrict');
+
+  useEffect(() => {
+    let kelurahan = '';
+
+    if (watchsubDistrict) {
+      updateForm('subDistrict', `${watchsubDistrict}`);
+      validate();
+      for (const data in subDistricts) {
+        if (subDistricts[data].value == watchsubDistrict) {
+          kelurahan = subDistricts[data].label.toLowerCase();
+        }
+      }
+      const loadZip = async () => {
+        const response = await fetch(
+          `https://alamat.thecloudalert.com/api/cari/index/?keyword=${kelurahan}`
+        );
+
+        const result = await response.json();
+        const dataZips = result.result.map((zip) => ({
+          value: parseInt(zip.kodepos),
+          label: zip.kodepos,
+        }));
+        setZips(dataZips);
+      };
+      loadZip();
+    }
+  }, [watchsubDistrict, setValue, subDistricts]);
+
+  const watchZip = watch('zip');
+  useEffect(() => {
+    if (watchZip) {
+      updateForm('zip', `${watchZip}`);
+      validate();
+    }
+  }, [watchZip]);
 
   useEffect(() => {
     const loadIndustries = async () => {
@@ -115,10 +193,10 @@ const InformasiPerusahaan = ({
   useEffect(() => {
     const loadPaymentTerm = async () => {
       const dataPaymentTerm = [
-        { id: 24, name: 'Tempo 14 Hari' },
-        { id: 25, name: 'Tempo 30 Hari' },
         { id: 29, name: 'Tempo 7 Hari' },
+        { id: 24, name: 'Tempo 14 Hari' },
         { id: 32, name: 'Tempo 21 Hari' },
+        { id: 25, name: 'Tempo 30 Hari' },
       ];
       setPaymentTerm(
         dataPaymentTerm?.map((o) => ({
@@ -157,15 +235,7 @@ const InformasiPerusahaan = ({
     updateForm('estimasi', formattedValue.replace(/^Rp\s*/, ''));
     validate();
   };
-  const onChangeTempoDuration = (e) => {
-    updateForm('tempoDuration', `${e}`);
-    validate();
-  };
 
-  const onChangeTempoLimit = (e) => {
-    updateForm('tempoLimit', `${e}`);
-    validate();
-  };
   const [isCustom, setIsCustom] = React.useState(false);
   const [tempoLimitValueEx, setTempoLimitValueEx] = React.useState('');
   const handleCheckboxBersediaChange = (value) => {
@@ -178,6 +248,16 @@ const InformasiPerusahaan = ({
     updateForm('bersedia', `${value}`);
     validate();
   };
+  const handleCheckboxPortalChange = (value) => {
+    // if (value === 'bersedia') {
+    //   setBersedia(true);
+    // } else if (value === 'tidakBersedia') {
+    //   setBersedia(false);
+    // }
+    // updateForm('bersedia', `${value === 'bersedia'}`);
+    updateForm('portal', `${value}`);
+    validate();
+  };
   const [selectedIds, setSelectedIds] = useState(
     form.categoryProduk ? form.categoryProduk.split(',').map(Number) : [] // Parse string menjadi array angka
   );
@@ -217,6 +297,8 @@ const InformasiPerusahaan = ({
   const streetRef = useRef(null);
   const stateRef = useRef(null);
   const cityRef = useRef(null);
+  const districtRef = useRef(null);
+  const subDistrictRef = useRef(null);
   const zipRef = useRef(null);
   const mobileRef = useRef(null);
   const bankNameRef = useRef(null);
@@ -225,55 +307,10 @@ const InformasiPerusahaan = ({
   const estimasiRef = useRef(null);
   const tempoDurationRef = useRef(null);
   const bersediaRef = useRef(null);
+  const portalRef = useRef(null);
   const categoryProdukRef = useRef(null);
   const tempoLimitRef = useRef(null);
 
-  useEffect(() => {
-    const options = {
-      behavior: 'smooth',
-      block: 'center',
-    };
-
-    const loadIndustries = async () => {
-      const watchZip = form.zip?.trim(); // Menghapus spasi berlebih
-
-      // Validasi: hanya eksekusi jika watchZip valid (contoh: minimal 5 karakter)
-      if (watchZip && watchZip.length >= 5) {
-        const loadZip = async () => {
-          try {
-            const response = await fetch(
-              `https://alamat.thecloudalert.com/api/cari/index/?keyword=${watchZip}`
-            );
-
-            const result = await response.json();
-
-            if (!result.result.length > 0) {
-              toast.error('Alamat pos salah');
-              updateForm('zip', ''); // Reset form.zip jika salah
-              validate(); // Memanggil validasi formulir
-              return false;
-            } else {
-              updateForm('zip', watchZip);
-              validate();
-              return true; // Jika valid
-            }
-          } catch (error) {
-            toast.error('Terjadi kesalahan saat memeriksa alamat pos.');
-            console.error('Error:', error);
-            return false;
-          }
-        };
-
-        const isValidZip = await loadZip();
-        if (!isValidZip) {
-          zipRef.current.scrollIntoView(options);
-        }
-      }
-    };
-
-    loadIndustries();
-  }, [form.zip]);
-
   useEffect(() => {
     const options = {
       behavior: 'smooth',
@@ -301,6 +338,14 @@ const InformasiPerusahaan = ({
           cityRef.current.scrollIntoView(options);
           return;
         }
+        if (errors.district && districtRef.current) {
+          districtRef.current.scrollIntoView(options);
+          return;
+        }
+        if (errors.subDistrict && subDistrictRef.current) {
+          subDistrictRef.current.scrollIntoView(options);
+          return;
+        }
         if (errors.zip && zipRef.current) {
           zipRef.current.scrollIntoView(options);
           return;
@@ -333,6 +378,10 @@ const InformasiPerusahaan = ({
           bersediaRef.current.scrollIntoView(options);
           return;
         }
+        if (errors.portal && portalRef.current) {
+          portalRef.current.scrollIntoView(options);
+          return;
+        }
         if (errors.categoryProduk && categoryProdukRef.current) {
           categoryProdukRef.current.scrollIntoView(options);
           return;
@@ -355,6 +404,15 @@ const InformasiPerusahaan = ({
     if (form.city) {
       setValue('city', parseInt(form.city));
     }
+    if (form.district) {
+      setValue('district', parseInt(form.district));
+    }
+    if (form.subDistrict) {
+      setValue('subDistrict', parseInt(form.subDistrict));
+    }
+    if (form.zip) {
+      setValue('zip', parseInt(form.zip));
+    }
     if (form.tempoDuration) {
       setValue('tempoDuration', parseInt(form.tempoDuration));
     }
@@ -383,14 +441,31 @@ const InformasiPerusahaan = ({
         if (dataProfile.name) {
           updateForm('name', dataProfile.name);
         }
+        if (dataProfile.stateId.id) {
+          updateForm('state', `${dataProfile.stateId.id}`);
+        }
+        if (dataProfile.city.id) {
+          updateForm('city', `${dataProfile.city.id}`);
+        }
+        if (dataProfile.district.id) {
+          updateForm('district', `${dataProfile.district.id}`);
+        }
+        if (dataProfile.subDistrict.id) {
+          updateForm('subDistrict', `${dataProfile.subDistrict.id}`);
+        }
         if (dataProfile.alamatBisnis) {
           updateForm('street', dataProfile.alamatBisnis);
         }
         if (dataProfile.zip) {
           updateForm('zip', dataProfile.zip);
         }
-        if (dataProfile.phone) {
-          updateForm('mobile', dataProfile.phone.replace(/\D/g, ''));
+        if (dataProfile.mobile) {
+          updateForm('mobile', dataProfile.mobile.replace(/\D/g, ''));
+        } else {
+          setChangeConfirmation(true);
+        }
+        if (!dataProfile.email) {
+          setChangeConfirmation(true);
         }
       } catch (error) {
         console.error('Error loading profile:', error);
@@ -402,7 +477,7 @@ const InformasiPerusahaan = ({
     if (auth?.parentId) {
       loadProfile();
     }
-  }, [auth?.parentId, updateForm]);
+  }, [auth?.parentId]);
   useEffect(() => {
     const loadProfile = async () => {
       try {
@@ -410,6 +485,8 @@ const InformasiPerusahaan = ({
         setValue('industryId', parseInt(dataProfile.industryId));
         setValue('state', parseInt(dataProfile.stateId.id));
         setValue('city', parseInt(dataProfile.city.id));
+        setValue('district', parseInt(dataProfile.district.id));
+        setValue('subDistrict', parseInt(dataProfile.subDistrict.id));
       } catch (error) {
         console.error('Error loading profile:', error);
       }
@@ -419,8 +496,46 @@ const InformasiPerusahaan = ({
       loadProfile();
     }
   }, [auth?.parentId, setValue]);
+
+  const handleLengkapiData = () => {
+    router.push('/my/profile');
+  };
+
   return (
     <>
+      <BottomPopup
+        active={changeConfirmation}
+        close={() => {
+          toast.error(
+            'Mohon lengkapi data perusahaan sebelum melakukan pengajuan tempo'
+          );
+        }}
+        title='Data Perusahaan Anda Belum Lengkap'
+      >
+        <div className='leading-7 text-gray_r-12/80'>
+          Mohon lengkapi data perusahaan sebelum melakukan pengajuan tempo
+        </div>
+        <div className='flex mt-6 gap-x-4 md:justify-end'>
+          <button
+            className='btn-solid-red flex-1 md:flex-none'
+            type='button'
+            onClick={handleLengkapiData}
+          >
+            Lengkapi Data
+          </button>
+          <button
+            className='btn-light flex-1 md:flex-none'
+            type='button'
+            onClick={() => {
+              toast.error(
+                'Mohon lengkapi data perusahaan sebelum melakukan pengajuan tempo'
+              );
+            }}
+          >
+            Batal
+          </button>
+        </div>
+      </BottomPopup>
       {isDesktop && (
         <div className=''>
           <h1 className={`font-bold ${isKonfirmasi ? 'text-xl' : ''}`}>
@@ -563,13 +678,71 @@ const InformasiPerusahaan = ({
                         </div>
                       )}
                     </div>
-                    <div className='w-1/3'>
+                    <div className='w-1/3' ref={districtRef}>
+                      <Controller
+                        name='district'
+                        control={control}
+                        render={(props) => (
+                          <HookFormSelect
+                            {...props}
+                            options={districts}
+                            disabled={!watchState || !watchCity}
+                            placeholder='Kecamatan'
+                          />
+                        )}
+                      />
+                      {chekValid && (
+                        <div className='text-caption-2 text-danger-500 mt-1'>
+                          {errors.district}
+                        </div>
+                      )}
+                    </div>
+                    <div className='w-1/3' ref={subDistrictRef}>
+                      <Controller
+                        name='subDistrict'
+                        control={control}
+                        render={(props) => (
+                          <HookFormSelect
+                            {...props}
+                            options={subDistricts}
+                            disabled={!watchDistrict}
+                            placeholder='Kelurahan'
+                          />
+                        )}
+                      />
+                      {chekValid && (
+                        <div className='text-caption-2 text-danger-500 mt-1'>
+                          {errors.district}
+                        </div>
+                      )}
+                    </div>
+                    <div className='w-1/3' ref={zipRef}>
+                      <Controller
+                        name='zip'
+                        control={control}
+                        render={(props) => (
+                          <HookFormSelect
+                            {...props}
+                            options={zips}
+                            disabled={!watchsubDistrict}
+                            placeholder='Zip'
+                          />
+                        )}
+                      />
+                      {chekValid && (
+                        <div className='text-caption-2 text-danger-500 mt-1'>
+                          {errors.district}
+                        </div>
+                      )}
+                    </div>
+                    {/* <div className='w-1/3'>
                       <input
                         id='zip'
                         name='zip'
                         ref={zipRef}
                         placeholder='Kode Pos'
                         type='number'
+                        disabled={!watchsubDistrict}
                         value={form.zip}
                         className='form-input'
                         onChange={handleInputChange}
@@ -579,7 +752,7 @@ const InformasiPerusahaan = ({
                           {errors.zip}
                         </div>
                       )}
-                    </div>
+                    </div> */}
                   </div>
                 </div>
               </div>
@@ -712,9 +885,9 @@ const InformasiPerusahaan = ({
 
               <div className='flex flex-row  justify-between items-start'>
                 <div className='w-2/5 text-nowrap'>
-                  <label className='form-label '>
+                  <label className='form-label text-wrap'>
                     Estimasi Pembelian pertahun{' '}
-                    <span className=' opacity-60'>(Opsional)</span>
+                    <span className=' opacity-60 '>(Opsional)</span>
                   </label>
                 </div>
                 <div className='w-3/5'>
@@ -799,14 +972,38 @@ const InformasiPerusahaan = ({
               <div className='flex flex-row justify-between items-start'>
                 <div className='w-2/5'>
                   <label className='form-label  text-wrap '>
-                    Apakah bersedia transaksi via website?
+                    Apakah terdapat vendor portal pada perusahaan anda?
                   </label>
-                  {!isKonfirmasi && (
-                    <span className='text-xs opacity-60'>
-                      Pilih produk bisa lebih dari 1
-                    </span>
+                </div>
+                <div className='w-3/5 flex flex-col justify-start'>
+                  <div className='flex gap-x-4' ref={portalRef}>
+                    <RadioGroup
+                      onChange={handleCheckboxPortalChange}
+                      value={form.portal}
+                    >
+                      <Stack direction='row'>
+                        <Radio colorScheme='red' value='ada'>
+                          Ya, ada
+                        </Radio>
+                        <Radio colorScheme='red' value='tidak'>
+                          Tidak ada
+                        </Radio>
+                      </Stack>
+                    </RadioGroup>
+                  </div>
+                  {chekValid && (
+                    <div className='text-caption-2 text-danger-500 mt-1'>
+                      {errors.portal}
+                    </div>
                   )}
                 </div>
+              </div>
+              <div className='flex flex-row justify-between items-start'>
+                <div className='w-2/5'>
+                  <label className='form-label  text-wrap '>
+                    Apakah bersedia transaksi via website?
+                  </label>
+                </div>
                 <div className='w-3/5 flex flex-col justify-start'>
                   <div className='flex gap-x-4' ref={bersediaRef}>
                     <RadioGroup
@@ -822,28 +1019,6 @@ const InformasiPerusahaan = ({
                         </Radio>
                       </Stack>
                     </RadioGroup>
-                    {/* <Checkbox
-                  name='bersedia'
-                  borderColor='gray.600'
-                  colorScheme='red'
-                  isChecked={bersedia === true} // Checked when bersedia is true
-                  onChange={() => handleCheckboxBersediaChange('bersedia')}
-                  value={true}
-                  size='md'
-                >
-                  Saya bersedia
-                </Checkbox>
-                <Checkbox
-                  name='bersedia'
-                  borderColor='gray.600'
-                  colorScheme='red'
-                  isChecked={bersedia === false} // Checked when bersedia is false
-                  onChange={() => handleCheckboxBersediaChange('tidakBersedia')}
-                  value={false}
-                  size='md'
-                >
-                  Tidak bersedia
-                </Checkbox> */}
                   </div>
                   {chekValid && (
                     <div className='text-caption-2 text-danger-500 mt-1'>
@@ -1027,6 +1202,25 @@ const InformasiPerusahaan = ({
                         </div>
                       )}
                     </div>
+                    <div className='w-1/3' ref={districtRef}>
+                      <Controller
+                        name='district'
+                        control={control}
+                        render={(props) => (
+                          <HookFormSelect
+                            {...props}
+                            options={districts}
+                            disabled={!watchCity}
+                            placeholder='Kecamatan'
+                          />
+                        )}
+                      />
+                      {chekValid && (
+                        <div className='text-caption-2 text-danger-500 mt-1'>
+                          {errors.district}
+                        </div>
+                      )}
+                    </div>
                     <div className='w-1/3'>
                       <input
                         id='zip'
-- 
cgit v1.2.3

