import {useState, useRef} from 'react' import Link from 'next/link' import Router from 'next/router' import styles from './style.module.css' import {Icon} from '@rmwc/icon' import {Input, Button} from '~/components/form' import useUser from '~/hooks/useUser' import axios from 'axios' // TODO: Load previous addresses CheckoutSummary.getInitialProps = async function({ctx: {axios}}){ const {data: order} = await axios.get(`/api/orders/current`) return {order} } export default function CheckoutSummary({order: _order}){ const user = useUser(); const [order, updateOrder] = useState(_order) const currentTransaction = order .transactions.find(transaction => ( transaction.payment_state === 'started' )) const {item_total_price, shipping_price, tax_price, coupon_effective_discount} = currentTransaction const {free_shipping} = currentTransaction.coupon || {} const formatMoney = money => { if (money === undefined || money === null) return null; return '$' + (money / 100).toFixed(2) } const total_price = (item_total_price && shipping_price && tax_price) ? item_total_price + (free_shipping ? 0 : shipping_price) + tax_price - (coupon_effective_discount || 0) : null // For coupon input const couponRef = useRef() const onCouponSubmit = async ev => { if(ev) ev.preventDefault() const code = couponRef.current?.value const {data: updatedOrder} = await axios.post(`/api/orders/current/coupon`, {code}) updateOrder(updatedOrder) } return ( <>

Checkout

Address

{ order.address ? (

{order.address.name}

{order.address.street1}

{order.address.street2}

{order.address.city}, {order.address.state}, {order.address.zip}

(Edit Address)

) : ( user ?(

TODO: Load previous addresses

):( <>

Log in to use your
saved addresses

OR
) ) }

Coupon (optional)

{ currentTransaction.coupon ? ( <>

Using coupon code: {currentTransaction.coupon.code}
( {coupon_effective_discount > 0 && `Discounting by ${formatMoney(coupon_effective_discount)}`} {coupon_effective_discount > 0 && free_shipping && ' & '} {free_shipping && `${coupon_effective_discount > 0 ? 'f' : 'F'}ree shipping`} )

) : (
) }

Total

{currentTransaction.cart.items.map(({uuid, count, item}) => ( ))} {coupon_effective_discount > 0 && ( )} {tax_price && ( )}
{item.name} {count > 1 ? `(${count})` : ''}: {formatMoney(count * item.price_cents)}
Coupon: - {formatMoney(coupon_effective_discount)}
Shipping: {formatMoney(shipping_price) || '-'}
Sales tax: {formatMoney(tax_price)}
Total: {formatMoney(total_price) || '-'}
{ total_price ? ( <> ) : (
) }
) }