From 81f06d02bef8701be568e7418828d925925c5b12 Mon Sep 17 00:00:00 2001
From: it-fixcomart <it@fixcomart.co.id>
Date: Fri, 20 Sep 2024 10:58:20 +0700
Subject: <iman> update new register disebled email

---
 src/lib/address/components/CreateAddress.jsx | 205 +++++++++++++++++----------
 1 file changed, 131 insertions(+), 74 deletions(-)

(limited to 'src/lib/address/components/CreateAddress.jsx')

diff --git a/src/lib/address/components/CreateAddress.jsx b/src/lib/address/components/CreateAddress.jsx
index 86519147..e315affe 100644
--- a/src/lib/address/components/CreateAddress.jsx
+++ b/src/lib/address/components/CreateAddress.jsx
@@ -1,76 +1,101 @@
-import HookFormSelect from '@/core/components/elements/Select/HookFormSelect'
-import useAuth from '@/core/hooks/useAuth'
-import { useRouter } from 'next/router'
-import { Controller, useForm } from 'react-hook-form'
-import * as Yup from 'yup'
-import cityApi from '../api/cityApi'
-import districtApi from '../api/districtApi'
-import subDistrictApi from '../api/subDistrictApi'
-import { useEffect, useState } from 'react'
-import createAddressApi from '../api/createAddressApi'
-import { toast } from 'react-hot-toast'
-import { yupResolver } from '@hookform/resolvers/yup'
-import Menu from '@/lib/auth/components/Menu'
+import HookFormSelect from '@/core/components/elements/Select/HookFormSelect';
+import useAuth from '@/core/hooks/useAuth';
+import { useRouter } from 'next/router';
+import { Controller, useForm } from 'react-hook-form';
+import * as Yup from 'yup';
+import cityApi from '../api/cityApi';
+import districtApi from '../api/districtApi';
+import subDistrictApi from '../api/subDistrictApi';
+import { useEffect, useState } from 'react';
+import createAddressApi from '../api/createAddressApi';
+import { toast } from 'react-hot-toast';
+import { yupResolver } from '@hookform/resolvers/yup';
+import Menu from '@/lib/auth/components/Menu';
+import useAddresses from '../hooks/useAddresses';
 
 const CreateAddress = () => {
-  const auth = useAuth()
-  const router = useRouter()
+  const auth = useAuth();
+  const router = useRouter();
   const {
     register,
     formState: { errors },
     handleSubmit,
     watch,
     setValue,
-    control
+    control,
   } = useForm({
     resolver: yupResolver(validationSchema),
-    defaultValues
-  })
-
-  const [cities, setCities] = useState([])
-  const [districts, setDistricts] = useState([])
-  const [subDistricts, setSubDistricts] = useState([])
+    defaultValues,
+  });
+  const { addresses = [] } = useAddresses(); // Ensure addresses is an array
+  const [cities, setCities] = useState([]);
+  const [districts, setDistricts] = useState([]);
+  const [subDistricts, setSubDistricts] = useState([]);
+  const [filteredTypes, setFilteredTypes] = useState(types); // State to manage filtered types
 
   useEffect(() => {
     const loadCities = async () => {
-      let dataCities = await cityApi()
-      dataCities = dataCities.map((city) => ({ value: city.id, label: city.name }))
-      setCities(dataCities)
+      let dataCities = await cityApi();
+      dataCities = dataCities.map((city) => ({
+        value: city.id,
+        label: city.name,
+      }));
+      setCities(dataCities);
+    };
+    loadCities();
+  }, []);
+
+  useEffect(() => {
+    if (addresses) {
+      let hasContactAddress = false;
+
+      for (let i = 0; i < addresses?.data?.length; i++) {
+        if (addresses.data[i].type === 'contact') {
+          hasContactAddress = true;
+          break;
+        }
+      }
+      if (hasContactAddress) {
+        setFilteredTypes(types.filter((type) => type.value !== 'contact'));
+      } else {
+        setFilteredTypes(types);
+      }
     }
-    loadCities()
-  }, [])
+  }, [auth]);
 
