summaryrefslogtreecommitdiff
path: root/src/lib/auth/components/SwitchAccount.jsx
blob: 840758c9f0c55d5983abf864a4782f74719ffc36 (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
import useAuth from '@/core/hooks/useAuth';
import { setAuth } from '@/core/utils/auth';
import addressApi from '@/lib/address/api/addressApi';
import { ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/24/outline';
import { useEffect, useState, useMemo } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'react-hot-toast';
import switchAccountApi from '../api/switchAccountApi';
import FormBisnis from '~/modules/register/components/FormBisnis.tsx';
import RegistrasiBisnis from '~/modules/register/components/RegistrasiBisnis.tsx';
import { Radio, RadioGroup, Stack, Divider, Button } from '@chakra-ui/react';
import { useRegisterStore } from '~/modules/register/stores/useRegisterStore.ts';
import { registerUser } from '~/services/auth';
import { useMutation } from 'react-query';
import { isValid } from 'zod';
import Spinner from "@/core/components/elements/Spinner/LogoSpinner";
import useDevice from '@/core/hooks/useDevice';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
const SwitchAccount = ({ company_type, setIsAprove, setUbahAkun }) => {
  const { isDesktop, isMobile } = useDevice();
  const auth = useAuth();
  const [isOpen, setIsOpen] = useState(true);
  const toggle = () => setIsOpen(!isOpen);
  const [isPKP, setIsPKP] = useState(true);
  const [isTerdaftar, setIsTerdaftar] = useState(false);
  const [isChecked, setIsChecked] = useState(false);
  const [selectedValueBisnis, setSelectedValueBisnis] = useState('false');
  const [selectedValue, setSelectedValue] = useState('PKP');
  const [buttonSubmitClick, setButtonSubmitClick] = useState(false);
  const [changeConfirmation, setChangeConfirmation] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingPopup, setIsLoadingPopup] = useState(false);
  const { register, setValue, handleSubmit } = useForm({
    defaultValues: {
      email: '',
      name: '',
      phone: '',
      password: '',
    },
  });
  const mutation = useMutation({
    mutationFn: (data) => registerUser(data),
  });
  const [notValid, setNotValid] = useState(false);
  const {
    form,
    isCheckedTNC,
    isValidCaptcha,
    errors,
    validate,
    updateForm,
    resetForm,
  } = useRegisterStore();
  const isFormValid = useMemo(() => Object.keys(errors).length === 0, [errors]);
  useEffect(() => {
    const loadProfile = async () => {
      const dataProfile = await addressApi({ id: auth.partnerId });
      setValue('email', dataProfile?.email);
      setValue('name', dataProfile?.name);
      setValue('phone', dataProfile?.phone);
    };
    if (auth) loadProfile();
  }, [auth, setValue]);

  useEffect(() => {
    if (selectedValue === 'PKP') {
      updateForm('is_pkp', 'true');
      validate();
    } else {
      updateForm('is_pkp', 'false');
      validate();
    }
  }, [selectedValue]);

  useEffect(() => {
    if (isTerdaftar) {
      updateForm('is_terdaftar', 'true');
      validate();
    } else {
      updateForm('is_terdaftar', 'false');
      validate();
    }
  }, [isTerdaftar]);
  useEffect(() => {
    const loadProfile = async () => {
      const dataProfile = await addressApi({
        id: auth.parentId ? auth.parentId : auth.parent_id,
      });
      if (dataProfile?.companyType === 'nonpkp') {
        setSelectedValue('PKP');
      }
      if (auth?.company) {
        updateForm('email_partner', dataProfile?.email);
        updateForm('business_name', dataProfile?.name);
        updateForm('industry_id', `${dataProfile?.industryId}`);
        updateForm('company_type_id', `${dataProfile?.companyTypeId}`);
        updateForm('nama_wajib_pajak', dataProfile?.taxName);
        updateForm('npwp', dataProfile?.npwp);
        updateForm('sppkp', dataProfile?.sppkp);
        updateForm('alamat_wajib_pajak', dataProfile?.alamatWajibPajak);
        updateForm('alamat_bisnis', dataProfile?.alamatBisnis);
        validate();
      }
    };
    if (auth) loadProfile();
  }, [auth, setValue]);
  useEffect(() => {
    updateForm('name', '-');
    updateForm('email', 'example@mail.com');
    updateForm('password', 'example@mail.com');
    updateForm('phone', '081234567890');
    validate();
  }, [buttonSubmitClick, changeConfirmation]);

  const handleChangeBisnis = (value) => {
    resetForm();
    setSelectedValueBisnis(value);
    if (value === 'true') {
      validate();
      setIsTerdaftar(true);
    } else {
      validate();
      setIsTerdaftar(false);
    }
  };
  const handleChange = (value) => {
    setSelectedValue(value);
    if (value === 'PKP') {
      validate();
      setIsPKP(true);
    } else {
      validate();
      setIsPKP(false);
      setIsPKP(false);
    }
  };
  const onSubmitHandler = async () => {
    setChangeConfirmation(false); // Tutup popup konfirmasi
    setIsLoadingPopup(true); // Munculkan popup loading

    updateForm('parent_id', `${auth.parentId}`);

    const data = form;
    if (!isFormValid) {
      setNotValid(true);
      setButtonSubmitClick(!buttonSubmitClick);
      toast.error('Form belum valid. Mohon periksa kembali input Anda.');
      setIsLoadingPopup(false);
      return;
    }

    try {
      const isUpdated = await switchAccountApi({ data });

      if (isUpdated?.switch === 'pending') {
        toast.success('Berhasil mengajukan ubah akun', { duration: 1500 });
        if (typeof window !== 'undefined') {
          localStorage.setItem('autoCheckProfile', 'true');
        }
        setTimeout(() => {
          setIsAprove('pending');
          setUbahAkun('pending');
          window.location.reload();
        }, 1500);
      } else {
        toast.error('Gagal mengubah akun. Silakan coba lagi nanti atau hubungi admin jika masalah tetap terjadi.');
        setIsLoadingPopup(false);
      }
    } catch (error) {
      console.error(error);
      toast.error('Terjadi kesalahan saat menghubungi server, silahkan cek internet Anda atau hubungi admin Indoteknik.');
      setIsLoadingPopup(false);
    }
  };


  const onSubmitHandlerCancel = async (values) => {
    window.location.reload();
  };

  return (
    <>
      <BottomPopup
        active={changeConfirmation}
        close={() => setChangeConfirmation(false)}
        title='Ubah profil Bisnis'
      >
        <div className='leading-7 text-gray_r-12/80'>
          Anda yakin akan merubah profil bisnis anda dari INDIVIDU menjadi {selectedValue}?
        </div>
        <div className='flex mt-6 gap-x-4 md:justify-end'>
          <button
            className='btn-solid-red flex-1 md:flex-none flex items-center justify-center'
            type='button'
            onClick={onSubmitHandler}
            disabled={isLoading}
          >
            {isLoading && <Spinner className="w-4 h-4 mr-2 text-white" />}
            {isLoading ? 'Menyimpan...' : 'Ya, Ubah'}
          </button>
          <button
            className='btn-light flex-1 md:flex-none'
            type='button'
            onClick={() => setChangeConfirmation(false)}
            disabled={isLoading}
          >
            Batal
          </button>
        </div>
      </BottomPopup>
      <BottomPopup active={isLoadingPopup} close="">
        <div className="leading-7 text-gray_r-12/80 flex justify-center">
          Mengubah status akun...
        </div>
        <div className="container flex justify-center my-4">
          <Spinner width={48} height={48} />
        </div>
      </BottomPopup>

      {/* <div type='button' className='ml-4 flex items-center text-left w-full'>
        <div
          className={`flex ${
            isDesktop ? 'flex-row' : 'flex-col gap-y-2'
          } items-start justify-start bg-slate-50`}
        >
          <div className='flex font-semibold mr-2'>Informasi Bisnis</div>
          <div className='text-red-500 text-xs'>
            *Perubahan akun tidak dapat diubah kembali
          </div>
        </div>
      </div> */}
      <div className='px-4 '>
        <div
          class='flex items-center p-4 mb-4 text-sm border border-red-500 text-red-800 rounded-lg bg-red-50'
          role='alert'
        >
          <svg
            class='flex-shrink-0 inline w-4 h-4 mr-3'
            aria-hidden='true'
            fill='currentColor'
            viewBox='0 0 20 20'
          >
            <path d='M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z' />
          </svg>
          <span class='sr-only'>Info</span>
          <div className='text-justify'>
            Mohon diperhatikan bahwa perubahan data akun bisnis akan
            mengakibatkan perubahan pada informasi yang tertera di faktur pajak
            dan invoice.
          </div>
        </div>
      </div>

      <div className='px-4 mb-4'>
        {!auth?.company && company_type === 'nonpkp' && (
          <>
            <div className='mb-4'>
              <p className='text-black font-bold mb-2'>
                Bisnis Terdaftar di Indoteknik?
              </p>
              <RadioGroup
                onChange={handleChangeBisnis}
                value={selectedValueBisnis}
              >
                <Stack direction='row'>
                  <Radio colorScheme='red' value='true'>
                    Sudah Terdaftar
                  </Radio>
                  <Radio colorScheme='red' value='false' className='ml-2'>
                    Belum Terdaftar
                  </Radio>
                </Stack>
              </RadioGroup>
            </div>
            {!isTerdaftar && (
              <div className=''>
                <p className='text-black font-bold mb-2'>Tipe Bisnis</p>
                <RadioGroup onChange={handleChange} value={selectedValue}>
                  <Stack direction='row' className='font-bold'>
                    <Radio colorScheme='red' value='PKP'>
                      PKP
                    </Radio>
                    {!auth?.company && company_type === 'nonpkp' && (
                      <Radio colorScheme='red' value='Non-PKP' className='ml-4'>
                        Non-PKP
                      </Radio>
                    )}
                  </Stack>
                </RadioGroup>
              </div>
            )}
          </>
        )}
        <FormBisnis
          type={isDesktop ? 'profil' : 'bisnis'}
          required={isTerdaftar}
          isPKP={isPKP}
          chekValid={notValid}
          buttonSubmitClick={buttonSubmitClick}
        />
        <div className='flex flex-row justify-end mt-4 '>
          <div className='mr-4'>
            <button
              type='submit'
              onClick={() => setChangeConfirmation(true)}
              className='btn-yellow w-full sm:w-fit sm:ml-auto mt-6 mr-8 md:mr-4'
            >
              {mutation.isLoading ? 'Loading...' : 'Simpan Perubahan'}
            </button>
          </div>
          <div>
            <button
              type='submit'
              onClick={onSubmitHandlerCancel}
              className='btn-solid-red w-full sm:w-fit sm:ml-auto mt-6'
            >
              {mutation.isLoading ? 'Loading...' : 'Batal'}
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

export default SwitchAccount;