328 lines
11 KiB
TypeScript
328 lines
11 KiB
TypeScript
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<CheckoutIntent | null>(
|
|
getIntent("checkout") ? checkoutInput.parse(getIntent("checkout")) : null,
|
|
);
|
|
const [busy, setBusy] = useState(false),
|
|
[error, setError] = useState<unknown>(null),
|
|
[addressId, setAddressId] = useState(""),
|
|
[coupon, setCoupon] = useState(""),
|
|
[uncertain, setUncertain] = useState(Boolean(attempt.current)),
|
|
[review, setReview] = useState(false);
|
|
const [reviewedVersion, setReviewedVersion] = useState<number | null>(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 (
|
|
<>
|
|
<Panel title="Cart">
|
|
<ApiNotice error={error} />
|
|
<QueryView query={query}>
|
|
{(data) => (
|
|
<>
|
|
{!data.lines.length ? (
|
|
<Alert severity="info">
|
|
Your cart is empty.{" "}
|
|
<Link href="/products">
|
|
<u>Explore candles</u>
|
|
</Link>
|
|
</Alert>
|
|
) : (
|
|
<>
|
|
<fieldset
|
|
className="cart-lines"
|
|
disabled={busy || uncertain || review}
|
|
>
|
|
{data.lines.map((line) => (
|
|
<div
|
|
className="cart-line"
|
|
key={`${line.variantId}-${data.version}`}
|
|
>
|
|
<div>
|
|
<h3>
|
|
{line.variant.product.name} · {line.variant.name}
|
|
</h3>
|
|
<p>
|
|
{line.variant.currency} {money(line.variant.price)}{" "}
|
|
each
|
|
</p>
|
|
{(!line.variant.active ||
|
|
line.variant.product.status !== "PUBLISHED") && (
|
|
<Alert severity="warning">
|
|
This variant is no longer available.
|
|
</Alert>
|
|
)}
|
|
</div>
|
|
<form
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
const quantity = Number(
|
|
new FormData(e.currentTarget).get("quantity"),
|
|
);
|
|
void edit(line.variantId, quantity, data.version);
|
|
}}
|
|
>
|
|
<TextField
|
|
name="quantity"
|
|
label={`Quantity for ${line.variant.name}`}
|
|
type="number"
|
|
defaultValue={line.quantity}
|
|
inputProps={{ min: 1, max: 100, step: 1 }}
|
|
/>
|
|
<Button type="submit">Update</Button>
|
|
<Button
|
|
onClick={() =>
|
|
edit(line.variantId, 0, data.version)
|
|
}
|
|
>
|
|
Remove
|
|
</Button>
|
|
</form>
|
|
</div>
|
|
))}
|
|
</fieldset>
|
|
<p className="workspace-intro">
|
|
Estimated merchandise: {data.lines[0].variant.currency}{" "}
|
|
{moneyTotal(
|
|
data.lines.map((l) => ({
|
|
price: l.variant.price,
|
|
quantity: l.quantity,
|
|
})),
|
|
)}
|
|
</p>
|
|
<Alert severity="info">
|
|
The cart does not reserve stock. Checkout rechecks current
|
|
prices and creates a 15-minute hold. This estimate excludes
|
|
coupon, tax and shipping.
|
|
</Alert>
|
|
</>
|
|
)}
|
|
</>
|
|
)}
|
|
</QueryView>
|
|
</Panel>
|
|
<Panel title="Create an order">
|
|
<QueryView query={addresses}>
|
|
{(items) => (
|
|
<>
|
|
{!items.length ? (
|
|
<Alert severity="info">
|
|
Save an{" "}
|
|
<Link href="/addresses">
|
|
<u>address</u>
|
|
</Link>{" "}
|
|
before checkout.
|
|
</Alert>
|
|
) : (
|
|
<>
|
|
<TextField
|
|
select
|
|
label="Delivery address"
|
|
fullWidth
|
|
value={addressId}
|
|
onChange={(e) => {
|
|
setAddressId(e.target.value);
|
|
setReview(false);
|
|
}}
|
|
disabled={busy || uncertain || review}
|
|
>
|
|
{items.map((a) => (
|
|
<MenuItem key={a.id} value={a.id}>
|
|
{a.recipient} · {a.line1}, {a.city} {a.postalCode}
|
|
</MenuItem>
|
|
))}
|
|
</TextField>
|
|
<TextField
|
|
label="Coupon code (optional)"
|
|
fullWidth
|
|
value={coupon}
|
|
onChange={(e) => {
|
|
setCoupon(e.target.value);
|
|
setReview(false);
|
|
}}
|
|
inputProps={{ maxLength: 40 }}
|
|
disabled={busy || uncertain || review}
|
|
/>
|
|
</>
|
|
)}
|
|
</>
|
|
)}
|
|
</QueryView>
|
|
<Alert severity="warning">
|
|
Payment collection is unavailable. Creating an order reserves stock;
|
|
it does not charge you or confirm fulfillment.
|
|
</Alert>
|
|
{uncertain ? (
|
|
<>
|
|
<Alert severity="warning">
|
|
The result is unknown. Retry the exact original request to recover
|
|
it. Do not create another order until you have checked your order
|
|
history.
|
|
</Alert>
|
|
<Button
|
|
disabled={busy || (!uncertain && query.isFetching)}
|
|
variant="contained"
|
|
onClick={checkout}
|
|
>
|
|
Retry original checkout
|
|
</Button>
|
|
<Link href="/orders">
|
|
<u>Check orders</u>
|
|
</Link>
|
|
</>
|
|
) : review ? (
|
|
<>
|
|
<p>
|
|
Review the selected address, coupon and cart quantities above.
|
|
Confirm to create a pending order using the current server prices.
|
|
</p>
|
|
<Button disabled={busy} onClick={() => setReview(false)}>
|
|
Back to editing
|
|
</Button>
|
|
<Button
|
|
disabled={busy || (!uncertain && query.isFetching)}
|
|
variant="contained"
|
|
onClick={checkout}
|
|
>
|
|
{busy ? "Creating…" : "Confirm order"}
|
|
</Button>
|
|
</>
|
|
) : (
|
|
<Button
|
|
disabled={
|
|
busy ||
|
|
!addressId ||
|
|
!query.data?.lines.length ||
|
|
query.isFetching ||
|
|
addresses.isFetching ||
|
|
query.isError ||
|
|
addresses.isError ||
|
|
query.data.lines.some(
|
|
(l) =>
|
|
!l.variant.active || l.variant.product.status !== "PUBLISHED",
|
|
)
|
|
}
|
|
variant="contained"
|
|
onClick={() => {
|
|
setReviewedVersion(query.data?.version ?? null);
|
|
setReview(true);
|
|
}}
|
|
>
|
|
Review checkout
|
|
</Button>
|
|
)}
|
|
</Panel>
|
|
</>
|
|
);
|
|
}
|
|
export default function CartPage() {
|
|
return (
|
|
<WorkspaceShell title="My Cart">
|
|
<Cart />
|
|
</WorkspaceShell>
|
|
);
|
|
}
|