-  const watchCity = watch('city')
+  const watchCity = watch('city');
   useEffect(() => {
-    setValue('district', '')
+    setValue('district', '');
     if (watchCity) {
       const loadDistricts = async () => {
-        let dataDistricts = await districtApi({ cityId: watchCity })
+        let dataDistricts = await districtApi({ cityId: watchCity });
         dataDistricts = dataDistricts.map((district) => ({
           value: district.id,
-          label: district.name
-        }))
-        setDistricts(dataDistricts)
-      }
-      loadDistricts()
+          label: district.name,
+        }));
+        setDistricts(dataDistricts);
+      };
+      loadDistricts();
     }
-  }, [watchCity, setValue])
+  }, [watchCity, setValue]);
 
-  const watchDistrict = watch('district')
+  const watchDistrict = watch('district');
   useEffect(() => {
-    setValue('subDistrict', '')
+    setValue('subDistrict', '');
     if (watchDistrict) {
       const loadSubDistricts = async () => {
-        let dataSubDistricts = await subDistrictApi({ districtId: watchDistrict })
+        let dataSubDistricts = await subDistrictApi({
+          districtId: watchDistrict,
+        });
         dataSubDistricts = dataSubDistricts.map((district) => ({
           value: district.id,
-          label: district.name
-        }))
-        setSubDistricts(dataSubDistricts)
-      }
-      loadSubDistricts()
+          label: district.name,
+        }));
+        setSubDistricts(dataSubDistricts);
+      };
+      loadSubDistricts();
     }
