From 6bbf1dbd94355f34f58f4b72f134f3dbeac776aa Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Sat, 23 Nov 2024 11:55:59 +0700
Subject: <iman> update tempo

---
 .../pengajuan-tempo/component/PengajuanTempo.jsx   | 228 +++++++++++++++++++--
 1 file changed, 210 insertions(+), 18 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 d0e1fcc6..fc558b01 100644
--- a/src/lib/pengajuan-tempo/component/PengajuanTempo.jsx
+++ b/src/lib/pengajuan-tempo/component/PengajuanTempo.jsx
@@ -7,7 +7,7 @@ import Pengiriman from './Pengiriman';
 import Referensi from './Referensi';
 import Dokumen from './Dokumen';
 import Konfirmasi from './Konfirmasi';
-import useAuth from '@/core/hooks/useAuth';
+import { getAuth } from '~/libs/auth';
 import { useRouter } from 'next/router';
 import { Controller, useForm } from 'react-hook-form';
 import {
@@ -23,14 +23,17 @@ import { Button, Checkbox, Spinner, Tooltip } from '@chakra-ui/react';
 import clsxm from '~/libs/clsxm';
 import { toast } from 'react-hot-toast';
 import useDevice from '@/core/hooks/useDevice';
+import odooApi from '~/libs/odooApi';
 const PengajuanTempo = () => {
   const { isDesktop, isMobile } = useDevice();
   const [currentStep, setCurrentStep] = React.useState(0);
   const NUMBER_OF_STEPS = 6;
   const [isLoading, setIsLoading] = useState(false);
+  const [bigData, setBigData] = useState();
+  const [idTempo, setIdTempo] = useState(0);
   const { form, errors, validate, updateForm } = usePengajuanTempoStore();
   const { control, watch, setValue } = useForm();
-  const auth = useAuth();
+  const auth = getAuth();
   const router = useRouter();
   const { formDokumen, errorsDokumen, validateDokumen, updateFormDokumen } =
     usePengajuanTempoStoreDokumen();
@@ -131,48 +134,230 @@ const PengajuanTempo = () => {
     validatePengiriman();
     validateDokumen();
     updateHasSave(false);
-
+    if (isFormValid) {
+      window.scrollTo({
+        top: 0,
+        behavior: 'smooth',
+      });
+    }
+  }, [currentStep, buttonSubmitClick]);
+  useEffect(() => {
     window.scrollTo({
       top: 0,
       behavior: 'smooth',
     });
-  }, [currentStep, buttonSubmitClick]);
+  }, [currentStep]);
 
   useEffect(() => {
-    const cachedData = getFromLocalStorage(stepLabels[currentStep]);
+    const loadBigData = async () => {
+      const toCamelCase = (str) =>
+        str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
+
+      const transformKeysToCamelCase = (data) => {
+        if (Array.isArray(data)) {
+          return data.map((item) => transformKeysToCamelCase(item));
+        } else if (data && typeof data === 'object') {
+          return Object.keys(data).reduce((acc, key) => {
+            const camelKey = toCamelCase(key); // Ubah kunci menjadi camelCase
+            acc[camelKey] = transformKeysToCamelCase(data[key]); // Rekursif untuk nested object atau array
+            return acc;
+          }, {});
+        }
+        return data; // Jika bukan object atau array, kembalikan nilai aslinya
+      };
+
+      try {
+        const dataPaymentTerm = await odooApi(
+          'GET',
+          `/api/v1/partner/detail-tempo/${auth.parentId}`
+        );
+
+        console.log('Original dataPaymentTerm', dataPaymentTerm);
+
+        const transformedData = transformKeysToCamelCase(dataPaymentTerm);
+
+        console.log('Transformed dataPaymentTerm', transformedData);
+
+        setBigData(transformedData);
+      } catch (error) {
+        console.error('Error loading dataPaymentTerm:', error);
+      }
+    };
+
+    loadBigData();
+  }, []);
+
+  console.log('bigData', bigData);
+
+  useEffect(() => {
+    const cachedData = bigData;
+    console.log('data_lama', getFromLocalStorage(stepLabels[currentStep]));
+    console.log('cachedData', cachedData);
+
     if (cachedData) {
-      if (currentStep == 3) {
+      // Ambil kunci-kunci yang relevan berdasarkan currentStep dari stepDivsForm
+      const formKeys = stepDivsForm[currentStep]
+        ? Object.keys(stepDivsForm[currentStep])
+        : [];
+      console.log('formKeys', formKeys);
+      if (currentStep === 3) {
         stepDivsUpdateForm[currentStep](cachedData);
-      } else if (currentStep == 4) {
-        Object.keys(cachedData).forEach((key) => {
-          const { name, format, base64 } = cachedData[key];
-          stepDivsUpdateForm[currentStep](key, name, format, base64);
+      } else if (currentStep === 4) {
+        formKeys.forEach((key) => {
+          if (cachedData[key]) {
+            // Proses hanya kunci yang ada di cachedData
+            const { name, format, base64 } = cachedData[key];
+            stepDivsUpdateForm[currentStep](key, name, format, base64);
+          }
         });
       } else {
-        Object.keys(cachedData).forEach((key) => {
-          stepDivsUpdateForm[currentStep](key, cachedData[key]);
+        formKeys.forEach((key) => {
+          if (cachedData[key]) {
+            // Ubah data menjadi string
+            const stringData =
+              typeof cachedData[key] === 'object'
+                ? JSON.stringify(cachedData[key]) // Untuk objek atau array
+                : String(cachedData[key]); // Untuk tipe primitif
+
+            // Kirim data yang sudah diubah ke string ke stepDivsUpdateForm
+            stepDivsUpdateForm[currentStep](key, stringData);
+          }
         });
       }
     }
+
     validate();
     validateKontakPerson();
     validatePengiriman();
     validateDokumen();
     updateHasSave(false);
-  }, [currentStep]);
+  }, [currentStep, bigData]);
+
   const goToNextStep = () => {
     if (!isFormValid) {
       setNotValid(true);
       setButtonSubmitClick(!buttonSubmitClick);
       return;
     } else {
-      saveToLocalStorage(stepLabels[currentStep], stepDivsForm[currentStep]);
+      // saveToLocalStorage(stepLabels[currentStep], stepDivsForm[currentStep]);
+      if (currentStep == 3) {
+        handleDaftarTempoSupplier();
+      } else if (currentStep == 4) {
+        handleDaftarTempoDokumen();
+      } else {
+        handleDaftarTempoPerPage(
+          stepLabels[currentStep],
+          stepDivsForm[currentStep]
+        );
+      }
       setButtonSubmitClick(!buttonSubmitClick);
       setNotValid(false);
     }
     setCurrentStep((prev) => (prev === NUMBER_OF_STEPS - 1 ? prev : prev + 1));
   };
 
+  const handleDaftarTempoPerPage = async (
+    label,
+    formData,
+    tempoRequest = false
+  ) => {
+    for (const error of stepDivsError) {
+      if (error.length > 0) {
+        return;
+      }
+    }
+    const toastId = toast.loading('Mengirimkan formulir pengajuan tempo...');
+    setIsLoading(true);
+    try {
+      const address = await createPengajuanTempoApi({
+        id: idTempo,
+        user_id: auth.parentId,
+        section: label,
+        tempo_request: tempoRequest,
+        ...formData,
+      });
+      if (address.id) {
+        setIdTempo(address.id);
+      }
+      toast.dismiss(toastId);
+      setIsLoading(false);
+    } catch (error) {
+      toast.dismiss(toastId);
+      setIsLoading(false);
+
+      toast.error('Terjadi kesalahan dalam pengiriman formulir');
+      console.error(error);
+    }
+  };
+  const handleDaftarTempoDokumen = async () => {
+    for (const error of stepDivsError) {
+      if (error.length > 0) {
+        return;
+      }
+    }
+    const formattedDokumen = Object.entries(formDokumen).map(([key, doc]) => ({
+      documentName: key,
+      details: {
+        name: doc.name,
+        format: doc.format,
+        base64: doc.base64,
+      },
+    }));
+    const toastId = toast.loading('Mengirimkan formulir pengajuan tempo...');
+    setIsLoading(true);
+    try {
+      const address = await createPengajuanTempoApi({
+        id: idTempo,
+        user_id: auth.parentId,
+        formDocs: JSON.stringify(formattedDokumen),
+      });
+      if (address.id) {
+        setIdTempo(address.id);
+      }
+      toast.dismiss(toastId);
+      setIsLoading(false);
+    } catch (error) {
+      toast.dismiss(toastId);
+      setIsLoading(false);
+
+      toast.error('Terjadi kesalahan dalam pengiriman formulir');
+      console.error(error);
+    }
+  };
+  const handleDaftarTempoSupplier = async () => {
+    for (const error of stepDivsError) {
+      if (error.length > 0) {
+        return;
+      }
+    }
+    const productOrder = formSupplier.map((product) => ({
+      supplier: product.supplier,
+      pic: product.pic,
+      telepon: product.telepon,
+      durasiTempo: product.durasiTempo,
+      creditLimit: product.creditLimit,
+    }));
+    const toastId = toast.loading('Mengirimkan formulir pengajuan tempo...');
+    setIsLoading(true);
+    try {
+      const address = await createPengajuanTempoApi({
+        id: idTempo,
+        user_id: auth.parentId,
+        formDocs: JSON.stringify(productOrder),
+      });
+      if (address.id) {
+        setIdTempo(address.id);
+      }
+      toast.dismiss(toastId);
+      setIsLoading(false);
+    } catch (error) {
+      toast.dismiss(toastId);
+      setIsLoading(false);
+
+      toast.error('Terjadi kesalahan dalam pengiriman formulir');
+      console.error(error);
+    }
+  };
   const handleDaftarTempo = async () => {
     for (const error of stepDivsError) {
       if (error.length > 0) {
@@ -195,6 +380,11 @@ const PengajuanTempo = () => {
         base64: doc.base64,
       },
     }));
+    if (currentStep == 3) {
+      formData = JSON.stringify(productOrder);
+    } else if (currentStep == 4) {
+      formData = JSON.stringify(formattedDokumen);
+    }
 
     const data2 = {
       user_id: auth.id,
@@ -209,8 +399,10 @@ const PengajuanTempo = () => {
     try {
       let address5;
       const address = await createPengajuanTempoApi({
-        id: '0',
-        user_id: auth.id,
+        id: 0,
+        user_id: auth.parentId,
+        section: label,
+        tempo_request: tempoRequest,
         ...form,
       });
       if (address.id) {
@@ -247,7 +439,7 @@ const PengajuanTempo = () => {
 
       if (address5.id) {
         toast.success('Pengajuan tempo berhasil dilakukan');
-        // removeFromLocalStorage();
+        removeFromLocalStorage();
         router.push('/pengajuan-tempo/finish?tempo_id=SO-2023-06480');
       }
     } catch (error) {
@@ -338,7 +530,7 @@ const PengajuanTempo = () => {
             <Button
               colorScheme='red'
               w={`${isMobile ? 'full' : 'fit'}`}
-              onClick={handleDaftarTempo}
+              onClick={handleDaftarTempo()}
             >
               Daftar Tempo {<ChevronRightIcon className='w-5' />}
             </Button>
-- 
cgit v1.2.3

