summaryrefslogtreecommitdiff
path: root/src/lib/address/components/EditAddress.jsx
blob: d990872606ffa9ba1654da263bd80c08b09f6790 (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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
import { yupResolver } from '@hookform/resolvers/yup';
import { useRouter } from 'next/router';
import { useEffect, useState, useMemo } from 'react';
import * as Yup from 'yup';
import cityApi from '../api/cityApi';
import { Controller, useForm } from 'react-hook-form';
import districtApi from '../api/districtApi';
import subDistrictApi from '../api/subDistrictApi';
import addressApi from '@/lib/address/api/addressApi';
import editAddressApi from '../api/editAddressApi';
import editPartnerApi from '../api/editPartnerApi';
import HookFormSelect from '@/core/components/elements/Select/HookFormSelect';
import { toast } from 'react-hot-toast';
import Menu from '@/lib/auth/components/Menu';
import useAuth from '@/core/hooks/useAuth';
import odooApi from '@/core/api/odooApi';
import stateApi from '../api/stateApi';
import { MapPinIcon } from 'lucide-react';
import { Button } from '@chakra-ui/react';
import { useMaps } from '../../maps/stores/useMaps';

import PinPointMap from '../../maps/components/PinPointMap';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
import { data } from 'autoprefixer';

const EditAddress = ({ id, defaultValues }) => {
  const auth = useAuth();
  const router = useRouter();
  const {
    register,
    formState: { errors },
    handleSubmit,
    watch,
    setValue,
    getValues,
    control,
  } = useForm({
    resolver: yupResolver(validationSchema),
    defaultValues,
  });

  const [states, setStates] = useState([]);
  const [cities, setCities] = useState([]);
  const [districts, setDistricts] = useState([]);
  const [subDistricts, setSubDistricts] = useState([]);
  const [tempAddress, setTempAddress] = useState(getValues('addressMap'));
  const resetPin = useMaps((state) => state.resetPin);
  const setSelectedPosition = useMaps((state) => state.setSelectedPosition);
  const setAddressMaps = useMaps((state) => state.setAddressMaps);
  const setDetailAddress = useMaps((state) => state.setDetailAddress);
  const [showValidationPopup, setShowValidationPopup] = useState(false);
  const [popupMessage, setPopupMessage] = useState("");
  const [selectedCityName, setSelectedCityName] = useState("");

  const {
    addressMaps,
    selectedPosition,
    detailAddress,
    pinedMaps,
    setPinedMaps,
    getDefaultCenter, // penting untuk deteksi default center
  } = useMaps();

  // Helper: cek apakah benar2 sudah PIN (bukan default center & ada addressMaps)
  const isPinned = useMemo(() => {
    if (!selectedPosition) return false;

    // pastikan selalu cast ke number
    const lat = Number(selectedPosition.lat);
    const lng = Number(selectedPosition.lng);

    // kalau hasil cast bukan angka valid
    if (isNaN(lat) || isNaN(lng)) return false;

    const dc =
      typeof getDefaultCenter === "function"
        ? getDefaultCenter()
        : { lat: -6.2, lng: 106.816666 };

    const nearDefault =
      Math.abs(lat - dc.lat) < 1e-4 &&
      Math.abs(lng - dc.lng) < 1e-4;

    return Boolean(addressMaps) && !nearDefault;
  }, [selectedPosition, addressMaps, getDefaultCenter]);

  // Hanya isi addressMap & lat/lng di form kalau SUDAH PIN
  useEffect(() => {
    // cek kalau form punya koordinat lama
    const lat = getValues("latitude");
    const lng = getValues("longtitude");
    const oldAddress = getValues("addressMap");

    if (lat && lng) {
      setTempAddress(oldAddress);
      setValue("addressMap", oldAddress);

      // kalau store punya setter untuk koordinat/alamat:
      if (typeof setSelectedPosition === "function") {
        setSelectedPosition({ lat: Number(lat), lng: Number(lng) });
      }
      if (typeof setAddressMaps === "function") {
        setAddressMaps(oldAddress);
      }
    }
  }, [setSelectedPosition, setAddressMaps, getValues, setValue]);

  useEffect(() => {
    const addr = getValues("addressMap");

    if (!addr || addr.trim() === "") {
      resetPin();
    } else {
      setAddressMaps(addr);

      const lat = getValues("latitude");
      const lng = getValues("longtitude");
      if (lat && lng) {
        setSelectedPosition({ lat: Number(lat), lng: Number(lng) });
      }
    }
  }, [getValues, resetPin, setAddressMaps, setSelectedPosition]);



  useEffect(() => {
    const loadProfile = async () => {
      const dataProfile = await addressApi({ id: auth.partnerId });
      setValue('industry', dataProfile.industryId);
      setValue('companyType', dataProfile.companyTypeId);
      setValue('taxName', dataProfile.taxName);
      setValue('npwp', dataProfile.npwp);
      setValue('alamat_wajib_pajak', dataProfile.alamatWajibPajak);
      setValue('alamat_bisnis', dataProfile.alamatBisnis);
      setValue('business_name', dataProfile.name);
    };
    if (auth) loadProfile();
  }, [auth?.parentId, setValue]);

  // Isi ZIP/Prov dari detailAddress (JANGAN isi street)
  useEffect(() => {
    const zip = getValues("zip");
    const province = getValues("state"); 
    if (!zip && defaultValues?.zip) {
      setValue("zip", defaultValues.zip);
    }

    if (!getValues("state") && province) {
      const selectedState = states.find(
        (state) =>
          province.includes(state.label) || state.label.includes(province)
      );
      if (selectedState) {
        setValue("state", selectedState.value);
      }
    }
  }, [states, setValue, getValues, defaultValues]);

  useEffect(() => {
    const loadStates = async () => {
      let dataStates = await stateApi({ tempo: false });
      dataStates = dataStates.map((state) => ({
        value: state.id,
        label: state.name,
      }));
      setStates(dataStates);
    };
    loadStates();
  }, []);

  const watchState = watch('state');
  useEffect(() => {
    setValue('city', '');
    if (watchState) {
      const loadCities = async () => {
        let dataCities = await cityApi({ stateId: watchState });
        dataCities = dataCities.map((city) => ({
          value: city.id,
          label: city.name,
        }));
        setCities(dataCities);
        let oldCity = getValues('oldCity');
        if (oldCity) {
          setValue('city', oldCity);
          setValue('oldCity', '');
        }
      };
      loadCities();
    }
  }, [watchState, setValue, getValues]);

  useEffect(() => {
    if (!isPinned) return;

    if (getValues("city")) return;

    if (Object.keys(detailAddress || {}).length > 0) {
      const selectedCities =
        cities.find(
          (city) =>
            city.label.toLowerCase() === detailAddress?.district?.toLowerCase()
        ) ||
        cities.find(
          (city) =>
            detailAddress?.district
              ?.toLowerCase()
              .includes(city.label.toLowerCase()) ||
            city.label
              .toLowerCase()
              .includes(detailAddress?.district?.toLowerCase())
        );

      if (selectedCities) {
        setValue("city", selectedCities.value);
      }
    }
  }, [cities, detailAddress, isPinned, getValues, setValue]);

  const watchCity = watch('city');
  useEffect(() => {
    if (watchCity) {
      const loadDistricts = async () => {
        let dataDistricts = await districtApi({ cityId: watchCity });
        dataDistricts = dataDistricts.map((district) => ({
          value: district.id,
          label: district.name,
        }));
        setDistricts(dataDistricts);
        let oldDistrict = getValues('oldDistrict');
        if (oldDistrict) {
          setValue('oldDistrict', '');
        }
      };
      loadDistricts();
    }
  }, [watchCity, setValue, getValues]);

  useEffect(() => {
    if (!isPinned) return; // skip kalau belum pin

    // jangan override kalau form sudah punya nilai district
    if (getValues("district")) return;

    if (Object.keys(detailAddress || {}).length > 0) {
      const selectedDistrict = districts.find(
        (district) =>
          detailAddress?.subDistrict
            ?.toLowerCase()
            .includes(district.label.toLowerCase()) ||
          district.label
            .toLowerCase()
            .includes(detailAddress?.subDistrict?.toLowerCase())
      );

      if (selectedDistrict) {
        setValue("district", selectedDistrict.value);
      }
    }
  }, [districts, detailAddress, isPinned, getValues, setValue]);
  

  const watchDistrict = watch('district');
  useEffect(() => {
    if (watchDistrict) {
      const loadSubDistricts = async () => {
        let dataSubDistricts = await subDistrictApi({
          districtId: watchDistrict,
        });
        dataSubDistricts = dataSubDistricts.map((district) => ({
          value: district.id,
          label: district.name,
        }));
        setSubDistricts(dataSubDistricts);
        let oldSubDistrict = getValues('oldSubDistrict');

        if (oldSubDistrict) {
          setValue('subDistrict', oldSubDistrict);
          setValue('oldSubDistrict', '');
        }
      };
      loadSubDistricts();
    }
  }, [watchDistrict, setValue, getValues]);

  useEffect(() => {
    if (!isPinned) return; // skip kalau belum pin

    // jangan override kalau form sudah punya nilai subDistrict
    if (getValues("subDistrict")) return;

    if (Object.keys(detailAddress || {}).length > 0) {
      const selectedSubDistrict = subDistricts.find(
        (district) =>
          detailAddress?.village
            ?.toLowerCase()
            .includes(district.label.toLowerCase()) ||
          district.label
            .toLowerCase()
            .includes(detailAddress?.village?.toLowerCase())
      );

      if (selectedSubDistrict) {
        setValue("subDistrict", selectedSubDistrict.value);
      }
    }
  }, [subDistricts, detailAddress, isPinned, getValues, setValue]);

  useEffect(() => {
    if (id) {
      setValue('id', id);
    }
  }, [id, setValue]);

  useEffect(() => {
    const currentCity = cities.find((c) => c.value === watch("city"))?.label || "";

    let normalized = currentCity.toLowerCase().trim();

    const parts = normalized.split(" ");

    if (parts.length >= 3) {
      // hapus prefix kabupaten/kota kalau ada
      normalized = normalized
        .replace(/^kabupaten\s+/i, "")
        .replace(/^kota\s+/i, "")
        .trim();
    }

    setSelectedCityName(normalized);
  }, [watch("city"), cities]);
  // console.log(defaultValues);
  
  // console.log(selectedCityName, '=', detailAddress?.district);
  const onSubmitHandler = async (values) => {
    if (addressMaps) {
      if (!detailAddress){
        if (defaultValues?.oldCity !== values.city) {
          setPopupMessage("Titik Koordinat tidak sesuai dengan Kota yang dipilih");
          setShowValidationPopup(true);
          console.log(detailAddress)
          return;
        }
      }
      if(detailAddress){
        if (selectedCityName && selectedCityName !== detailAddress?.district?.toLowerCase()) {
          setPopupMessage("Titik Koordinat tidak sesuai dengan Kota yang dipilih");
          setShowValidationPopup(true);
          return;
        }
      }
    }
    // if(!addressMaps && detailAddress){
    //   if (selectedCityName && selectedCityName !== detailAddress?.district?.toLowerCase()) {
    //     setPopupMessage("Titik Koordinat tidak sesuai dengan Kota yang dipilih 3");
    //     setShowValidationPopup(true);
    //     return;
    //   }
    // }

    const data = {
      ...values,
      phone: values.mobile,
      state_id: parseInt(values.state, 10),
      city_id: parseInt(values.city, 10),
      district_id: parseInt(values.district, 10),
      sub_district_id: parseInt(values.subDistrict, 10),
    };

    
    if (isPinned) {
      data.longtitude = selectedPosition?.lng;
      data.latitude = selectedPosition?.lat;
      data.address_map = addressMaps || values.addressMap;
      data.use_pin = true;
    } else {
      data.use_pin = false;
      // pastikan tidak ada nilai default center yang ikut terkirim
      delete data.longtitude;
      delete data.latitude;
      delete data.address_map;
    }

    if (!auth.company) {
      data.alamat_lengkap_text = values.street;
    }

    try {
      const address = await editAddressApi({ id, data });
      console.log('Response address:', address);

      let isUpdated = null;

      const isCompanyEditingSelf = auth.company && auth.partnerId == id;

      if (isCompanyEditingSelf) {
        const dataProfile = await addressApi({ id: auth.partnerId });
        const dataAlamat = {
          id_user: auth.id,
          company_type_id: dataProfile.companyTypeId,
          industry_id: dataProfile.industryId,
          tax_name: values.taxName,
          npwp: values.npwp,
          alamat_lengkap_text: values.alamat_wajib_pajak || values.street,
          street: values.street,
          email: values.email,
          mobile: values.mobile,
        };

        const isUpdatedRes = await editPartnerApi({
          id: auth.partnerId,
          data: dataAlamat,
        });
        console.log('Response isUpdated:', isUpdatedRes);
      }

      const isSuccess = !!address?.id;

      if (isSuccess) {
        toast.success('Berhasil mengubah alamat');
        router.back();
      } else {
        const errorMsg =
          address?.message ||
          isUpdated?.message ||
          'Gagal memperbarui alamat, silakan coba lagi.';
        toast.error(errorMsg);
      }
    } catch (error) {
      console.error('Catch error:', error);
      toast.error(error?.message || 'Terjadi kesalahan tidak terduga.');
    }

    const dataProfile = await addressApi({ id: auth.partnerId });
    console.log('ini adalah', dataProfile);
  };
  // console.log('ini adalah', detailAddress);
  return (
    <>
      <BottomPopup
        className=' !h-[75%]'
        title='Pin Maps Address'
        active={pinedMaps}
        close={() => setPinedMaps(false)}
      >
        <div className='flex mt-4'>
          <PinPointMap
            initialLatitude={getValues('latitude')}
            initialLongitude={getValues('longtitude')}
            initialAddress={getValues('addressMap')}
          />
        </div>
      </BottomPopup>
      <BottomPopup
        active={showValidationPopup}
        close={() => setShowValidationPopup(false)}
      >
        <div className="leading-7 text-gray_r-12/80 text-center">
          {popupMessage}
        </div>

        <div className="flex justify-center mt-6">
          <button
            className="btn-solid-red w-full md:w-auto"
            type="button"
            onClick={() => setShowValidationPopup(false)}
          >
            OK
          </button>
        </div>
      </BottomPopup>
      <div className='max-w-none md:container mx-auto flex p-0 md:py-10'>
        <div className='hidden md:block w-3/12 pr-4'>
          <Menu />
        </div>
        <div className='w-full md:w-9/12 p-4 bg-white border border-gray_r-6 rounded'>
          <div className='flex justify-start items-center mb-6'>
            <h1 className='text-title-sm font-semibold hidden md:block mr-2'>
              Ubah Alamat
            </h1>
            {auth?.partnerId == id && <div className='badge-green'>Utama</div>}
          </div>
          <form onSubmit={handleSubmit(onSubmitHandler)}>
            <div className='mb-4 items-start'>
              <label className='form-label mb-2'>Koordinat Alamat</label>
              {addressMaps ? (
                <div className='flex gap-x-2 items-center'>
                  <button
                    type='button'
                    className='flex items-center justify-center me-3 p-2 badge-solid-red text-white rounded-full hover:bg-red-500 transition'
                  >
                    <MapPinIcon
                      className='h-6 w-6'
                      onClick={() => setPinedMaps(true)}
                    />
                  </button>
                  <span> {addressMaps} </span>
                </div>
              ) : (
                <Button
                  variant='plain'
                  style={{ padding: 0 }}
                  onClick={() => setPinedMaps(true)}
                >
                  <button
                    type='button'
                    className='flex items-center justify-center me-3 p-2 badge-solid-red text-white rounded-full hover:bg-red-500 transition'
                  >
                    <MapPinIcon className='h-6 w-6' />
                  </button>
                  Pin Koordinat Alamat
                </Button>
              )}
            </div>
            <div className='grid grid-cols-1 md:grid-cols-2 gap-4'>
              <div>
                <label className='form-label mb-2'>Label Alamat</label>
                <Controller
                  name='type'
                  control={control}
                  render={(props) => (
                    <HookFormSelect
                      {...props}
                      isSearchable={false}
                      options={types}
                    />
                  )}
                />
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.type?.message}
                </div>
              </div>

              <div>
                <label className='form-label mb-2'>Nama</label>
                <input
                  {...register('name')}
                  placeholder='John Doe'
                  type='text'
                  className='form-input'
                />
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.name?.message}
                </div>
              </div>

              <div>
                <label className='form-label mb-2'>Email</label>
                <input
                  {...register('email')}
                  placeholder='johndoe@example.com'
                  type='email'
                  className='form-input'
                  disabled={auth?.partnerId == id && true}
                />
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.email?.message}
                </div>
              </div>

              <div>
                <label className='form-label mb-2'>Mobile</label>
                <input
                  {...register('mobile')}
                  placeholder='08xxxxxxxx'
                  type='tel'
                  className='form-input'
                />
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.mobile?.message}
                </div>
              </div>

              <div>
                <label className='form-label mb-2'>Alamat</label>
                <input
                  {...register('street')}
                  placeholder='Jl. Bandengan Utara 85A'
                  type='text'
                  className='form-input'
                />
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.street?.message}
                </div>
              </div>

              <div>
                <label className='form-label mb-2'>Kode Pos</label>
                <input
                  {...register('zip')}
                  placeholder='10100'
                  type='number'
                  className='form-input'
                />
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.zip?.message}
                </div>
              </div>

              <div>
                <label className='form-label mb-2'>Provinsi</label>
                <Controller
                  name='state'
                  control={control}
                  render={(props) => (
                    <HookFormSelect {...props} options={states} />
                  )}
                />
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.state?.message}
                </div>
              </div>

              <div>
                <label className='form-label mb-2'>Kota</label>
                <Controller
                  name='city'
                  control={control}
                  render={(props) => (
                    <HookFormSelect
                      {...props}
                      options={cities}
                      disabled={!watchState}
                    />
                  )}
                />
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.city?.message}
                </div>
              </div>

              <div>
                <label className='form-label mb-2'>Kecamatan</label>
                <Controller
                  name='district'
                  control={control}
                  render={(props) => (
                    <HookFormSelect
                      {...props}
                      options={districts}
                      disabled={!watchCity}
                    />
                  )}
                />
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.district?.message}
                </div>
              </div>

              <div>
                <label className='form-label mb-2'>Kelurahan</label>
                <Controller
                  name='subDistrict'
                  control={control}
                  render={(props) => (
                    <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'
            >
              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 johndoe@example.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'),
  state: Yup.string().required('Harus di-pilih'),
  city: Yup.string().required('Harus di-pilih'),
  district: Yup.string().required('Harus di-pilih'),
});

const types = [
  { value: 'contact', label: 'Contact Address' },
  { value: 'invoice', label: 'Invoice Address' },
  { value: 'delivery', label: 'Delivery Address' },
  { value: 'other', label: 'Other Address' },
];

export default EditAddress;