summaryrefslogtreecommitdiff
path: root/src/lib/auth/components/SwitchAccount.jsx
blob: fa1d39243e5043c4cdbb78f51aa16ed6f7ae9691 (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
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 useDevice from '@/core/hooks/useDevice';
const SwitchAccount = () => {
  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 { 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 } =
    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,
      });
      console.log('dataProfile', dataProfile);
      if (dataProfile?.companyType === 'nonpkp') {
        setSelectedValue('PKP');
      }
      updateForm('email_partner', dataProfile?.email_partner);
      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('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();
  }, []);

  const handleChangeBisnis = (value) => {
    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 (values) => {
    // let data = { ...form, id: `${auth.partnerId}` };
    const data = form;
    if (!isFormValid) {
      setNotValid(true);
      setButtonSubmitClick(!buttonSubmitClick);
      return;
    } else {
      setButtonSubmitClick(!buttonSubmitClick);
      setNotValid(false);
    }
    // if (!values.password) delete data.password;
    const isUpdated = await switchAccountApi({ data });

    if (isUpdated?.switch === 'Pending') {
      // setAuth(isUpdated.user);
      // setValue('password', '');
      toast.success('Berhasil mengubah akun', { duration: 1500 });
      setTimeout(() => {
        window.location.reload();
      }, 1500);
      return;
    }
    toast.error('Terjadi kesalahan internal');
  };

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

  return (
    <>
      <button
        type='button'
        onClick={toggle}
        className='p-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 className='ml-auto p-2 bg-gray_r-3 rounded'>
          {!isOpen && <ChevronDownIcon className='w-6' />}
          {isOpen && <ChevronUpIcon className='w-6' />}
        </div>
      </button>

      {isOpen && (
        <div className='p-4'>
          <div>
            <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>
          <div className='mt-4'>
            <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>
                <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 justify-end mb-4 mr-4'>
            <button
              type='submit'
              onClick={onSubmitHandler}
              className='btn-yellow w-full sm:w-fit sm:ml-auto mt-6'
            >
              {mutation.isLoading ? 'Loading...' : 'Simpan Perubahan'}
            </button>
            <button
              type='submit'
              onClick={onSubmitHandlerCancel}
              className='btn-red w-full sm:w-fit sm:ml-auto mt-6'
            >
              {mutation.isLoading ? 'Loading...' : 'Batal'}
            </button>
          </div>
        </div>
      )}
    </>
  );
};

export default SwitchAccount;