import { ChangeEvent, useEffect, useMemo, useRef, useState, MouseEvent, } from 'react'; import { useMutation } from 'react-query'; import { useRegisterStore } from '../stores/useRegisterStore'; import { Button, Checkbox, UseToastOptions, color, useToast, } from '@chakra-ui/react'; import getFileBase64 from '@/core/utils/getFileBase64'; import { Controller, useForm } from 'react-hook-form'; import HookFormSelect from '@/core/components/elements/Select/HookFormSelect'; import odooApi from '~/libs/odooApi'; import { toast } from 'react-hot-toast'; import { EyeIcon, CheckCircleIcon, XCircleIcon, } from '@heroicons/react/24/outline'; import BottomPopup from '@/core/components/elements/Popup/BottomPopup'; import Image from 'next/image'; import useDevice from '@/core/hooks/useDevice'; import useAuth from '@/core/hooks/useAuth'; interface FormProps { type: string; required: boolean; isPKP: boolean; chekValid: boolean; buttonSubmitClick: boolean; } interface industry_id { label: string; value: string; category: string; } interface companyType { value: string; label: string; } interface Auth { id: string; parentId: string; } const form: React.FC = ({ type, required, isPKP, chekValid, buttonSubmitClick, }) => { const { form, errors, updateForm, validate } = useRegisterStore(); const { control, watch, setValue } = useForm(); const [selectedCategory, setSelectedCategory] = useState(''); const [isChekBox, setIsChekBox] = useState(false); const [isExample, setIsExample] = useState(false); const { isDesktop, isMobile } = useDevice(); // Inside your component const [formattedNpwp, setFormattedNpwp] = useState(''); // State for formatted NPWP const [unformattedNpwp, setUnformattedNpwp] = useState(''); // State for unformatted NPWP const auth = useAuth() as unknown as Auth; const [industries, setIndustries] = useState([]); const [companyTypes, setCompanyTypes] = useState([]); const toast = useToast(); const emailRef = useRef(null); const businessNameRef = useRef(null); const companyTypeRef = useRef(null); const industryRef = useRef(null); const addressRef = useRef(null); const namaWajibPajakRef = useRef(null); const alamatWajibPajakRef = useRef(null); const npwpRef = useRef(null); const sppkpRef = useRef(null); const docsSppkpRef = useRef(null); const docsNpwpRef = useRef(null); useEffect(() => { const loadCompanyTypes = async () => { const dataCompanyTypes = await odooApi( 'GET', '/api/v1/partner/company_type' ); setCompanyTypes( dataCompanyTypes?.map((o: { id: any; name: any }) => ({ value: o.id, label: o.name, })) ); // setValue('companyType', form.company_type_id); }; loadCompanyTypes(); }, []); useEffect(() => { if (form.company_type_id) { setValue('companyType', parseInt(form.company_type_id)); } }, [form.company_type_id]); useEffect(() => { if (form.industry_id) { setValue('industry_id', parseInt(form.industry_id)); } }, [form.industry_id]); useEffect(() => { const loadIndustries = async () => { const dataIndustries = await odooApi('GET', '/api/v1/partner/industry'); setIndustries( dataIndustries?.map((o: { id: any; name: any; category: any }) => ({ value: o.id, label: o.name, category: o.category, })) ); // setValue('industry_id', form.industry_id); }; loadIndustries(); }, []); const handleInputChange = (event: ChangeEvent) => { const { name, value } = event.target; updateForm('type_acc', 'business'); updateForm('is_pkp', `${isPKP}`); // Update form dengan nilai terbaru dari input yang berubah updateForm(name, value); // Jika checkbox aktif, sinkronisasi alamat_wajib_pajak dengan alamat_bisnis if (isChekBox) { if (name === 'alamat_wajib_pajak') { updateForm('alamat_bisnis', value); } else if (name === 'alamat_bisnis') { updateForm('alamat_wajib_pajak', value); } } // Validasi setelah perubahan dilakukan validate(); }; const handleInputChangeNpwp = (event: ChangeEvent) => { const { name, value } = event.target; updateForm('type_acc', `business`); updateForm('is_pkp', `${isPKP}`); updateForm('npwp', value); validate(); }; const handleChange = (event: ChangeEvent) => { setIsChekBox(!isChekBox); }; const formatNpwp = (value: string) => { try { const cleaned = ('' + value).replace(/\D/g, ''); let match; if (cleaned.length <= 15) { match = cleaned.match( /(\d{0,2})?(\d{0,3})?(\d{0,3})?(\d{0,1})?(\d{0,3})?(\d{0,3})$/ ); } else { match = cleaned.match( /(\d{0,3})?(\d{0,3})?(\d{0,3})?(\d{0,1})?(\d{0,3})?(\d{0,3})$/ ); } if (match) { return [ match[1], match[2] ? '.' : '', match[2], match[3] ? '.' : '', match[3], match[4] ? '.' : '', match[4], match[5] ? '-' : '', match[5], match[6] ? '.' : '', match[6], ].join(''); } // If match is null, return the original cleaned string or handle as needed return cleaned; } catch (error) { // Handle error or return a default value console.error('Error formatting NPWP:', error); return value; } }; useEffect(() => { if (isChekBox) { updateForm('isChekBox', 'true'); updateForm('alamat_wajib_pajak', `${form.alamat_bisnis}`); validate(); } else { updateForm('isChekBox', 'false'); validate(); } }, [isChekBox]); const handleFileChange = async (event: ChangeEvent) => { const toastProps: UseToastOptions = { duration: 5000, isClosable: true, position: 'top', }; let fileBase64 = ''; const { name } = event.target; const file = event.target.files?.[0]; // Allowed file extensions const allowedExtensions = ['pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg']; if (file) { const fileExtension = file.name.split('.').pop()?.toLowerCase(); // Extract file extension // Check if the file extension is allowed if (!fileExtension || !allowedExtensions.includes(fileExtension)) { toast({ ...toastProps, title: 'Format file yang diijinkan adalah .pdf, .png, .jpg, atau .jpeg', status: 'error', }); event.target.value = ''; return; } // Check for file size if (file.size > 2000000) { toast({ ...toastProps, title: 'Maksimal ukuran file adalah 2MB', status: 'error', }); event.target.value = ''; return; } // Convert file to Base64 fileBase64 = await getFileBase64(file); updateForm(name, fileBase64); // Update form with the Base64 string validate(); // Perform form validation } }; const isFormValid = useMemo(() => Object.keys(errors).length === 0, [errors]); useEffect(() => { const loadIndustries = async () => { if (!isFormValid) { const options: ScrollIntoViewOptions = { behavior: 'smooth', block: 'center', }; if (errors.email_partner && emailRef.current) { emailRef.current.scrollIntoView(options); return; } if (errors.company_type_id && companyTypeRef.current) { companyTypeRef.current.scrollIntoView(options); return; } if (errors.business_name && businessNameRef.current) { businessNameRef.current.scrollIntoView(options); return; } if (errors.industry_id && industryRef.current) { industryRef.current.scrollIntoView(options); return; } if (errors.alamat_bisnis && addressRef.current) { addressRef.current.scrollIntoView(options); return; } if (errors.npwp && npwpRef.current) { npwpRef.current.scrollIntoView(options); return; } if (errors.sppkp && sppkpRef.current) { sppkpRef.current.scrollIntoView(options); return; } if (errors.sppkp_document && docsSppkpRef.current) { docsSppkpRef.current.scrollIntoView(options); return; } if (errors.npwp_document && docsNpwpRef.current) { docsNpwpRef.current.scrollIntoView(options); return; } } }; loadIndustries(); }, [buttonSubmitClick, chekValid]); const handleCompanyTypeChange = (event: MouseEvent) => { const selectedCompanyTypeValue = watch('companyType'); const selectedCompanyType = companyTypes.find( (company) => company.value === selectedCompanyTypeValue ); if (selectedCompanyType !== undefined) { updateForm('company_type_id', `${selectedCompanyType.value}`); validate(); } }; const handleIndustriIdChange = (event: MouseEvent) => { const selectedIndustriIdValue = watch('industry_id'); const selectedIndustryType = industries.find( (industry) => industry.value === selectedIndustriIdValue ); if (selectedIndustryType) { updateForm('industry_id', `${selectedIndustryType?.value}`); setSelectedCategory(selectedIndustryType.category); validate(); } }; const [fileUrl, setFileUrl] = useState(''); const [popUpNPWP, setPopUpNpwp] = useState(false); const [popSppkp, setPopUpSppkp] = useState(false); const [hasNPWP, setHasNpwp] = useState(false); const [hasSPPKP, setHasSPPKP] = useState(false); const [fileUrlSppkp, setFileUrlSppkp] = useState(''); useEffect(() => { const checkUrlNPWP = async (url: string | URL | Request) => { try { const response = await odooApi( 'GET', `/api/v1/user/chek/npwp/${auth?.parentId}` ); return response.status; // Returns true if status is 200-299 } catch (error) { console.error('Error accessing URL:', url, error); return false; } }; const checkUrlSPPKP = async (url: string | URL | Request) => { try { const response = await odooApi( 'GET', `/api/v1/user/chek/sppkp/${auth?.parentId}` ); return response.status; // Returns true if status is 200-299 } catch (error) { console.error('Error accessing URL:', url, error); return false; } }; const npwpUrl = `${process.env.NEXT_PUBLIC_ODOO_API_HOST}/api/v1/user/download/npwp/${auth?.parentId}`; const sppkpUrl = `${process.env.NEXT_PUBLIC_ODOO_API_HOST}/api/v1/user/download/sppkp/${auth?.parentId}`; if (auth?.parentId) { checkUrlNPWP(npwpUrl).then((isAccessible) => { if (isAccessible) { setFileUrl(npwpUrl); setHasNpwp(true); updateForm('npwp_document', ' '); } }); checkUrlSPPKP(sppkpUrl).then((isAccessible) => { if (isAccessible) { setFileUrlSppkp(sppkpUrl); setHasSPPKP(true); updateForm('sppkp_document', ' '); } }); } }, [auth?.parentId]); return ( <> setPopUpNpwp(false)} >
setPopUpSppkp(false)} >
setIsExample(false)} >
Contoh SPPKP
{chekValid && !required && isPKP && !!errors.email_partner && ( {errors.email_partner} )}
( )} /> {chekValid && !required && !!errors.company_type_id && ( {errors.company_type_id} )}
{chekValid && !!errors.business_name && ( {errors.business_name} )}
( )} />
{selectedCategory && ( Kategori : {selectedCategory} )} {chekValid && !required && !!errors.industry_id && ( {errors.industry_id} )}
{chekValid && !required && !!errors.alamat_bisnis && ( {errors.alamat_bisnis} )}
{chekValid && isPKP && !required && !!errors.nama_wajib_pajak && ( {errors.nama_wajib_pajak} )}
{chekValid && isPKP && !required && !!errors.alamat_wajib_pajak && ( {errors.alamat_wajib_pajak} )}
{ if (!required) { const unformatted = e.target.value.replace(/\D/g, ''); // Remove all non-digit characters const formattedValue = formatNpwp(unformatted); // Format the value setUnformattedNpwp(unformatted); // Store unformatted value setFormattedNpwp(formattedValue); // Store formatted value handleInputChangeNpwp({ ...e, target: { ...e.target, value: unformatted }, }); // Update form state with unformatted value } }} aria-invalid={chekValid && !required && !!errors.npwp} /> {chekValid && !required && !!errors.npwp && ( {errors.npwp} )}
{chekValid && !required && !!errors.sppkp && ( {errors.sppkp} )}
{chekValid && isPKP && !required && !!errors.npwp_document && ( {errors.npwp_document} )} Format: .pdf, .png, .jpg, atau .jpeg, Maks 2MB {hasNPWP && (
Dokumen sudah diupload
setPopUpNpwp(true)} className={`w-6 mr-2 hover:scale-110 transition-transform duration-200}`} /> setHasNpwp(false)} className='w-6 hover:scale-110 transition-transform duration-200' />
)}
{chekValid && isPKP && !required && !!errors.sppkp_document && ( {errors.sppkp_document} )} Format: .pdf, .png, .jpg, atau .jpeg, Maks 2MB {hasSPPKP && (
Dokumen sudah di upload
setPopUpSppkp(true)} className={`w-6 mr-2 hover:scale-110 transition-transform duration-200}`} /> setHasSPPKP(false)} className='w-6 hover:scale-110 transition-transform duration-200' />
)}
); }; export default form;