summaryrefslogtreecommitdiff
path: root/src/lib/product/components/Product/ProductMobileVariant.jsx
blob: de5c3f10556f0bd621e9009ccee080537ad8d1e6 (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
import { Button, Skeleton } from '@chakra-ui/react';
import { HeartIcon } from '@heroicons/react/24/outline';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import { toast } from 'react-hot-toast';
import LazyLoad from 'react-lazy-load';
import ImageNext from 'next/image';
import odooApi from '@/core/api/odooApi';
import Divider from '@/core/components/elements/Divider/Divider';
import Image from '@/core/components/elements/Image/Image';
import Link from '@/core/components/elements/Link/Link';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
import MobileView from '@/core/components/views/MobileView';
import { updateItemCart } from '@/core/utils/cart';
import currencyFormat from '@/core/utils/currencyFormat';
import { gtagAddToCart } from '@/core/utils/googleTag';
import { createSlug } from '@/core/utils/slug';
import whatsappUrl from '@/core/utils/whatsappUrl';
import { getAuth } from '~/libs/auth';
import SimilarBottom from '~/modules/product-detail/components/SimilarBottom';
import ProductSimilar from '../ProductSimilar';

const ProductMobileVariant = ({ product, wishlist, toggleWishlist }) => {
  const router = useRouter();
  const { slug } = router.query;
  const { srsltid } = router.query;
  let auth = getAuth();
  const [quantity, setQuantity] = useState('1');
  const [selectedVariant, setSelectedVariant] = useState(product.id);
  const [informationTab, setInformationTab] = useState(
    informationTabOptions[0].value
  );
  const [addCartAlert, setAddCartAlert] = useState(false);

  const [isLoadingSLA, setIsLoadingSLA] = useState(true);

  const getLowestPrice = () => {
    const lowest = product.lowestPrice;
    return lowest;
  };

  const [activeVariant, setActiveVariant] = useState({
    id: null,
    code: product.code,
    name: product.name,
    price: getLowestPrice(),
    stock: product.stockTotal,
    weight: product.weight,
    isFlashSale: product.isFlashSale,
  });

  useEffect(() => {
    if (selectedVariant) {
      setActiveVariant({
        id: product.id,
        code: product.code,
        name: product.name,
        price: product.price,
        stock: product.stockTotal,
        weight: product.weight,
        isFlashSale: product.isFlashSale,
      });
    }
  }, [selectedVariant, product]);

  const validAction = () => {
    let isValid = true;
    if (!selectedVariant) {
      toast.error('Pilih varian terlebih dahulu');
      isValid = false;
    }
    if (!quantity || quantity < 1 || isNaN(parseInt(quantity))) {
      toast.error('Jumlah barang minimal 1');
      isValid = false;
    }
    return isValid;
  };

  const handleClickCart = async () => {
    if (!auth) {
      router.push(`/login?next=/shop/product/${slug}?srsltid=${srsltid}`);
      return;
    }

    if (!validAction()) return;
    gtagAddToCart(activeVariant, quantity);
    updateItemCart({
      productId: product.id,
      quantity,
      programLineId: null,
      selected: true,
      source: null,
    });
    setAddCartAlert(true);
  };

  const handleClickBuy = async () => {
    let isLoggedIn = typeof auth === 'object';

    if (!isLoggedIn) {
      const currentUrl = encodeURIComponent(router.asPath);
      await router.push(`/login?next=${currentUrl}`);

      // Tunggu login berhasil, misalnya dengan memantau perubahan status auth.
      const authCheckInterval = setInterval(() => {
        const newAuth = getAuth();
        if (typeof newAuth === 'object') {
          isLoggedIn = true;
          auth = newAuth; // Update nilai auth setelah login
          clearInterval(authCheckInterval);
        }
      }, 500); // Periksa status login setiap 500ms

      await new Promise((resolve) => {
        const checkLogin = setInterval(() => {
          if (isLoggedIn) {
            clearInterval(checkLogin);
            resolve(null);
          }
        }, 500);
      });
    }

    if (!validAction()) return;

    updateItemCart({
      productId: product.id,
      quantity,
      programLineId: null,
      selected: true,
      source: 'buy',
    });
    router.push(`/shop/checkout?source=buy`);
  };

  const handleButton = (variant) => {
    const quantity = quantityInput;
    if (!validQuantity(quantity)) return;

    updateItemCart({
      productId: variant,
      quantity,
      programLineId: null,
      selected: true,
      source: 'buy',
    });
    router.push('/shop/quotation?source=buy');
  };

  const productSimilarQuery = [
    product?.name,
    `fq=-product_id_i:${product.id}`,
    `fq=-manufacture_id_i:${product.manufacture?.id || 0}`,
  ].join('&');

  useEffect(() => {
    const fetchData = async () => {
      const dataSLA = await odooApi(
        'GET',
        `/api/v1/product_variant/${product.id}/stock`
      );
      product.sla = dataSLA;

      setIsLoadingSLA(false);
    };
    fetchData();
  }, [product]);

  return (
    <MobileView>
      <div
        className={`px-4 block md:sticky md:top-[150px] md:py-6 fixed  bottom-0 left-0 right-0 bg-white p-2 z-10 pb-6 pt-6  rounded-lg  shadow-[rgba(0,0,4,0.1)_0px_-4px_4px_0px] `}
      >
        {activeVariant.isFlashSale &&
        activeVariant?.price?.discountPercentage > 0 ? (
          <>
            <div className='flex gap-x-1 items-center'>
              <div className='bg-danger-500 px-2 py-1.5 rounded text-white text-caption-2'>
                {activeVariant?.price?.discountPercentage}%
              </div>
              <div className='text-gray_r-11 line-through text-caption-1'>
                {currencyFormat(activeVariant?.price?.price)}
              </div>
              <div className='text-danger-500 font-semibold'>
                {currencyFormat(activeVariant?.price?.priceDiscount)}
              </div>
            </div>
            <div className='text-gray_r-9 text-base font-normal mt-1'>
              Termasuk PPN:{' '}
              {currencyFormat(
                activeVariant?.price.priceDiscount * process.env.NEXT_PUBLIC_PPN
              )}
            </div>
          </>
        ) : (
          <div className='text-danger-500 font-semibold mt-1 text-3xl'>
            {activeVariant?.price?.price > 0 ? (
              <>
                {currencyFormat(activeVariant?.price?.price)}
                <div className='text-gray_r-9 text-base font-normal mt-1'>
                  Termasuk PPN:{' '}
                  {currencyFormat(
                    activeVariant?.price.price * process.env.NEXT_PUBLIC_PPN
                  )}
                </div>
              </>
            ) : (
              <span className='text-gray_r-11 leading-6 font-normal'>
                Hubungi kami untuk dapatkan harga terbaik,&nbsp;
                <a
                  href={whatsappUrl('product', {
                    name: product.name,
                    url: createSlug(
                      '/shop/product/',
                      product.name,
                      product.id,
                      true
                    ),
                  })}
                  className='text-danger-500 underline'
                >
                  klik disini
                </a>
              </span>
            )}
          </div>
        )}
        <div className=''>
          <div className='mt-4 mb-2'>Jumlah</div>
          <div className='flex gap-x-3'>
            <div className='w-2/12'>
              <input
                name='quantity'
                type='number'
                className='form-input'
                value={quantity}
                onChange={(e) => setQuantity(e.target.value)}
              />
            </div>
            <button
              type='button'
              className='btn-yellow flex-1'
              onClick={handleClickCart}
            >
              Keranjang
            </button>
            <button
              type='button'
              className='btn-solid-red flex-1'
              onClick={handleClickBuy}
            >
              Beli
            </button>
          </div>
          <Button
            onClick={() => handleButton(product.id)}
            color={'red'}
            colorScheme='white'
            className='w-full border-2 p-2 gap-1 mt-2 hover:bg-slate-100 flex items-center'
          >
            <ImageNext
              src='/images/writing.png'
              alt='penawaran instan'
              className=''
              width={25}
              height={25}
            />
            Penawaran Harga Instan
          </Button>
        </div>
      </div>
      <Image
        src={product.image + '?variant=True'}
        alt={product.name}
        className='h-72 object-contain object-center w-full border-b border-gray_r-4'
      />

      <div className='p-4'>
        <div className='flex items-end mb-2'>
          {product.manufacture?.name ? (
            <Link
              href={createSlug(
                '/shop/brands/',
                product.manufacture?.name,
                product.manufacture?.id
              )}
            >
              {product.manufacture?.name}
            </Link>
          ) : (
            <div>-</div>
          )}
          <button type='button' className='ml-auto' onClick={toggleWishlist}>
            {wishlist.data?.productTotal > 0 ? (
              <HeartIcon className='w-6 fill-danger-500 text-danger-500' />
            ) : (
              <HeartIcon className='w-6' />
            )}
          </button>
        </div>
        <h1 className='font-medium text-h-lg leading-8 md:text-title-md md:leading-10 mb-3'>
          {activeVariant?.name}
        </h1>
      </div>

      <Divider />

      <div className='p-4'>
        <h2 className='font-semibold'>Informasi Produk</h2>
        <div className='flex gap-x-4 mt-4 mb-3'>
          {informationTabOptions.map((option) => (
            <TabButton
              value={option.value}
              key={option.value}
              active={informationTab == option.value}
              onClick={() => setInformationTab(option.value)}
            >
              {option.label}
            </TabButton>
          ))}
        </div>

        <TabContent
          active={informationTab == 'specification'}
          className='rounded border border-gray_r-6 divide-y divide-gray_r-6'
        >
          <SpecificationContent label='Ketersediaan'>
            <span>
              {isLoadingSLA ? (
                <Skeleton width='100px' height='full' />
              ) : product?.sla?.slaDate != '-' ? (
                <button
                  type='button'
                  title={`Masa Persiapan Barang ${product?.sla?.slaDate}`}
                  className={`flex gap-x-1 items-center p-2 h-8 rounded-lg w-full ${
                    product?.sla?.slaDate === 'indent'
                      ? 'bg-indigo-900'
                      : 'btn-light'
                  }`}
                >
                  <div
                    className={`flex-1 text-sm  ${
                      product?.sla?.slaDate === 'indent' ? 'text-white' : ''
                    }`}
                  >
                    {product?.sla?.slaDate}
                  </div>
                  <div className='flex-end'>
                    <svg
                      aria-hidden='true'
                      fill='none'
                      stroke='currentColor'
                      stroke-width='1.5'
                      className={`w-7 h-7 text-sm ${
                        product?.sla?.slaDate === 'indent' ? 'text-white' : ''
                      }`}
                    >
                      <path
                        d='M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z'
                        stroke-linecap='round'
                        stroke-linejoin='round'
                      ></path>
                    </svg>
                  </div>
                </button>
              ) : (
                '-'
              )}
            </span>
          </SpecificationContent>
          <SpecificationContent label='Nomor SKU'>
            <span>SKU-{product?.id}</span>
          </SpecificationContent>
          <SpecificationContent label='Part Number'>
            <span>{activeVariant?.code || '-'}</span>
          </SpecificationContent>
          <SpecificationContent label='Stok'>
            {activeVariant?.stock > 0 && (
              <span className='flex gap-x-1.5'>
                <div className='badge-solid-red'>Ready Stock</div>
                <div className='badge-gray'>
                  {activeVariant?.stock > 5 ? '> 5' : '< 5'}
                </div>
              </span>
            )}
            {activeVariant?.stock == 0 && (
              <a
                href={whatsappUrl('product', {
                  name: product.name,
                  url: createSlug(
                    '/shop/product/',
                    product.name,
                    product.id,
                    true
                  ),
                })}
                className='text-danger-500 font-medium'
              >
                Tanya Stok
              </a>
            )}
          </SpecificationContent>
          <SpecificationContent label='Berat Barang'>
            {activeVariant?.weight > 0 && (
              <span>{activeVariant?.weight} KG</span>
            )}
            {activeVariant?.weight == 0 && (
              <a
                href={whatsappUrl('productWeight', {
                  name: product.name,
                  url: createSlug(
                    '/shop/product/',
                    product.name,
                    product.id,
                    true
                  ),
                })}
                className='text-danger-500 font-medium'
              >
                Tanya Berat
              </a>
            )}
          </SpecificationContent>
        </TabContent>

        <TabContent
          active={informationTab == 'description'}
          className='leading-6 text-gray_r-11'
          dangerouslySetInnerHTML={{
            __html:
              product.description != ''
                ? product.description
                : 'Belum ada deskripsi produk.',
          }}
        />
      </div>

      <Divider />

      <div className='p-4'>
        <h2 className='font-semibold mb-4'>Kamu Mungkin Juga Suka</h2>
        <LazyLoad>
          <SimilarBottom product={product} />
        </LazyLoad>
        {/* <LazyLoad>
          <ProductSimilar query={productSimilarQuery} />
        </LazyLoad> */}
      </div>

      <BottomPopup
        title='Berhasil Ditambahkan'
        active={addCartAlert}
        close={() => setAddCartAlert(false)}
      >
        <div className='flex mt-4'>
          <div className='w-[15%]'>
            <Image
              src={product.image + '?variant=True'}
              alt={product.name}
              className='h-20 object-contain object-center w-full border border-gray_r-4'
            />
          </div>
          <div className='ml-3 flex flex-1 items-center text-sm font-normal'>
            {product.name}
          </div>
          <div className='ml-3 flex items-center text-sm font-normal'>
            <Link
              href='/shop/cart'
              className='flex-1 py-2 text-gray_r-12 btn-yellow'
            >
              Lihat Keranjang
            </Link>
          </div>
        </div>
        <div className='mt-8 mb-4'>
          <div className='text-h-sm font-semibold mb-6'>
            Kamu Mungkin Juga Suka
          </div>
          <LazyLoad>
            <SimilarBottom product={product} />
          </LazyLoad>
          {/* <LazyLoad>
            <ProductSimilar query={productSimilarQuery} />
          </LazyLoad> */}
        </div>
      </BottomPopup>
    </MobileView>
  );
};

const informationTabOptions = [
  { value: 'specification', label: 'Spesifikasi' },
  // { value: 'description', label: 'Deskripsi' },
  // { value: 'information', label: 'Info Penting' }
];

const TabButton = ({ children, active, ...props }) => {
  const activeClassName = active
    ? 'text-danger-500 underline underline-offset-4'
    : 'text-gray_r-11';
  return (
    <button
      {...props}
      type='button'
      className={`font-medium pb-1 ${activeClassName}`}
    >
      {children}
    </button>
  );
};

const TabContent = ({ children, active, className, ...props }) => (
  <div {...props} className={`${active ? 'block' : 'hidden'} ${className}`}>
    {children}
  </div>
);

const SpecificationContent = ({ children, label }) => (
  <div className='flex justify-between p-3'>
    <span className='text-gray_r-11'>{label}</span>
    {children}
  </div>
);

export default ProductMobileVariant;