summaryrefslogtreecommitdiff
path: root/src-migrate/modules/product-detail/components/AddToCart.tsx
blob: 4accab17e654f1b785c77a36b158050515992139 (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
import React from 'react'
import { Button, useToast } from '@chakra-ui/react'
import { getAuth } from '~/libs/auth'
import { useRouter } from 'next/router'
import Link from 'next/link'
import { upsertUserCart } from '~/services/cart'

type Props = {
  variantId: number | null,
  quantity?: number;
  source?: 'buy' | 'add_to_cart';
}

const AddToCart = ({
  variantId,
  quantity = 1,
  source = 'add_to_cart'
}: Props) => {
  const auth = getAuth()
  const router = useRouter()
  const toast = useToast({
    position: 'top',
    isClosable: true
  })

  const handleClick = async () => {
    if (typeof auth !== 'object') {
      const currentUrl = encodeURIComponent(router.asPath)
      toast({
        title: 'Masuk Akun',
        description: <>
          Masuk akun untuk dapat menambahkan barang ke keranjang belanja. {' '}
          <Link className='underline' href={`/login?next=${currentUrl}`}>Klik disini</Link>
        </>,
        status: 'error',
        duration: 4000,
      })
      return;
    }

    if (
      !variantId ||
      isNaN(quantity) ||
      typeof auth !== 'object'
    ) return;

    toast.promise(
      upsertUserCart(auth.id, 'product', variantId, quantity, true, source),
      {
        loading: { title: 'Menambahkan ke keranjang', description: 'Mohon tunggu...' },
        success: { title: 'Menambahkan ke keranjang', description: 'Berhasil menambahkan ke keranjang belanja' },
        error: { title: 'Menambahkan ke keranjang', description: 'Gagal menambahkan ke keranjang belanja' },
      }
    )

    if (source === 'buy') {
      router.push('/shop/checkout?source=buy')
    }
  }

  const btnConfig = {
    'add_to_cart': {
      colorScheme: 'yellow',
      text: 'Keranjang'
    },
    'buy': {
      colorScheme: 'red',
      text: 'Beli'
    }
  }

  return (
    <Button onClick={handleClick} colorScheme={btnConfig[source].colorScheme} className='w-full'>
      {btnConfig[source].text}
    </Button>
  )
}

export default AddToCart