-  }, [watchDistrict, setValue])
+  }, [watchDistrict, setValue]);
 
   const onSubmitHandler = async (values) => {
     const data = {
@@ -78,15 +103,15 @@ const CreateAddress = () => {
       city_id: values.city,
       district_id: values.district,
       sub_district_id: values.subDistrict,
-      parent_id: auth.partnerId
-    }
+      parent_id: auth.partnerId,
+    };
 
-    const address = await createAddressApi({ data })
+    const address = await createAddressApi({ data });
     if (address?.id) {
-      toast.success('Berhasil menambahkan alamat')
-      router.back()
+      toast.success('Berhasil menambahkan alamat');
+      router.back();
     }
-  }
+  };
 
   return (
     <div className='max-w-none md:container mx-auto flex p-0 md:py-10'>
@@ -102,10 +127,16 @@ const CreateAddress = () => {
                 name='type'
                 control={control}
                 render={(props) => (
-                  <HookFormSelect {...props} isSearchable={false} options={types} />
+                  <HookFormSelect
+                    {...props}
+                    isSearchable={false}
+                    options={filteredTypes}
+                  />
                 )}
               />
-              <div className='text-caption-2 text-danger-500 mt-1'>{errors.type?.message}</div>
+              <div className='text-caption-2 text-danger-500 mt-1'>
+                {errors.type?.message}
+              </div>
             </div>
 
             <div>
@@ -116,7 +147,9 @@ const CreateAddress = () => {
                 type='text'
                 className='form-input'
               />
-              <div className='text-caption-2 text-danger-500 mt-1'>{errors.name?.message}</div>
+              <div className='text-caption-2 text-danger-500 mt-1'>
+                {errors.name?.message}
+              </div>
             </div>
 
             <div>
@@ -127,7 +160,9 @@ const CreateAddress = () => {
                 type='email'
                 className='form-input'
               />
-              <div className='text-caption-2 text-danger-500 mt-1'>{errors.email?.message}</div>
+              <div className='text-caption-2 text-danger-500 mt-1'>
+                {errors.email?.message}
+              </div>
             </div>
 
             <div>
@@ -138,7 +173,9 @@ const CreateAddress = () => {
                 type='tel'
                 className='form-input'
               />
-              <div className='text-caption-2 text-danger-500 mt-1'>{errors.mobile?.message}</div>
+              <div className='text-caption-2 text-danger-500 mt-1'>
+                {errors.mobile?.message}
+              </div>
             </div>
 
             <div>
@@ -149,7 +186,9 @@ const CreateAddress = () => {
                 type='text'
                 className='form-input'
               />
-              <div className='text-caption-2 text-danger-500 mt-1'>{errors.street?.message}</div>
+              <div className='text-caption-2 text-danger-500 mt-1'>
+                {errors.street?.message}
+              </div>
             </div>
 
             <div>
@@ -160,7 +199,9 @@ const CreateAddress = () => {
                 type='number'
                 className='form-input'
               />
-              <div className='text-caption-2 text-danger-500 mt-1'>{errors.zip?.message}</div>
+              <div className='text-caption-2 text-danger-500 mt-1'>
+                {errors.zip?.message}
+              </div>
             </div>
 
             <div>
@@ -168,9 +209,13 @@ const CreateAddress = () => {
               <Controller
                 name='city'
                 control={control}
-                render={(props) => <HookFormSelect {...props} options={cities} />}
+                render={(props) => (
+                  <HookFormSelect {...props} options={cities} />
+                )}
               />
-              <div className='text-caption-2 text-danger-500 mt-1'>{errors.city?.message}</div>
+              <div className='text-caption-2 text-danger-500 mt-1'>
+                {errors.city?.message}
+              </div>
             </div>
 
             <div>
@@ -179,10 +224,16 @@ const CreateAddress = () => {
                 name='district'
                 control={control}
                 render={(props) => (
-                  <HookFormSelect {...props} options={districts} disabled={!watchCity} />
+                  <HookFormSelect
+                    {...props}
+                    options={districts}
+                    disabled={!watchCity}
+                  />
                 )}
               />
-              <div className='text-caption-2 text-danger-500 mt-1'>{errors.district?.message}</div>
+              <div className='text-caption-2 text-danger-500 mt-1'>
+                {errors.district?.message}
+              </div>
             </div>
 
             <div>
@@ -191,31 +242,37 @@ const CreateAddress = () => {
                 name='subDistrict'
                 control={control}
                 render={(props) => (
-                  <HookFormSelect {...props} options={subDistricts} disabled={!watchDistrict} />
+                  <HookFormSelect
+                    {...props}
+                    options={subDistricts}
+                    disabled={!watchDistrict}
+                  />
                 )}
               />
             </div>
           </div>
 
-          <button type='submit' className='btn-yellow w-full md:w-fit mt-6 ml-0 md:ml-auto'>
+          <button
+            type='submit'
+            className='btn-yellow w-full md:w-fit mt-6 ml-0 md:ml-auto'
+          >
             Simpan
           </button>
         </form>
       </div>
     </div>
-  )
-}
+  );
+};
 
 const validationSchema = Yup.object().shape({
   type: Yup.string().required('Harus di-pilih'),
   name: Yup.string().min(3, 'Minimal 3 karakter').required('Harus di-isi'),
-  // email: Yup.string().email('Format harus seperti contoh@email.com').required('Harus di-isi'),
   mobile: Yup.string().required('Harus di-isi'),
   street: Yup.string().required('Harus di-isi'),
   zip: Yup.string().required('Harus di-isi'),
   city: Yup.string().required('Harus di-pilih'),
-  district: Yup.string().required('Harus di-pilih')
-})
+  district: Yup.string().required('Harus di-pilih'),
+});
 
 const defaultValues = {
   type: '',
@@ -226,14 +283,14 @@ const defaultValues = {
   city: '',
   district: '',
   subDistrict: '',
-  zip: ''
-}
+  zip: '',
+};
 
 const types = [
   { value: 'contact', label: 'Contact Address' },
   { value: 'invoice', label: 'Invoice Address' },
   { value: 'delivery', label: 'Delivery Address' },
-  { value: 'other', label: 'Other Address' }
-]
+  { value: 'other', label: 'Other Address' },
+];
 
-export default CreateAddress
+export default CreateAddress;
-- 
cgit v1.2.3

