You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
3.2 KiB
JavaScript

import React from 'react'
import Router from 'next/router'
5 years ago
import Link from 'next/link'
import axios from 'axios'
import Head from 'next/head'
import useCart from '~/hooks/useCart'
import {FormController, Input, Button} from '~/components/form'
import Table from '~/components/table'
5 years ago
export default function Cart(){
const [cart, setCart] = useCart()
const numItems = (cart?.items) ? cart.items.length : 0
const allInStock = !cart?.items?.some(item => !item.item.number_in_stock || item.item.number_in_stock < 1)
const allHaveEnough = !cart?.items?.some(item => item.count > item.item.number_in_stock)
const handleRemove = id => async ev => {
if(ev) ev.preventDefault()
const {data} = await axios.post(`/api/cart/remove/${id}`)
setCart(data)
}
// We can't let the form controller do this as it shouldn't actually pass a body
const handleCreateTransaction = async () => {
await axios.put(`/api/orders`)
Router.push('/store/checkout')
}
return (
<>
<Head><title>Cart</title></Head>
5 years ago
<h2>Cart</h2>
5 years ago
{
numItems > 0
?<Table
columns={[
5 years ago
{name: 'Item', extractor: row => (
<>
<Link href={`/store/item/${row.item.urlslug}`}><a>{row.item.name}</a></Link>
{(!row.item.number_in_stock || row.item.number_in_stock < 1) && <strong style={{marginLeft: '6px'}}>Out of stock</strong>}
{(row.item.number_in_stock > 0 && row.count > row.item.number_in_stock) && <strong style={{marginLeft: '6px'}}>Not enough in stock</strong>}
5 years ago
</>
)},
5 years ago
{name: 'Quantity in Cart', extractor: row => row.count},
{name: 'Price Each', extractor: row => '$' + (row.item.price_cents / 100).toFixed(2)},
{name: 'Total Price', extractor: row => '$' + (row.count * row.item.price_cents / 100).toFixed(2)},
{name: '', extractor: row =>
<button className="buttonLink" onClick={handleRemove(row.item.uuid)}>Remove</button>
}
]}
rows={cart?.items?.map(row=>({
...row,
id: row.item.uuid
}))}
foot={[
'Total:',
cart?.items.map(r=>r.count).reduce((a,b) => (a+b), 0) || 0,
'',
'$' + ((cart?.items.map(r=>r.count * r.item.price_cents).reduce((a,b) => (a+b), 0) || 0) / 100).toFixed(2),
''
]}
/>
// Empty cart table
:<Table
columns={[
{name: 'No items in cart'}
]}
foot={[
'Total:',
'',
'',
'$0.00'
]}
/>
}
<FormController afterSubmit={handleCreateTransaction}>
{(()=>{
if(!(cart?.items?.length))
return <Button enabled={false} type="submit">No items in cart</Button>
if(!allInStock)
return <Button enabled={false} type="submit">Items out of stock</Button>
if(!allHaveEnough)
return <Button enabled={false} type="submit">Not enough stock</Button>
return <Button type="submit">Proceed to Checkout</Button>
})()}
5 years ago
</FormController>
</>
)
}