summaryrefslogtreecommitdiff
path: root/src-migrate/modules/register/components/FormBisnis.tsx
blob: 1004d944489c73f0172918784191bf588af9136b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
import { ChangeEvent, useEffect, useMemo, useState } from "react";
import { useMutation } from "react-query";
import { useRegisterStore } from "../stores/useRegisterStore";
import { RegisterProps } from "~/types/auth";
import { registerUser } from "~/services/auth";
import { useRouter } from "next/router";
import { Button, Checkbox, UseToastOptions, color, useToast } from "@chakra-ui/react";
import Link from "next/link";
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
} from '@heroicons/react/24/outline';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
import Image from 'next/image'
import useDevice from '@/core/hooks/useDevice'
interface FormProps {
  type: string;
  required: boolean;
  isPKP: boolean;
}

interface industry_id {
  label: string;
  value: string;
  category: string;
}

interface companyType {
  value: string;
  label: string;
}

const form: React.FC<FormProps> = ({ type, required, isPKP }) => {
  const {
    form,
    errors,
    updateForm,
    validate
  } = useRegisterStore()
  const { control, watch, setValue } = useForm();
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [isChekBox, setIsChekBox] = useState<boolean>(false);
  const [isExample, setIsExample] = useState<boolean>(false);
  const { isDesktop, isMobile } = useDevice()
  // Inside your component
  const [formattedNpwp, setFormattedNpwp] = useState<string>(""); // State for formatted NPWP
  const [unformattedNpwp, setUnformattedNpwp] = useState<string>(""); // State for unformatted NPWP


  const [industries, setIndustries] = useState<industry_id[]>([]);
  const [companyTypes, setCompanyTypes] = useState<companyType[]>([]);

  const router = useRouter();
  const toast = useToast();

  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 })));
    };
    loadCompanyTypes();
  }, []);

  useEffect(() => {
    const selectedCompanyType = companyTypes.find(company => company.value === watch('companyType'));
    if (selectedCompanyType) {
      updateForm("company_type_id", `${selectedCompanyType?.value}`);
      validate();
    }
  }, [watch('companyType'), companyTypes]);

  useEffect(() => {
    const selectedIndustryType = industries.find(industry => industry.value === watch('industry_id'));
    if (selectedIndustryType) {
      updateForm("industry_id", `${selectedIndustryType?.value}`);
      setSelectedCategory(selectedIndustryType.category);
      validate();
    }
  }, [watch('industry_id'), industries]);

  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 })));
    };
    loadIndustries();
  }, []);

  const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    updateForm('type_acc',`business`)
    updateForm('is_pkp',`${isPKP}`)
    updateForm(name, value);
    validate();
  };

  const handleInputChangeNpwp = (event: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    updateForm('type_acc',`business`)
    updateForm('is_pkp',`${isPKP}`)
    updateForm('npwp', value);
    validate();
  };

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    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');
      validate();
    } else {
      updateForm("isChekBox", 'false');
      validate();
    }
  }, [isChekBox,]);

  const handleFileChange = async (event: ChangeEvent<HTMLInputElement>) => {

    const toastProps: UseToastOptions = {
      duration: 5000,
      isClosable: true
    };
    let fileBase64 = '';
    const { name} = event.target;
    const file = event.target.files?.[0];
    if (file) {
      if (typeof file !== 'undefined') {
        if (file.size > 5000000) {
          toast({
            ...toastProps,
            title: 'Maksimal ukuran file adalah 5MB',
            status: 'warning'
          });
          return;
        }
        fileBase64 = await getFileBase64(file);
      }
      updateForm(name, fileBase64);
      validate();
    }
  };

  const mutation = useMutation({
    mutationFn: (data: RegisterProps) => registerUser(data)
  });

  const handleSubmit = async (e: ChangeEvent<HTMLFormElement>) => {
    e.preventDefault();

    const response = await mutation.mutateAsync(form);

    if (response?.register === true) {
      const urlParams = new URLSearchParams({
        activation: 'otp',
        email: form.email,
        redirect: (router.query?.next || '/') as string
      });
      router.push(`${router.route}?${urlParams}`);
    }

    const toastProps: UseToastOptions = {
      duration: 5000,
      isClosable: true
    };

    switch (response?.reason) {
      case 'EMAIL_USED':
        toast({
          ...toastProps,
          title: 'Email sudah digunakan',
          status: 'warning'
        });
        break;
      case 'NOT_ACTIVE':
        const activationUrl = `${router.route}?activation=email`;
        toast({
          ...toastProps,
          title: 'Akun belum aktif',
          description: <>Akun sudah terdaftar namun belum aktif. <Link href={activationUrl} className="underline">Klik untuk aktivasi akun</Link></>,
          status: 'warning'
        });
        break;
    }
  };
  return (
    <>
    <BottomPopup
        className=''
        title='Contoh SPPKP'
        active={isExample}
        close={() => setIsExample(false)}
      >
        <div className='flex p-2'>
        <Image
                src='/images/NO-SPPKP-FORMAT-TEMPLATE.jpg'
                alt='Contoh SPPKP'
                className='w-full h-full '
                width={800}
                height={800}
                quality={100}
              />
        </div>
      </BottomPopup>
    <form className="mt-6 grid grid-cols-1 gap-y-4" onSubmit={handleSubmit}>
      <div>
        <label htmlFor='email' className="font-bold">Email Bisnis {!isPKP && !required && <span className='font-normal text-gray_r-11'>(opsional)</span>}</label>

        <input
          type='text'
          id='email_partner'
          name='email_partner'
          placeholder='example@email.com'
          value={!required ? form.email_partner : ''}
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          onChange={handleInputChange}
          autoComplete="username"
          aria-invalid={!required && isPKP && !!errors.email_partner}

        />

        {!required && isPKP && !!errors.email_partner && <span className="form-msg-danger">{errors.email_partner}</span>}
      </div>

      <div className="">
        <label className="font-bold" htmlFor="company">
          Nama Bisnis 
        </label>
        <div className="flex justify-between items-start gap-2 max-h-12 min-h-12 text-sm">
          <div className='w-4/5 pr-1'>
            <Controller
              name='companyType'
              control={control}
              render={(props) => <HookFormSelect {...props} options={companyTypes} disabled={required} placeholder="Badan Usaha"/>}
              />
              {!required &&  !!errors.company_type_id && <span className="form-msg-danger">{errors.company_type_id}</span>}
          </div>
          <div className="w-[120%]">
            <input
              type="text"
              name="business_name"
              id="business_name"
              className="form-input h-12 "
              placeholder="Nama Perusahaan"
              autoCapitalize="true"
              value={form.business_name}
              aria-invalid={!!errors.business_name}
              onChange={handleInputChange}
              />

            { !!errors.business_name && <span className="form-msg-danger">{errors.business_name}</span>}
          </div>
        </div>
      </div>

      <div className="mt-8 sm:mt-8">
        <label className="font-bold" htmlFor="business_name">
          Klasifikasi Jenis Usaha
        </label>
        <Controller
          name='industry_id'
          control={control}
          render={(props) => <HookFormSelect {...props} options={industries} disabled={required} placeholder={'Select industry'}/>}
          />
          {selectedCategory && 
            <span className='text-gray_r-11 text-xs'>Kategori : {selectedCategory}</span>
          }
          {!required && !!errors.industry_id && <span className="form-msg-danger">{errors.industry_id}</span>}
      </div>

      <div>
        <label htmlFor='alamat_bisnis' className="font-bold">Alamat Bisnis</label>

        <input
          type='text'
          id='alamat_bisnis'
          name='alamat_bisnis'
          placeholder='Masukan alamat bisnis anda'
          value={!required? form.alamat_bisnis : ''}
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          onChange={handleInputChange}
          aria-invalid={!required && !!errors.alamat_bisnis}
        />

        {!required && !!errors.alamat_bisnis && <span className="form-msg-danger">{errors.alamat_bisnis}</span>}
      </div>

      <div>
        <label htmlFor='nama_wajib_pajak' className="font-bold">Nama Wajib Pajak {!isPKP && !required && <span className='font-normal text-gray_r-11'>(opsional)</span>}</label>

        <input
          type='text'
          id='nama_wajib_pajak'
          name='nama_wajib_pajak'
          placeholder='Masukan nama lengkap anda'
          value={!required?  form.nama_wajib_pajak : ''}
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          onChange={handleInputChange}
          aria-invalid={isPKP && !required && !!errors.nama_wajib_pajak}
        />

        {isPKP && !required && !!errors.nama_wajib_pajak && <span className="form-msg-danger">{errors.nama_wajib_pajak}</span>}
      </div>

      <div>
        <label htmlFor='alamat_wajib_pajak' className="font-bold flex items-center">
          <p>
          Alamat Wajib Pajak {!isPKP && !required && <span className='font-normal text-gray_r-11'>(opsional)</span>}
          </p>  
          <div className="flex items-center ml-2 mt-1">
          <Checkbox
                borderColor='gray.600'
                colorScheme='red'
                size='md'
                isChecked={isChekBox}
                onChange={handleChange}
              />
              <span className='text-caption-2 ml-2 font-normal italic'>
                sama dengan alamat bisnis? 
              </span>
          </div> 
              </label>

        <input
          type='text'
          id='alamat_wajib_pajak'
          name='alamat_wajib_pajak'
          placeholder='Masukan alamat wajib pajak anda'
          value={!required? (isChekBox?form.alamat_bisnis : form.alamat_wajib_pajak)  : ''}
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={isChekBox || required}
          contentEditable={required}
          readOnly={required}
          onChange={handleInputChange}
          aria-invalid={isPKP && !required && !!errors.alamat_wajib_pajak}
        />

        {isPKP && !required && !!errors.alamat_wajib_pajak && <span className="form-msg-danger">{errors.alamat_wajib_pajak}</span>}
      </div>

      <div>
        <label htmlFor="npwp" className="font-bold">
          Nomor NPWP {!isPKP && !required && <span className="font-normal text-gray_r-11">(opsional)</span>}
        </label>

        <input
          type="tel"
          id="npwp"
          name="npwp"
          className={`form-input mt-3 ${required ? "cursor-no-drop" : ""}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          placeholder="000.000.000.0-000.000"
          value={!required ? formattedNpwp : ""}
          maxLength={21} // Set maximum length to 16 characters
          onChange={(e) => {
            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={!required && !!errors.npwp}
        />

        {!required && !!errors.npwp && <span className="form-msg-danger">{errors.npwp}</span>}
      </div>

      <div>
        <label htmlFor='sppkp' className="font-bold flex flex-row items-center justify-between"> 
          <div className="flex flex-row items-center">
            Nomor SPPKP { !required && <span className='ml-2 font-normal text-gray_r-11'>(opsional) </span>}
          </div>
              {<div onClick={() => setIsExample(!isExample)} className="rounded text-white p-2 flex flex-row bg-red-500 hover:cursor-pointer hover:bg-red-400" >
                <EyeIcon className={`w-4 ${isDesktop && 'mr-2'}`} />
                {isDesktop &&
                <p className="font-light text-xs">Lihat Contoh</p> 
                }
              </div>}
          </label>


        <input
          type='tel'
          id='sppkp'
          name='sppkp'
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          placeholder='X-XXXPKP/WJPXXX/XX.XXXX/XXXX'
          onChange={handleInputChange}
          value={!required ? form.sppkp : ''}
          aria-invalid={!required && !!errors.sppkp}
        />

        {!required && !!errors.sppkp && <span className="form-msg-danger">{errors.sppkp}</span>}
      </div>

      <div>
        <label htmlFor="npwp_document" className="font-bold">Dokumen NPWP {!isPKP && !required && <span className='font-normal text-gray_r-11'>(opsional)</span>}</label>

        <input
          type="file"
          id="npwp_document"
          name="npwp_document"
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          onChange={handleFileChange}
          accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"  // Filter file types
        />

        {isPKP && !required && !!errors.npwp_document && <span className="form-msg-danger">{errors.npwp_document}</span>}
      </div>

      <div>
        <label htmlFor="sppkp_document" className="font-bold">Dokumen SPPKP {!isPKP && !required && <span className='font-normal text-gray_r-11'>(opsional)</span>}</label>

        <input
          type="file"
          id="sppkp_document"
          name="sppkp_document"
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          onChange={handleFileChange}
          accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"  // Filter file types
        />

        {isPKP && !required && !!errors.sppkp_document && <span className="form-msg-danger">{errors.sppkp_document}</span>}
      </div>
    </form>
    </>
  )
}

export default form;