Augur

Checkout

Cart management, checkout flow, and order submission to P21.

Checkout Guide

The checkout flow moves a customer from browsing to a submitted P21 order. The augur packages handle cart state, pricing, shipping, address validation, payment and order submission; your site wires them to its server actions.

Flow Overview

Add to Cart → Cart Page → Checkout → Order Submitted → Confirmation
  1. Cart: lines live in augur-hooks' Zustand cart store, kept in step with the commerce service.
  2. Shipping: the customer enters a shipping address (checked with SmartyStreets) and picks a method from live rates.
  3. Billing and payment: a card through the hosted payment iframe, or invoice for approved accounts.
  4. Order submission: the order (lines, addresses, shipping, payment) goes to P21 through the commerce service.
  5. Confirmation: the customer sees the order on a thank-you page.

Cart Management

Initialization

useCartInitialization (augur-hooks) finds or creates the cart header in the commerce service and loads its lines into the store. Call it once in the root layout:

import { useCartInitialization } from "@simpleapps-com/augur-hooks";
import { useSession } from "next-auth/react";
import { cartHdrLookup, getCartLines } from "@/lib/actions/commerce";

const { data: session, status } = useSession();
useCartInitialization(
  {
    status,
    userId: session?.user?.id,
    cartHdrUid: session?.user?.cartHdrUid,
    customerId: session?.user?.customerId,
  },
  { cartHdrLookup, getCartLines },
);

cartHdrLookup(userId, cartToken) and getCartLines(cartHdrUid) are your server actions (over getSiteActions().commerce). A guest's cart token is a UUID kept in localStorage by default; getCartToken, saveCartToken and generateCartToken replace that.

On a B2B site (mode: "b2b" in the site config given to AugurSiteProvider), a guest looks no cart up, since there are no guest carts. A signed-in user looks theirs up only with a customer, from customerId above or the provider's auth. Pass the site config, or a guest keeps retrying its lookup. Pass the customer, or a B2B user with a customer and no session cart gets no cart. Other modes are unchanged.

Once initialized, the cart is available anywhere:

import { useCartHdrUid, useCartLines } from "@simpleapps-com/augur-hooks";

const cartHdrUid = useCartHdrUid();
const cartLines = useCartLines();

Cart Actions

useCartActions changes the store at once and rolls back if the server action fails. Each server action resolves true on success and false on failure (Recipes):

import { useCartActions } from "@simpleapps-com/augur-hooks";
import { addToCart, deleteItemsFromCart, updateCartLines } from "@/lib/actions/commerce";

const { addToCart: add, updateQuantity, removeFromCart, clearCart } = useCartActions({
  addToCart,
  updateCartLines,
  deleteItemsFromCart,
  toast: { success: toast.success, error: toast.error },
});

A cart line MUST have a quantity and a unit of measure. addToCart refuses an item whose quantity isn't a finite number (positive, negative and zero are all quantities) or whose unitOfMeasure is blank: nothing changes, nothing is sent, the error toast reads "Choose a quantity and a unit of measure." and onError gets the error. updateQuantity refuses a missing quantity (NaN) the same way ("Choose a quantity."): sent on, the commerce service would write it as 0 and delete the line. The commerce service enforces neither: it stores a blank unit as empty, not as the item's default selling unit.

The checkout provider waits for any cart change in flight and refetches the cart before it builds the order, so the order holds what the server's cart holds.

Debounce quantity edits (useDebounce): update the field at once and send the change after a pause, so rapid clicks don't flood the server.

Cart Pricing

useCartPricing prices every line at its cart quantity, so quantity breaks apply. It is the one source of prices for the cart and checkout pages:

const { getLineUnitPrice, getLineTotal, subtotal, isLoading } = useCartPricing();

cartLines.map((line, index) => {
  const unitPrice = getLineUnitPrice(index);
  const total = getLineTotal(index);
  // …
});

Each line is priced in its own unit of measure: the price engine prices a query without a unit in the item's default selling unit, so a CASE/6 line asks for "CASE/6" and gets the case price. A custom queryFn receives the unit as its fourth argument, (itemId, customerId, quantity, unitOfMeasure), and MUST pass it on; augur-server's getItemPrice takes it in the same place.

Read prices by line, not by item: one item can sit on two lines (two units of measure), each priced at its own quantity, and getLineUnitPrice(index) keeps both. getUnitPrice(itemId) and the prices map are per item and hold the item's last line; subtotal adds each line at its own price. For GA4, pass getLineUnitPrice to buildTrackingData.

isSuccess and isLoading count only the prices that are fetched, so a line without an itemId, or a cart without a customer, never leaves the cart waiting.

The Checkout Provider

