import { useEffect, useRef, useState } from "react"; import { Link, useLocation } from "wouter"; import { z } from "zod"; import Button from "@mui/material/Button"; import TextField from "@mui/material/TextField"; import MenuItem from "@mui/material/MenuItem"; import Alert from "@mui/material/Alert"; import { cart, address, checkoutIntent, checkoutInput, order, money, moneyTotal, type CheckoutIntent, } from "@/lib/commerce"; import { usePlatform } from "@/lib/platform"; import { ApiError, isUnknownOutcome } from "@/lib/api"; import { WorkspaceShell } from "@/components/WorkspaceShell"; import { Panel, QueryView, usePrivateQuery } from "@/components/WorkspaceTools"; import { ApiNotice } from "@/components/ApiNotice"; function Cart() { const { request, getIntent, saveIntent, clearIntent } = usePlatform(), query = usePrivateQuery("/cart", cart), addresses = usePrivateQuery("/addresses", z.array(address)); const [, navigate] = useLocation(); const locked = useRef(false), attempt = useRef( getIntent("checkout") ? checkoutInput.parse(getIntent("checkout")) : null, ); const [busy, setBusy] = useState(false), [error, setError] = useState(null), [addressId, setAddressId] = useState(""), [coupon, setCoupon] = useState(""), [uncertain, setUncertain] = useState(Boolean(attempt.current)), [review, setReview] = useState(false); const [reviewedVersion, setReviewedVersion] = useState(null); useEffect(() => { if (review && query.data && query.data.version !== reviewedVersion) { setReview(false); setError( new Error( "The cart changed. Review the updated quantities before checkout.", ), ); } }, [review, query.data, reviewedVersion]); async function edit(id: string, quantity: number, version: number) { if (locked.current) return; locked.current = true; setBusy(true); setError(null); try { z.number().int().min(0).max(100).parse(quantity); await request(`/cart/lines/${id}`, z.object({ version: z.number() }), { method: quantity ? "PUT" : "DELETE", body: quantity ? { quantity, version } : { version }, }); await query.refetch(); } catch (error) { setError(error); if (error instanceof ApiError && error.code === "CART_CHANGED") await query.refetch(); } finally { locked.current = false; setBusy(false); setReview(false); } } async function checkout() { if (locked.current || (!attempt.current && !query.data)) return; locked.current = true; setBusy(true); setError(null); try { if (!attempt.current) { if ( !query.data || query.isFetching || query.data.version !== reviewedVersion ) throw new Error("The cart changed. Review it again before checkout."); attempt.current = checkoutIntent( { cartVersion: reviewedVersion, addressId, couponCode: coupon.trim() ? coupon : undefined, }, crypto.randomUUID(), ); saveIntent("checkout", attempt.current); } const result = await request("/checkout", order, { method: "POST", body: attempt.current, }); clearIntent("checkout", attempt.current.idempotencyKey); attempt.current = null; setUncertain(false); await query.refetch(); navigate(`/orders/${result.id}`); } catch (error) { setError(error); if (isUnknownOutcome(error)) { setUncertain(true); } else { if (attempt.current) clearIntent("checkout", attempt.current.idempotencyKey); attempt.current = null; setReview(false); await query.refetch(); } } finally { locked.current = false; setBusy(false); } } return ( <> {(data) => ( <> {!data.lines.length ? ( Your cart is empty.{" "} Explore candles ) : ( <>
{data.lines.map((line) => (

{line.variant.product.name} · {line.variant.name}

{line.variant.currency} {money(line.variant.price)}{" "} each

{(!line.variant.active || line.variant.product.status !== "PUBLISHED") && ( This variant is no longer available. )}
{ e.preventDefault(); const quantity = Number( new FormData(e.currentTarget).get("quantity"), ); void edit(line.variantId, quantity, data.version); }} >
))}

Estimated merchandise: {data.lines[0].variant.currency}{" "} {moneyTotal( data.lines.map((l) => ({ price: l.variant.price, quantity: l.quantity, })), )}

The cart does not reserve stock. Checkout rechecks current prices and creates a 15-minute hold. This estimate excludes coupon, tax and shipping. )} )}
{(items) => ( <> {!items.length ? ( Save an{" "} address {" "} before checkout. ) : ( <> { setAddressId(e.target.value); setReview(false); }} disabled={busy || uncertain || review} > {items.map((a) => ( {a.recipient} · {a.line1}, {a.city} {a.postalCode} ))} { setCoupon(e.target.value); setReview(false); }} inputProps={{ maxLength: 40 }} disabled={busy || uncertain || review} /> )} )} Payment collection is unavailable. Creating an order reserves stock; it does not charge you or confirm fulfillment. {uncertain ? ( <> The result is unknown. Retry the exact original request to recover it. Do not create another order until you have checked your order history. Check orders ) : review ? ( <>

Review the selected address, coupon and cart quantities above. Confirm to create a pending order using the current server prices.

) : ( )}
); } export default function CartPage() { return ( ); }