summaryrefslogtreecommitdiff
path: root/src/pages/shop/cart.js
blob: fe31e7c9370d6222c17fd92c8f3418b522cd93cc (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
import { useEffect, useState } from "react";
import Header from "../../components/Header";
import Layout from "../../components/Layout";
import Link from "../../components/Link";
import { createOrUpdateItemCart, deleteItemCart, getCart } from "../../helpers/cart";
import ChevronLeftIcon from "../../icons/chevron-left.svg";
import MinusIcon from "../../icons/minus.svg";
import PlusIcon from "../../icons/plus.svg";
import TrashIcon from "../../icons/trash.svg";
import { LazyLoadImage } from "react-lazy-load-image-component";
import apiOdoo from "../../helpers/apiOdoo";
import currencyFormat from "../../helpers/currencyFormat";
import { createSlug } from "../../helpers/slug";
import ConfirmAlert from "../../components/ConfirmAlert";
import { toast } from "react-hot-toast";

import 'react-lazy-load-image-component/src/effects/blur.css';

export default function Cart() {
  const [products, setProducts] = useState([]);
  const [totalPriceBeforeTax, setTotalPriceBeforeTax] = useState(0);
  const [totalTaxAmount, setTotalTaxAmount] = useState(0);
  const [totalDiscountAmount, setTotalDiscountAmount] = useState(0);
  const [deleteConfirmation, setDeleteConfirmation] = useState({
    productId: null,
    show: false
  });

  const getProducts = async () => {
    let cart = getCart();
    let productIds = Object.keys(cart);
    if (productIds.length > 0) {
      productIds = productIds.join(',');
      let dataProducts = await apiOdoo('GET', `/api/v1/product_variant/${productIds}`);
      dataProducts = dataProducts.map((product) => ({
        ...product,
        quantity: cart[product.id].quantity,
        to_process: false
      }));
      setProducts(dataProducts);
    }
  }

  useEffect(() => {
    getProducts();
  }, []);

  useEffect(() => {
    const productsToProcess = products.filter((product) => product.to_process == true);
    let calculateTotalPriceBeforeTax = 0;
    let calculateTotalTaxAmount = 0;
    let calculateTotalDiscountAmount = 0;
    productsToProcess.forEach(product => {
      let priceBeforeTax = product.price.price / 1.11; 
      calculateTotalPriceBeforeTax += priceBeforeTax * product.quantity;
      calculateTotalTaxAmount += (product.price.price - priceBeforeTax) * product.quantity;
      calculateTotalDiscountAmount += (product.price.price - product.price.price_discount) * product.quantity;
    });
    setTotalPriceBeforeTax(calculateTotalPriceBeforeTax);
    setTotalTaxAmount(calculateTotalTaxAmount);
    setTotalDiscountAmount(calculateTotalDiscountAmount);
  }, [products]);

  const getProductsToProcess = () => {
    return products.filter((product) => product.to_process == true);
  }

  const updateCart = (productId, quantity) => {
    let productIndexToUpdate = products.findIndex((product) => product.id == productId);
    if (quantity != '') createOrUpdateItemCart(productId, quantity);
    let productsToUpdate = products;
    productsToUpdate[productIndexToUpdate].quantity = quantity;
    setProducts([...productsToUpdate]);
  };

  const blurQuantity = (productId, quantity) => {
    quantity = quantity == ('' || 0) ? 1 : parseInt(quantity);
    updateCart(productId, quantity);
  };

  const updateQuantity = (productId, quantity) => {
    quantity = quantity == '' ? '' : parseInt(quantity);
    updateCart(productId, quantity);
  };

  const plusQuantity = (productId) => {
    let productIndexToUpdate = products.findIndex((product) => product.id == productId);
    let quantity = products[productIndexToUpdate].quantity + 1;
    updateCart(productId, quantity);
  }

  const minusQuantity = (productId) => {
    let productIndexToUpdate = products.findIndex((product) => product.id == productId);
    let quantity = products[productIndexToUpdate].quantity - 1;
    updateCart(productId, quantity);
  }

  const showDeleteConfirmation = (productId) => {
    setDeleteConfirmation({
      productId: productId,
      show: true
    });
  }

  const hideDeleteConfirmation = () => {
    setDeleteConfirmation({
      productId: null,
      show: false
    });
  }

  const deleteItem = () => {
    const productId = deleteConfirmation.productId;
    let productIndexToUpdate = products.findIndex((product) => product.id == productId);
    let productsToUpdate = products;
    productsToUpdate.splice(productIndexToUpdate, 1);
    setProducts([...productsToUpdate]);
    deleteItemCart(productId);
    hideDeleteConfirmation();
    toast.success('Berhasil menghapus 1 barang dari keranjang', { duration: 1500 });
  }

  const toggleProductToProcess = (productId) => {
    let productIndexToUpdate = products.findIndex((product) => product.id == productId);
    let productsToUpdate = products;
    productsToUpdate[productIndexToUpdate].to_process = !productsToUpdate[productIndexToUpdate].to_process;
    setProducts([...productsToUpdate]);
  }

  return (
    <>
      <ConfirmAlert 
        title="Hapus barang dari keranjang"
        caption="Apakah anda yakin menghapus barang dari keranjang?"
        show={deleteConfirmation.show}
        onClose={hideDeleteConfirmation}
        onSubmit={deleteItem}
      />
      <Header title={`Keranjang Belanja - Indoteknik`}/>
      <Layout>

        {/* jsx-start: Progress Bar */}
        <div className="bg-gray_r-2 flex gap-x-2 p-4 rounded-md">
          <div className="flex gap-x-2 items-center">
            <div className="bg-yellow_r-9 leading-none p-2 rounded-full w-7 text-center text-gray_r-12 text-caption-2">1</div>
            <p className="font-medium text-gray_r-12 text-caption-2">Keranjang</p>
          </div>
          <div className="flex-1 flex items-center">
            <div className="h-0.5 w-full bg-gray_r-7"></div>
          </div>
          <div className="flex gap-x-2 items-center">
            <div className="bg-gray_r-4 leading-none p-2 rounded-full w-7 text-center text-gray_r-11 text-caption-2">2</div>
            <p className="font-medium text-gray_r-11 text-caption-2">Pembayaran</p>
          </div>
          <div className="flex-1 flex items-center">
            <div className="h-0.5 w-full bg-gray_r-7"></div>
          </div>
          <div className="flex gap-x-2 items-center">
            <div className="bg-gray_r-4 leading-none p-2 rounded-full w-7 text-center text-gray_r-11 text-caption-2">3</div>
            <p className="font-medium text-gray_r-11 text-caption-2">Selesai</p>
          </div>
        </div>
        {/* [End] Progress Bar */}
        <div className="p-4">

          {/* [Start] Title */}
          <Link href="/" className="flex gap-x-2 mb-8">
            <ChevronLeftIcon className="w-6 stroke-gray_r-12"/>
            <h1 className="text-gray_r-12">Keranjang Saya</h1> 
          </Link>
          {/* [End] Title */}

          {/* [Start] Product List */}
          <div className="flex flex-col gap-y-6 mb-8">
          {products.map((product, index) => (
            <div className="flex gap-x-3" key={index}>
              <div className="w-4/12 flex items-center gap-x-2">
                <button 
                  className={'p-2 rounded border-2 ' + (product.to_process ? 'border-yellow_r-9 bg-yellow_r-9' : 'border-gray_r-12')} 
                  onClick={() => toggleProductToProcess(product.id)}
                ></button>
                <LazyLoadImage effect="blur" src={product.parent.image ? product.parent.image : '/images/noimage.jpeg'} alt={product.parent.name} className="object-contain object-center border border-gray_r-6 h-32 w-full rounded-md" />
              </div>
              <div className="w-8/12 flex flex-col">
                <Link href={'/shop/product/' + createSlug(product.parent.name, product.parent.id)} className="product-card__title wrap-line-ellipsis-2">
                  {product.parent.name}
                </Link>
                <p className="text-caption-1 text-gray_r-11 mt-1">
                  {product.code || '-'}
                  {product.attributes.length > 0 ? ` | ${product.attributes.join(', ')}` : ''}
                </p>
                <div className="flex flex-wrap gap-x-1 items-center mb-2 mt-auto">
                  <p className="text-caption-1 text-gray_r-12">{currencyFormat(product.price.price_discount)}</p>
                  {product.price.discount_percentage > 0 ? (
                    <>
                      <span className="badge-red">{product.price.discount_percentage}%</span>
                      <p className="text-caption-2 text-gray_r-11 line-through">{currencyFormat(product.price.price)}</p>
                    </>
                  ) : ''}
                  
                </div>
                <div className="flex items-center">
                  <p className="mr-auto text-caption-1 text-gray_r-12 font-bold">{currencyFormat(product.quantity * product.price.price_discount)}</p>
                  <div className="flex gap-x-2 items-center">
                    <button 
                      className="btn-red p-2 rounded"
                      onClick={() => showDeleteConfirmation(product.id)}
                    >
                      <TrashIcon className="stroke-red_r-12 w-3"/>
                    </button>
                    <button 
                      className="btn-light p-2 rounded" 
                      disabled={product.quantity == 1} 
                      onClick={() => minusQuantity(product.id)}
                    >
                      <MinusIcon className={'stroke-gray_r-12 w-3' + (product.quantity == 1 ? ' stroke-gray_r-11' : '')}/>
                    </button>
                    <input 
                      type="number" 
                      className="bg-transparent border-none w-6 text-center outline-none" 
                      onBlur={(e) => blurQuantity(product.id, e.target.value)} 
                      onChange={(e) => updateQuantity(product.id, e.target.value)} 
                      value={product.quantity} 
                    />
                    <button className="btn-light p-2 rounded" onClick={() => plusQuantity(product.id)}>
                      <PlusIcon className="stroke-gray_r-12 w-3"/>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
          </div>
          {/* [End] Product List */}

          {/* [Start] Review Order */}
          {products.length > 0 ? (
            <div className="p-4 border border-gray_r-6 rounded-md mb-4">
              <div className="flex justify-between items-center">
                <h2>Ringkasan Pesanan</h2>
                {getProductsToProcess().length > 0 ? (
                  <p className="text-gray_r-11 text-caption-1">{getProductsToProcess().length} Barang</p>
                ) : ''}
              </div>
              <hr className="my-4 border-gray_r-6"/>
              <div className="flex flex-col gap-y-4">
                <div className="flex gap-x-2 justify-between">
                  <p>Subtotal</p>
                  <p className="font-medium">{currencyFormat(totalPriceBeforeTax)}</p>
                </div>
                <div className="flex gap-x-2 justify-between">
                  <p>PPN 11%</p>
                  <p className="font-medium">{currencyFormat(totalTaxAmount)}</p>
                </div>
                <div className="flex gap-x-2 justify-between">
                  <p>Total Diskon</p>
                  <p className="font-medium text-red_r-11">- {currencyFormat(totalDiscountAmount)}</p>
                </div>
              </div>
              <hr className="my-4 border-gray_r-6"/>
              <div className="flex gap-x-2 justify-between mb-4">
                <p>Grand Total</p>
                <p className="font-medium text-yellow_r-11">{currencyFormat(totalPriceBeforeTax + totalTaxAmount - totalDiscountAmount)}</p>
              </div>
              <p className="text-caption-2 text-gray_r-10 mb-2">*) Belum termasuk biaya pengiriman</p>
              <p className="text-caption-2 text-gray_r-10 leading-5">
                Dengan melakukan pembelian melalui website Indoteknik, saya menyetujui <Link href="/">Syarat & Ketentuan</Link> yang berlaku
              </p>
            </div>
          ) : ''}
          {/* [End] Review Order */}

          {/* [Start] Submit Button */}
          {products.length > 0 ? (
            <div className="flex gap-x-3">
              <button 
                className="flex-1 btn-light"
                disabled={getProductsToProcess().length == 0}
              >
                Quotation {getProductsToProcess().length > 0 ? `(${getProductsToProcess().length})` : ''}
              </button>
              <button 
                className="flex-1 btn-yellow"
                disabled={getProductsToProcess().length == 0}
              >
                Bayar {getProductsToProcess().length > 0 ? `(${getProductsToProcess().length})` : ''}
              </button>
            </div>
          ) : ''}
          {/* [End] Submit Button */}

        </div>
      </Layout>
    </>
  );
}