createCheckoutProvider (from @simpleapps-com/augur-hooks/checkout) holds the checkout's state (steps, addresses, carrier, payment, readiness) and submits the order. Create it once per site:

// lib/checkout.ts
import { createCheckoutProvider } from "@simpleapps-com/augur-hooks/checkout";
import { submitOrder, transactionSetup, cardInfo, validatePayment, accountQuery, billingUpdate } from "@/lib/actions/checkout";

export const { CheckoutProvider, useCheckout } = createCheckoutProvider({
  shipping: { carriers: { "1": "Ground", "2": "Next Day" }, defaultCarrierId: "1" },
  payments: { callbacks: { transactionSetup, cardInfo, validatePayment, accountQuery, billingUpdate } },
  order: { successRedirect: "/checkout/thank-you", submitOrder },
});
  • shipping: the carriers to offer, the default, and optional free-shipping thresholds by customer class.
  • payments (optional; B2B sites without card processing leave it out): the server actions usePaymentFlow calls, invoice availability, allowed iframe origins.
  • order: where to go after success, submitOrder(orderData, cartHdrUid), and optional calculateTax and fetchClientIp.
  • identity, ui.onError, customState and lifecycle hooks (the hooks) cover the rest.

The provider builds the order payload with augur-utils' buildCheckoutPayload (oe_hdr and oe_line) unless hooks.assembleOrder replaces it, and gates the Process Order button with determineOrderReadiness unless hooks.isOrderReady overrides it.

Shipping

Address Validation

const result = await getSiteActions().smartyStreets.validateAddress({ address1, address2, city, state, postalCode });
// result.status: "success" | "not_found" | "error", with the corrected fields

Validation is never cached. Validate on blur or after a short debounce, and offer the correction when augur-utils' isAddressDifferent says the result differs from what was entered.

Shipping Rates

const rates = await getSiteActions().shipping.getShippingRates(toAddress, weight, serviceCodes);

The origin is the site config's shipping.fromAddress, and shipping.defaultServiceCodes filters the services when serviceCodes is left out. Your site decides which carriers to offer and any free-shipping rules.

Billing & Payment

Card payments normally run through the hosted iframe, so card data never touches your server. The exception is Element tokenize, below. usePaymentFlow (inside the checkout provider) runs:

  1. Setup: transactionSetup returns the session and iframe URL; augur-web's PaymentModal shows it.
  2. Capture: the customer enters the card in the iframe.
  3. Card info and validation: cardInfo, then validatePayment confirm the card.
  4. Account: accountQuery returns the payment account for the order, and billingUpdate records the billing address.

Each step is a server action over getSiteActions().payments (transactionSetup, cardInfo, validatePayment, accountQuery, billingUpdate, getSurcharge). For invoice customers, billing is an address and PO number, with no payment processing.

Element tokenize (your own card form)

