# AI in-chat checkout

> In-chat merchant checkout card with quantity stepper, dynamic shipping and tax totals, animated pay progress, and collapsible receipt.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-checkout`
- File: `src/components/haze/blocks/ai-checkout.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-checkout

## Use when
- Completing a fast reorder or one-item purchase directly inside an assistant conversation
- Showing live subtotal, free-shipping threshold, tax calculation, and saved card confirmation before charging
- Folding a finished purchase card into a compact receipt row without leaving the chat thread

## Avoid when
- Collecting full billing addresses, multi-item carts, or new card details; use payment-card-input in a dedicated checkout flow
- Tracking a shipment after checkout has completed; use ai-order-status instead

## Alternatives
- [payment-card-input](https://hazeui.com/ui/payment-card-input.md)
- [ai-order-status](https://hazeui.com/blocks/ai-order-status.md)
- [ai-send](https://hazeui.com/blocks/ai-send.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-checkout" | no | Unique prefix for section heading and aria-labelledby IDs. |
| heading | `string` | "In-chat checkout" | no | Screen-reader section heading for landmark navigation. |
| userPrompt | `string` | "Reorder the coffee beans I got last month" | no | User message bubble requesting the purchase. |
| assistantReply | `string` | "Same as October, two bags of Ethiopia Worka. Want me to place it?" | no | Assistant reply introducing the checkout card. |
| merchant | `string` | "Verve Roasters" | no | Merchant title shown in the checkout header. |
| itemName | `string` | "Ethiopia Worka" | no | Product name inside the order line. |
| itemMeta | `string` | "Whole bean, 250 g" | no | Variant or weight detail shown under the product name. |
| unitPrice | `number` | 19 | no | Price per unit in USD used for live total recalculation. |
| initialQuantity | `number` | 2 | no | Starting item quantity between 1 and 8. |
| freeShippingAt | `number` | 35 | no | Subtotal threshold at which shipping becomes free. |
| shippingFee | `number` | 4.5 | no | Flat shipping charge applied below the free-shipping threshold. |
| taxRate | `number` | 0.08 | no | Decimal tax rate applied to the subtotal. |
| cardSummary | `string` | "Card •••• 4242 · Arrives in 2 days" | no | Saved payment method and delivery estimate line. |
| orderCode | `string` | "VR-8042" | no | Order reference displayed in the collapsed paid receipt. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- Quantity stepper buttons carry explicit Decrease quantity and Increase quantity labels, disable at bounds (1 and 8), and announce recalculated totals through a polite status region.
- Payment progress honors prefers-reduced-motion and shifts focus cleanly to the Start over action once the checkout card folds into the paid receipt.
- Key Tab: Move between the quantity stepper buttons, the Pay button, and Start over after payment
- Key Enter / Space: Adjust item quantity, submit the simulated payment, or reset the checkout card

## Agent prompts

### Install and use

Install the Haze UI block "AI in-chat checkout" with `npx shadcn@latest add @haze/ai-checkout`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiCheckout from "@/components/haze/blocks/ai-checkout.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/blocks/ai-checkout.md

### Customize with real content

Adapt the Haze ai-checkout block for our product. Replace the demo values of these props with our real content: id, heading, userPrompt, assistantReply, merchant, itemName, itemMeta, unitPrice, initialQuantity, freeShippingAt, shippingFee, taxRate, cardSummary, orderCode, class. Keep the layout, the heading level rules and these accessibility details: Quantity stepper buttons carry explicit Decrease quantity and Increase quantity labels, disable at bounds (1 and 8), and announce recalculated totals through a polite status region. Payment progress honors prefers-reduced-motion and shifts focus cleanly to the Start over action once the checkout card folds into the paid receipt. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-checkout, check it fits: use it when completing a fast reorder or one-item purchase directly inside an assistant conversation; showing live subtotal, free-shipping threshold, tax calculation, and saved card confirmation before charging; folding a finished purchase card into a compact receipt row without leaving the chat thread. Avoid it when collecting full billing addresses, multi-item carts, or new card details; use payment-card-input in a dedicated checkout flow; tracking a shipment after checkout has completed; use ai-order-status instead. Alternatives: @haze/payment-card-input, @haze/ai-order-status, @haze/ai-send.

## Example requests that should lead here
- Build an AI in-chat checkout card with a working quantity stepper, free-shipping threshold, pay progress bar, and paid receipt fold
- Add an assistant reorder bubble for coffee beans that recalculates subtotal, shipping, and tax before charging a saved card

## Source

```astro
---
import { Check, CreditCard, Lock, Minus, Plus, RotateCcw } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id?: string;
  heading?: string;
  userPrompt?: string;
  assistantReply?: string;
  merchant?: string;
  itemName?: string;
  itemMeta?: string;
  unitPrice?: number;
  initialQuantity?: number;
  freeShippingAt?: number;
  shippingFee?: number;
  taxRate?: number;
  cardSummary?: string;
  orderCode?: string;
  class?: string;
}

const {
  id = "haze-ai-checkout",
  heading = "In-chat checkout",
  userPrompt = "Reorder the coffee beans I got last month",
  assistantReply = "Same as October, two bags of Ethiopia Worka. Want me to place it?",
  merchant = "Verve Roasters",
  itemName = "Ethiopia Worka",
  itemMeta = "Whole bean, 250 g",
  unitPrice = 19,
  initialQuantity = 2,
  freeShippingAt = 35,
  shippingFee = 4.5,
  taxRate = 0.08,
  cardSummary = "Card •••• 4242 · Arrives in 2 days",
  orderCode = "VR-8042",
  class: className,
} = Astro.props;

const qty = Math.min(8, Math.max(1, Math.round(initialQuantity)));
const subtotal = unitPrice * qty;
const shipping = subtotal >= freeShippingAt ? 0 : shippingFee;
const tax = Math.round(subtotal * taxRate * 100) / 100;
const total = subtotal + shipping + tax;
const fmt = (n: number) => `$${n.toFixed(2)}`;
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-checkout
  data-unit-price={String(unitPrice)}
  data-free-shipping-at={String(freeShippingAt)}
  data-shipping-fee={String(shippingFee)}
  data-tax-rate={String(taxRate)}
  data-initial-qty={String(qty)}
  data-order-code={orderCode}
  class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
  <h2 id={`${id}-title`} class="sr-only">{heading}</h2>

  <div class="mx-auto max-w-md space-y-3.5">
    <div class="flex justify-end">
      <p class="max-w-[85%] rounded-2xl bg-muted px-4 py-2.5 text-sm/5 text-foreground">
        {userPrompt}
      </p>
    </div>

    <p class="text-[0.9375rem]/6 text-pretty text-foreground">
      {assistantReply}
    </p>

    <div data-chk-card class="overflow-hidden rounded-2xl border border-border bg-muted/40 p-1.5">
      <div class="flex items-center justify-between gap-2 px-3 py-2 text-xs/5">
        <h3 class="truncate font-medium text-foreground">{merchant}</h3>
        <span class="inline-flex shrink-0 items-center gap-1.5 text-muted-foreground">
          <Lock class="size-3.5" aria-hidden="true" />
          Secure checkout
        </span>
      </div>

      <div class="rounded-xl border border-border bg-card">
        <div class="flex flex-wrap items-center justify-between gap-3 p-4">
          <div class="flex min-w-0 flex-1 items-center gap-3">
            <span
              class="inline-flex size-12 shrink-0 items-center justify-center rounded-xl border border-frame bg-muted/50"
              aria-hidden="true"
            >
              <svg viewBox="0 0 36 36" class="size-8" fill="none">
                <rect x="8" y="8" width="20" height="22" rx="3" class="fill-muted-foreground/20 stroke-muted-foreground" stroke-width="1.5" />
                <path d="M10 8V6.5C10 5.7 10.7 5 11.5 5H24.5C25.3 5 26 5.7 26 6.5V8" class="stroke-muted-foreground" stroke-width="1.5" />
                <rect x="12" y="14" width="12" height="10" rx="1.5" class="fill-card stroke-border-strong" stroke-width="1" />
                <circle cx="18" cy="19" r="2.25" class="fill-muted-foreground" />
              </svg>
            </span>

            <div class="min-w-0">
              <p class="truncate text-sm/5 font-semibold text-foreground">{itemName}</p>
              <p class="mt-0.5 text-xs/5 text-muted-foreground tabular-nums">
                {fmt(unitPrice)} · {itemMeta}
              </p>
            </div>
          </div>

          <div
            class="inline-flex h-9 shrink-0 items-center gap-1 rounded-full border border-frame bg-muted/30 px-1"
            role="group"
            aria-label={`Quantity for ${itemName}`}
          >
            <button
              type="button"
              data-chk-dec
              aria-label="Decrease quantity"
              disabled={qty <= 1}
              class="inline-flex size-7 cursor-pointer items-center justify-center rounded-full text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.95] disabled:cursor-not-allowed disabled:opacity-40"
            >
              <Minus class="size-3.5" aria-hidden="true" />
            </button>
            <span data-chk-qty class="min-w-5 text-center text-sm/5 font-semibold text-foreground tabular-nums" aria-live="polite">
              {qty}
            </span>
            <button
              type="button"
              data-chk-inc
              aria-label="Increase quantity"
              disabled={qty >= 8}
              class="inline-flex size-7 cursor-pointer items-center justify-center rounded-full text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.95] disabled:cursor-not-allowed disabled:opacity-40"
            >
              <Plus class="size-3.5" aria-hidden="true" />
            </button>
          </div>
        </div>

        <dl class="mx-4 space-y-2 border-t border-dashed border-border py-3.5 text-sm/5">
          <div class="flex items-center justify-between gap-2">
            <dt class="text-muted-foreground">Subtotal</dt>
            <dd data-chk-subtotal class="text-foreground tabular-nums">{fmt(subtotal)}</dd>
          </div>
          <div class="flex items-center justify-between gap-2">
            <dt class="text-muted-foreground">Shipping</dt>
            <dd data-chk-shipping class={cn("tabular-nums", shipping === 0 ? "text-success" : "text-foreground")}>
              {shipping === 0 ? "Free" : fmt(shipping)}
            </dd>
          </div>
          <div class="flex items-center justify-between gap-2">
            <dt class="text-muted-foreground">Tax</dt>
            <dd data-chk-tax class="text-foreground tabular-nums">{fmt(tax)}</dd>
          </div>
        </dl>

        <div class="flex items-center justify-between gap-2 border-t border-border px-4 py-3.5">
          <span class="text-sm/5 font-semibold text-foreground">Total</span>
          <span data-chk-total class="text-lg/6 font-semibold text-foreground tabular-nums">{fmt(total)}</span>
        </div>
      </div>

      <div class="flex flex-wrap items-center justify-between gap-3 px-3 pt-2.5 pb-1.5">
        <div class="flex min-w-0 items-center gap-2 text-xs/5 text-muted-foreground">
          <span class="inline-flex size-6 shrink-0 items-center justify-center rounded-md border border-frame bg-field text-foreground" aria-hidden="true">
            <CreditCard class="size-3.5" />
          </span>
          <span class="min-w-0 truncate">{cardSummary}</span>
        </div>

        <button
          type="button"
          data-chk-pay
          class="relative inline-flex h-10 shrink-0 cursor-pointer items-center justify-center overflow-hidden rounded-full bg-primary px-5 text-sm/5 font-semibold text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-92 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.98] disabled:cursor-wait"
        >
          <span
            data-chk-progress
            aria-hidden="true"
            class="pointer-events-none absolute inset-y-0 left-0 w-0 bg-foreground/15 transition-[width] duration-150 ease-snappy"
          ></span>
          <span data-chk-pay-label class="relative z-10 tabular-nums">Pay {fmt(total)}</span>
        </button>
      </div>
    </div>

    <div
      data-chk-receipt
      hidden
      class="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-frame-success bg-success/8 px-4 py-3 animate-rise"
    >
      <div class="flex min-w-0 items-center gap-2.5">
        <span class="inline-flex size-6 shrink-0 items-center justify-center rounded-full bg-success/14 text-success" aria-hidden="true">
          <Check class="size-3.5" />
        </span>
        <p data-chk-receipt-text class="min-w-0 text-sm/5 font-medium text-foreground tabular-nums">
          Paid {fmt(total)} · Order {orderCode}
        </p>
      </div>
      <button
        type="button"
        data-chk-reset
        class="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-full border border-frame bg-field px-3 text-xs/5 font-medium text-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.97]"
      >
        <RotateCcw class="size-3" aria-hidden="true" />
        Start over
      </button>
    </div>

    <p data-chk-status role="status" class="sr-only"></p>
  </div>
</section>

<script>
  function initAiCheckouts() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-checkout]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const unitPrice = Number(root.dataset.unitPrice ?? 19);
      const freeShippingAt = Number(root.dataset.freeShippingAt ?? 35);
      const shippingFee = Number(root.dataset.shippingFee ?? 4.5);
      const taxRate = Number(root.dataset.taxRate ?? 0.08);
      const initialQty = Math.min(8, Math.max(1, Number(root.dataset.initialQty ?? 2)));
      const orderCode = root.dataset.orderCode ?? "VR-8042";

      const card = root.querySelector<HTMLElement>("[data-chk-card]");
      const receipt = root.querySelector<HTMLElement>("[data-chk-receipt]");
      const receiptText = root.querySelector<HTMLElement>("[data-chk-receipt-text]");
      const qtyEl = root.querySelector<HTMLElement>("[data-chk-qty]");
      const decBtn = root.querySelector<HTMLButtonElement>("[data-chk-dec]");
      const incBtn = root.querySelector<HTMLButtonElement>("[data-chk-inc]");
      const subtotalEl = root.querySelector<HTMLElement>("[data-chk-subtotal]");
      const shippingEl = root.querySelector<HTMLElement>("[data-chk-shipping]");
      const taxEl = root.querySelector<HTMLElement>("[data-chk-tax]");
      const totalEl = root.querySelector<HTMLElement>("[data-chk-total]");
      const payBtn = root.querySelector<HTMLButtonElement>("[data-chk-pay]");
      const payLabel = root.querySelector<HTMLElement>("[data-chk-pay-label]");
      const progressBar = root.querySelector<HTMLElement>("[data-chk-progress]");
      const resetBtn = root.querySelector<HTMLButtonElement>("[data-chk-reset]");
      const status = root.querySelector<HTMLElement>("[data-chk-status]");

      let qty = initialQty;
      let charging = false;
      let chargeTimer: number | undefined;
      let rafId: number | undefined;

      const fmt = (n: number) => `$${n.toFixed(2)}`;

      const calc = () => {
        const subtotal = unitPrice * qty;
        const shipping = subtotal >= freeShippingAt ? 0 : shippingFee;
        const tax = Math.round(subtotal * taxRate * 100) / 100;
        const total = subtotal + shipping + tax;
        return { subtotal, shipping, tax, total };
      };

      const render = (announce = false) => {
        const { subtotal, shipping, tax, total } = calc();
        if (qtyEl) qtyEl.textContent = String(qty);
        if (decBtn) decBtn.disabled = charging || qty <= 1;
        if (incBtn) incBtn.disabled = charging || qty >= 8;
        if (subtotalEl) subtotalEl.textContent = fmt(subtotal);
        if (shippingEl) {
          shippingEl.textContent = shipping === 0 ? "Free" : fmt(shipping);
          shippingEl.classList.toggle("text-success", shipping === 0);
          shippingEl.classList.toggle("text-foreground", shipping !== 0);
        }
        if (taxEl) taxEl.textContent = fmt(tax);
        if (totalEl) totalEl.textContent = fmt(total);
        if (payLabel && !charging) payLabel.textContent = `Pay ${fmt(total)}`;
        if (announce && status) {
          status.textContent = `Updated quantity to ${qty}. Total ${fmt(total)}${shipping === 0 ? " with free shipping" : ""}.`;
        }
      };

      const clearTimers = () => {
        if (chargeTimer !== undefined) {
          window.clearTimeout(chargeTimer);
          chargeTimer = undefined;
        }
        if (rafId !== undefined) {
          window.cancelAnimationFrame(rafId);
          rafId = undefined;
        }
      };

      decBtn?.addEventListener("click", () => {
        if (charging || qty <= 1) return;
        qty -= 1;
        render(true);
      });

      incBtn?.addEventListener("click", () => {
        if (charging || qty >= 8) return;
        qty += 1;
        render(true);
      });

      payBtn?.addEventListener("click", () => {
        if (charging) return;
        const { total } = calc();
        charging = true;
        if (payBtn) payBtn.disabled = true;
        if (decBtn) decBtn.disabled = true;
        if (incBtn) incBtn.disabled = true;
        if (payLabel) payLabel.textContent = `Charging ${fmt(total)}…`;
        if (status) status.textContent = `Processing payment of ${fmt(total)}.`;

        const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
        const duration = reduced ? 160 : 950;
        const start = performance.now();

        const complete = () => {
          clearTimers();
          charging = false;
          if (progressBar) progressBar.style.width = "0%";
          if (payBtn) payBtn.disabled = false;
          if (card) card.hidden = true;
          if (receiptText) receiptText.textContent = `Paid ${fmt(total)} · Order ${orderCode}`;
          if (receipt) receipt.hidden = false;
          if (status) status.textContent = `Payment complete. Paid ${fmt(total)} for order ${orderCode}.`;
          resetBtn?.focus();
        };

        if (reduced) {
          if (progressBar) progressBar.style.width = "100%";
          chargeTimer = window.setTimeout(complete, duration);
          return;
        }

        const step = (now: number) => {
          const pct = Math.min(100, ((now - start) / duration) * 100);
          if (progressBar) progressBar.style.width = `${pct.toFixed(1)}%`;
          if (pct < 100) {
            rafId = window.requestAnimationFrame(step);
          } else {
            chargeTimer = window.setTimeout(complete, 140);
          }
        };
        rafId = window.requestAnimationFrame(step);
      });

      resetBtn?.addEventListener("click", () => {
        clearTimers();
        charging = false;
        qty = initialQty;
        if (progressBar) progressBar.style.width = "0%";
        if (payBtn) payBtn.disabled = false;
        if (receipt) receipt.hidden = true;
        if (card) card.hidden = false;
        render(false);
        if (status) status.textContent = "Checkout reset. Adjust quantity or pay again.";
        payBtn?.focus();
      });

      render(false);
    });
  }

  initAiCheckouts();
  document.addEventListener("astro:page-load", initAiCheckouts);
</script>
```
