import {useState, useRef} from 'react' import Link from 'next/link' import Head from 'next/head' import Router from 'next/router' import getConfig from 'next/config' import styles from './style.module.css' import {Input, Button} from '~/components/form' import useUser from '~/hooks/useUser' import axios from 'axios' import { loadStripe } from '@stripe/stripe-js'; import {DateTime} from 'luxon' const { publicRuntimeConfig: {STRIPE_PUBLIC_KEY} } = getConfig() const stripePromise = loadStripe(STRIPE_PUBLIC_KEY); import PaypalIcon from '../../../images/icons/paypal.svg' CheckoutSummary.getInitialProps = async function({ctx: {axios}}){ const {data: addresses} = await axios.get(`/api/orders/addresses`) const {data: order} = await axios.get(`/api/orders/current`) return {order, addresses} } export default function CheckoutSummary({order: _order, addresses}){ const user = useUser(); const [order, updateOrder] = useState(_order) const [couponError, setCouponError] = useState(null) 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 total_price = (item_total_price && shipping_price) ? item_total_price + (free_shipping ? 0 : shipping_price) + tax_price - (coupon_effective_discount || 0) : null const preorderItems = currentTransaction.cart.items.filter(({item, count}) => count > item.number_in_stock && item.preorder_availability_date).map(({item}) => DateTime.fromISO(item.preorder_availability_date)) || [] preorderItems.sort((b, a) => a < b ? -1 : a > b ? 1 : 0) const latestPreorder = preorderItems[0]?.toLocaleString(DateTime.DATE_FULL) const formatMoney = money => { if (money === undefined || money === null) return null; return '$' + (money / 100).toFixed(2) } // For coupon input const couponRef = useRef() const onCouponSubmit = async ev => { if(ev) ev.preventDefault() setCouponError(null) const code = couponRef.current?.value try { const {data: updatedOrder} = await axios.post(`/api/orders/current/coupon`, {code}) updateOrder(updatedOrder) } catch (err) { console.log(err.response.data.errors) const message = err?.response?.data?.error?.message || err.response?.data?.errors?.find(e => e.param === 'code')?.msg || 'Unknown error applying coupon' setCouponError(message) } } // For address selection const onAddressSelect = uuid => async ev => { if(ev) ev.preventDefault() const {data: updatedOrder} = await axios.post(`/api/orders/current/address/${uuid}`) updateOrder(updatedOrder) } // For Stripe checkout const handleStripeButton = async ev => { if(ev) ev.preventDefault() // Create a stripe session on server const {data: sessionId} = await axios.post('/api/orders/current/checkout/stripe') // Allow Stripe to finish initializing const stripe = await stripePromise; const {error} = await stripe.redirectToCheckout({sessionId}) if(error) alert(error.message) } return ( <> Checkout | Society of Socks

Checkout

Address

{ order.address ? ( <>

Shipping To:

{order.address.name}

{order.address.street1}

{order.address.street2}

{order.address.city}, {order.address.state}, {order.address.zip} {order.address.country !== 'US' && `, ${order.address.country}`}

(Edit Address)

{!order.address.verified && (

Your address could not be automatically verified. Please double check it for accuracy before continuing checkout.

)} ) : ( <> {!user && ( <>

Log in to use your
saved addresses

OR )} {user && addresses && !!addresses.length && ( <>
Select a previous address: {addresses.map(address => (
{address.name || address.company} / {address.street1}
{address.street2 && <> {address.street2}
} {address.city} / {address.state} / {address.zip}
))}
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`} )

) : (
setCouponError(null)} error={couponError} />
) }

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 ? (
{/* */}
) : (
{/* Hit API endpoint to get Stripe session, and then redirect */} {/* */}
) }
{latestPreorder && (

Note: Your cart contains one or more pre-order items. If you complete this order, it will not ship until at least {latestPreorder}

)} ) }