A site that collects the card in its own form turns it into an Element payment token with augur-hooks' useTokenizeCard (atlas#259). It runs augur-server's tokenizeCard server action, which calls getSiteActions().payments.tokenizeElementCard (payments' POST /element/payment), so the site writes no server action of its own. Unlike the iframe, the card number passes through your server, so it MUST go straight from the form to the hook and MUST NOT be logged or stored. @simpleapps-com/augur-server/hooks MUST be imported somewhere in the app: that import registers the action. Without it, the hook answers { ok: false } saying so.

"use client";
import { elementBodyOf, useTokenizeCard } from "@simpleapps-com/augur-hooks";

const tokenize = useTokenizeCard();
// card: { ccNumber, cvv, expMonth, expYear } as typed; billing and shipping: checkout addresses
const token = await tokenize.mutateAsync(elementBodyOf(card, billingAddress, shippingAddress));
if (token.ok) setPaymentAccountId(token.paymentAccountId);

Server code can still call getSiteActions().payments.tokenizeElementCard(body) directly; both paths run the same checks. The generic queryAction (and createServerQueryProxy) refuses payments.element.payment.create, so a card can never skip them.

  • The number as typed is fine: spaces, dashes and any other character are dropped, and Element gets the digits only (4111 1111-1111 1111 is 4111111111111111).
  • Checked first, on the server, as a sanity check: the card number's digits MUST be 12 to 19 (every brand, American Express's 15 included) and pass the Luhn check (a mistyped digit fails it), and the CVV 3 or 4 digits (Amex's is 4). Element itself refuses a card it can't take. A refused card is never sent, and the message names the value that is wrong, never the value itself.
  • The result (TElementToken from augur-utils): { ok: true, paymentAccountId, lastFour, expirationMonth, expirationYear, brand, avsVerdict } when Element tokenized the card, else { ok: false, message }. That message is Element's own reason, that the card processor did not answer, or the service's error (for example no Element processor configured for the site).
  • Address check: avsVerdict is Element's AVS answer as it came: match, partial, no_match or unavailable (AVS is off per site by default), or "" when Element sent none. It never makes ok false. Treat a non-match as a reason for review, not a decline, and never treat unavailable as no_match.
  • Shipping state and postalCode pick the site's Element processor; billing address1 and postalCode feed AVS.

Tax estimate

useTaxEstimate(lines, shipTo) (augur-hooks, atlas#259) estimates sales tax through augur-server's estimateTax server action. That action calls getSiteActions().avalara.calculateTax, which uses payments' POST /rates, never the Avalara service. As with tokenize, @simpleapps-com/augur-server/hooks registers the action, and the site writes no server action of its own.

"use client";
import { taxLinesOf, useCartLines, useCartPricing, useTaxEstimate } from "@simpleapps-com/augur-hooks";

const cartLines = useCartLines();
const pricing = useCartPricing();
// one tax line per cart line, each priced only once its own price has loaded
const { tax, isLoading, error } = useTaxEstimate(taxLinesOf(cartLines, pricing), shippingAddress);

Build the lines with taxLinesOf, not getLineUnitPrice alone: that answers 0 for a line whose price hasn't loaded, so the line would be taxed at 0.

With the checkout provider: leave order.calculateTax unset and hand the estimate to the provider's taxRate with setTaxRate. The provider's own calculateTax slot is given only the billing postal code, while the estimate needs the whole ship-to address:

"use client";
import { useEffect } from "react";
import { taxLinesOf, useCartPricing, useTaxEstimate } from "@simpleapps-com/augur-hooks";
import { useCheckout } from "@/lib/checkout";

export function CheckoutTax() {
  const { cartLines, shippingAddress, setTaxRate } = useCheckout();
  const pricing = useCartPricing();
  const { tax } = useTaxEstimate(taxLinesOf(cartLines, pricing), shippingAddress);
  useEffect(() => setTaxRate(tax), [tax, setTaxRate]);
  return null;
}

Render <CheckoutTax /> inside the CheckoutProvider. Until an estimate comes back, or when it fails, taxRate is undefined, as with no tax engine.

  • When it asks: only with a ship-to postal code and at least one line, every line priced. It asks again whenever a line or the address changes.
  • The body (ratesBodyOf): the ship-to's address1, address2, city, state and postalCode, its country (US when the address has none), and one item per line, with amount the unit price times the quantity.
  • The tax lines (taxLinesOf): each cart line's itemId, its quantity (none as 0), and its own price once that has loaded, else null.
  • Never throws: a failed call, or an answer that is not a number of 0 or more, is error (a message), and tax stays undefined.
  • Never cached: payments is a no-cache namespace, on the server and in the browser.

Order Submission

submitOrder is your server action:

"use server";
import { getSiteActions, safeAction } from "@simpleapps-com/augur-server";

export async function submitOrder(orderData: Record<string, unknown>, cartHdrUid: number) {
  return safeAction(() => getSiteActions().commerce.checkoutOrder(cartHdrUid, orderData));
}

On success the provider clears the cart state, saves the confirmation in sessionStorage (ORDER_CONFIRMATION_KEY) and redirects to successRedirect. The commerce service creates the order in P21.

Server Actions

All checkout operations go through the site actions from augur-server:

const actions = getSiteActions();

actions.commerce; // cart lookups and lines, order submission
actions.shipping; // rate quotes
actions.payments; // card processing
actions.smartyStreets; // address validation
actions.pricing; // prices and tax estimates

Client Hooks

Hook Purpose
useCartInitialization Find or create the cart and load its lines
useCartActions Add, update, remove and clear, optimistically
useCartHdrUid The cart header UID from the store
useCartLines The cart lines from the store
useCartPricing Prices for the cart with quantity breaks
usePaymentFlow The card payment sequence
useTaxEstimate Sales tax for the lines and ship-to address
useTokenizeCard An Element token for a card from your own form
useOrderReadiness Whether the order can be submitted, debounced
useCheckoutPersistence Keeps checkout fields across reloads

Typical Architecture

Client (React)                    Server (Next.js)                 Augur Services
─────────────────                 ────────────────                 ──────────────
Zustand cart store  ──actions──►  commerce actions  ──SDK calls──► Commerce API
useCartPricing      ──proxy────►  queryAction       ──SDK calls──► Pricing API
Shipping step       ──actions──►  shipping actions  ──SDK calls──► Logistics API
Address form        ──actions──►  smartyStreets     ──SDK calls──► SmartyStreets API
PaymentModal        ──actions──►  payments actions  ──SDK calls──► Payments API
Process Order       ──actions──►  checkoutOrder     ──SDK calls──► Commerce API → P21