From e9cd13307f0095dc4edc5048752675d80c551564 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Fri, 6 Dec 2024 17:06:26 +0700
Subject: <iman> pengajuan tempo

---
 .../pengajuan-tempo/component/PengajuanTempo.jsx   | 235 ++++++++++++++-------
 1 file changed, 159 insertions(+), 76 deletions(-)

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

diff --git a/src/lib/pengajuan-tempo/component/PengajuanTempo.jsx b/src/lib/pengajuan-tempo/component/PengajuanTempo.jsx
index 1704556e..82b64df7 100644
--- a/src/lib/pengajuan-tempo/component/PengajuanTempo.jsx
+++ b/src/lib/pengajuan-tempo/component/PengajuanTempo.jsx
@@ -27,6 +27,8 @@ import { toast } from 'react-hot-toast';
 import useDevice from '@/core/hooks/useDevice';
 import odooApi from '~/libs/odooApi';
 import editAuthTempo from '../api/editAuthTempo';
+import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
+import PageContent from '@/lib/content/components/PageContent';
 const PengajuanTempo = () => {
   const { isDesktop, isMobile } = useDevice();
   const [currentStep, setCurrentStep] = React.useState(0);
@@ -137,7 +139,7 @@ const PengajuanTempo = () => {
     validateKontakPerson();
     validatePengiriman();
     validateDokumen();
-    updateHasSave(false);
+    updateHasSave(true);
     if (isFormValid) {
       window.scrollTo({
         top: 0,
@@ -175,7 +177,8 @@ const PengajuanTempo = () => {
           'GET',
           `/api/v1/partner/detail-tempo/${auth.parentId}`
         );
-
+        console.log('original data', dataPaymentTerm);
+        const transformedData = transformKeysToCamelCase(dataPaymentTerm);
         setBigData(transformedData);
       } catch (error) {
         console.error('Error loading dataPaymentTerm:', error);
@@ -213,6 +216,7 @@ const PengajuanTempo = () => {
                   ? JSON.stringify(bigData[key]) // Untuk objek atau array
                   : String(bigData[key]); // Untuk tipe primitif
               // Kirim data yang sudah diubah ke string ke stepDivsUpdateForm
+              console.log('key', key, stringData);
               stepDivsUpdateForm[currentStep](key, stringData);
             }
           });
@@ -225,7 +229,7 @@ const PengajuanTempo = () => {
     validatePengiriman();
     validateDokumen();
     validateSupplier();
-    updateHasSave(false);
+    updateHasSave(true);
   }, [currentStep, bigData, auth]);
 
   const goToNextStep = () => {
@@ -291,15 +295,25 @@ const PengajuanTempo = () => {
         return;
       }
     }
-    const formattedDokumen = Object.entries(formDokumen).map(([key, doc]) => ({
-      documentName: key,
-      details: {
-        name: doc.name,
-        format: doc.format,
-        base64: doc.base64,
-      },
-    }));
+
+    // Filter hanya dokumen dengan `format` yang tidak undefined
+    const formattedDokumen = Object.entries(formDokumen)
+      .filter(([_, doc]) => doc.format !== undefined) // Hanya dokumen dengan `format` tidak undefined
+      .map(([key, doc]) => ({
+        documentName: key,
+        details: {
+          name: doc.name,
+          format: doc.format,
+          base64: doc.base64,
+        },
+      }));
+
     const toastId = toast.loading('Mengirimkan formulir pengajuan tempo...');
+    if (formattedDokumen.length === 0) {
+      // toast.error('Tidak ada dokumen valid untuk dikirim.');
+      return;
+    }
+
     setIsLoading(true);
     try {
       const address = await createPengajuanTempoApi({
@@ -321,12 +335,30 @@ const PengajuanTempo = () => {
       console.error(error);
     }
   };
+
+  const isSupplierDataChanged = (formSupplier, supplierIds) => {
+    if (formSupplier.length !== supplierIds.length) {
+      return true;
+    }
+    return formSupplier.some((supplier, index) => {
+      const original = supplierIds[index];
+      return (
+        supplier.supplier !== original.supplier ||
+        supplier.pic !== original.pic ||
+        supplier.telepon !== original.telepon ||
+        supplier.durasiTempo !== original.durasiTempo ||
+        supplier.creditLimit !== original.creditLimit
+      );
+    });
+  };
+
   const handleDaftarTempoSupplier = async () => {
     for (const error of stepDivsError) {
       if (error.length > 0) {
         return;
       }
     }
+
     const productOrder = formSupplier.map((product) => ({
       supplier: product.supplier,
       pic: product.pic,
@@ -334,7 +366,13 @@ const PengajuanTempo = () => {
       durasiTempo: product.durasiTempo,
       creditLimit: product.creditLimit,
     }));
+
+    // Periksa perubahan
     const toastId = toast.loading('Mengirimkan formulir pengajuan tempo...');
+    if (!isSupplierDataChanged(productOrder, bigData.supplierIds)) {
+      return;
+    }
+
     setIsLoading(true);
     try {
       const address = await createPengajuanTempoApi({
@@ -363,35 +401,23 @@ const PengajuanTempo = () => {
         return;
       }
     }
-    const productOrder = formSupplier.map((product) => ({
-      supplier: product.supplier,
-      pic: product.pic,
-      telepon: product.telepon,
-      durasiTempo: product.durasiTempo,
-      creditLimit: product.creditLimit,
-    }));
 
-    const formattedDokumen = Object.entries(formDokumen).map(([key, doc]) => ({
-      documentName: key,
-      details: {
-        name: doc.name,
-        format: doc.format,
-        base64: doc.base64,
-      },
-    }));
+    // Filter hanya dokumen dengan `format` yang tidak undefined
+    const formattedDokumen = Object.entries(formDokumen)
+      .filter(([_, doc]) => doc.format !== undefined) // Hanya dokumen dengan `format` tidak undefined
+      .map(([key, doc]) => ({
+        documentName: key,
+        details: {
+          name: doc.name,
+          format: doc.format,
+          base64: doc.base64,
+        },
+      }));
 
-    // const data2 = {
-    //   user_id: auth.id,
-    //   ...form,
-    //   ...formKontakPerson,
-    //   ...formPengiriman,
-    //   formDocs: JSON.stringify(formattedDokumen),
-    //   formSupplier: JSON.stringify(productOrder),
-    // };
     const toastId = toast.loading('Mengirimkan formulir pengajuan tempo...');
     setIsLoading(true);
     try {
-      let address5;
+      let address4;
       const address = await createPengajuanTempoApi({
         id: 0,
         partner_id: auth.partnerId,
@@ -415,37 +441,29 @@ const PengajuanTempo = () => {
             tempo_request: false,
             ...formPengiriman,
           });
-          if (address3.id) {
-            const address4 = await createPengajuanTempoApi({
+          if (address3.id && formattedDokumen.length > 0) {
+            // Kirim dokumen yang sudah difilter
+            address4 = await createPengajuanTempoApi({
               id: address3.id,
               partner_id: auth.partnerId,
               user_id: address3.userId,
-              tempo_request: false,
+              tempo_request: true,
               formDocs: JSON.stringify(formattedDokumen),
             });
-            if (address4.id) {
-              address5 = await createPengajuanTempoApi({
-                id: address4.id,
-                partner_id: auth.partnerId,
-                user_id: address4.userId,
-                tempo_request: true,
-                formSupplier: JSON.stringify(productOrder),
-              });
-            }
           }
         }
       }
 
-      if (address5.id) {
+      if (address4?.id) {
         const isUpdated = await editAuthTempo();
         toast.dismiss(toastId);
-        setIsLoading(false);
-        toast.success('Pengajuan tempo berhasil dilakukan');
         if (isUpdated?.user) {
           setAuth(isUpdated.user);
+          setIsLoading(false);
+          toast.success('Pengajuan tempo berhasil dilakukan');
           toast.success('Berhasil mengubah status akun', { duration: 1000 });
           removeFromLocalStorage();
-          router.push('/pengajuan-tempo/finish?tempo_id=SO-2023-06480');
+          router.push('/pengajuan-tempo/finish');
           return;
         }
       }
@@ -479,6 +497,14 @@ const PengajuanTempo = () => {
     }
   };
 
+  const [isCheckedTNC, setIsCheckedTNC] = useState(false);
+
+  const handleCheckChange = (checked) => {
+    setIsCheckedTNC(checked);
+  };
+  console.log('formSupplier', formSupplier);
+  console.log('!hassavedata', hasSavedata);
+  console.log('isCheckedTNC', isCheckedTNC);
   return (
     <>
       <div className='container flex flex-col items-center '>
@@ -507,45 +533,102 @@ const PengajuanTempo = () => {
           className={`flex ${
             isMobile
               ? 'flex-col justify-start items-start'
-              : 'flex-row justify-end items-center'
-          }   gap-4 mb-8`}
+              : 'flex-col justify-end items-end'
+          }    mb-8 gap-2`}
         >
           <span className='text-xs opacity-60'>
             *Pastikan data yang anda masukan sudah benar dan sesuai
           </span>
           {currentStep < 5 && (
-            <Tooltip
-              label={clsxm({
-                'Klik simpan data terlebih dahulu':
-                  currentStep === 3 && !hasSavedata,
-              })}
-            >
+            <>
+              <Tooltip
+                label={clsxm({
+                  'Klik simpan data terlebih dahulu':
+                    currentStep === 3 && !hasSavedata,
+                })}
+              >
+                <Button
+                  colorScheme='red'
+                  w={`${isMobile ? 'full' : 'fit'}`}
+                  isDisabled={
+                    (currentStep === 3 && !hasSavedata) ||
+                    currentStep === NUMBER_OF_STEPS - 1
+                  }
+                  onClick={goToNextStep}
+                >
+                  Langkah Selanjutnya {<ChevronRightIcon className='w-5' />}
+                </Button>
+              </Tooltip>
+            </>
+          )}
+          {currentStep == 5 && (
+            <div className='flex flex-col items-end justify-start gap-4'>
+              <TempoTermCondition onCheckChange={handleCheckChange} />
               <Button
                 colorScheme='red'
-                w={`${isMobile ? 'full' : 'fit'}`}
-                isDisabled={
-                  (currentStep === 3 && !hasSavedata) ||
-                  currentStep === NUMBER_OF_STEPS - 1
-                }
-                onClick={goToNextStep}
+                w={`${isMobile ? 'full' : '36'}`}
+                isDisabled={!isCheckedTNC}
+                onClick={handleDaftarTempo}
               >
-                Langkah Selanjutnya {<ChevronRightIcon className='w-5' />}
+                Daftar Tempo {<ChevronRightIcon className='w-5' />}
               </Button>
-            </Tooltip>
-          )}
-          {currentStep == 5 && (
-            <Button
-              colorScheme='red'
-              w={`${isMobile ? 'full' : 'fit'}`}
-              onClick={handleDaftarTempo}
-            >
-              Daftar Tempo {<ChevronRightIcon className='w-5' />}
-            </Button>
+            </div>
           )}
         </div>
       </div>
     </>
   );
 };
+const TempoTermCondition = ({ onCheckChange }) => {
+  const [isCheckedTNC, SetIsCheckedTNC] = useState(false);
+  const [openTNC, SetOpenTNC] = useState(false);
+
+  const openTNCHandle = () => {
+    SetOpenTNC(!openTNC);
+  };
+
+  const toggleCheckTNC = () => {
+    const newValue = !isCheckedTNC;
+    SetIsCheckedTNC(newValue);
+    if (onCheckChange) {
+      onCheckChange(newValue);
+    }
+  };
+  return (
+    <>
+      <div className='flex items-center gap-x-2'>
+        <Checkbox
+          id='tnc'
+          name='tnc'
+          colorScheme='red'
+          isChecked={isCheckedTNC}
+          onChange={toggleCheckTNC}
+        />
+        <div>
+          <label htmlFor='tnc' className='cursor-pointer'>
+            Dengan ini saya menyetujui
+          </label>{' '}
+          <span
+            className='font-medium text-danger-500 cursor-pointer'
+            onClick={openTNCHandle}
+          >
+            syarat dan ketentuan
+          </span>
+          <label htmlFor='tnc' className='ml-2 cursor-pointer'>
+            yang berlaku
+          </label>
+        </div>
+      </div>
+
+      <BottomPopup
+        active={openTNC}
+        close={() => SetOpenTNC(false)}
+        title='Syarat & Ketentuan Pendaftaran Tempo'
+      >
+        <PageContent path='/tempoTnd' />
+      </BottomPopup>
+    </>
+  );
+};
 
 export default PengajuanTempo;
-- 
cgit v1.2.3

