# Discount Builder

> A discount builder where the offer is one editable sentence, with a live checkout preview. Handles code checks, drafts and schedules.

Canonical: https://hextaui.com/blocks/discount-builder
Last updated: 2026-10-29

## Overview

Discount Builder is the page a merchant uses to create or edit a discount. A new discount opens with a short type dialog: amount off products, amount off order, buy X get Y or free shipping. After that the offer is a sentence the merchant edits in place: “Customers get [15%] off [Ring Vase and Glass Carafe]”. Each underlined part is a real control with a label, so screen readers hear “Percentage off, 15” rather than a sentence of buttons.

Everything optional sits in a Rules card as collapsed rows: Minimum purchase, Customers, Usage limits, Combines with and Schedule. Each row shows its current value, so a merchant can read the whole setup without opening anything, and each panel explains its setting with an example. Schedules start now by default and offer presets for 7 days, 30 days and the end of the month, in the store’s time zone.

The rail is a preview, not a list of settings. It shows the offer as one sentence and a sample checkout built from your products, with the discount applied and what the customer saves. A Qualifies / Doesn’t toggle swaps to a cart just under the minimum and shows the same message a storefront would, such as “Add $10.00 more to use SUMMER15”. Risky settings, like 100% off with no limit, show up as warnings under it.

Data goes in, async callbacks come out. onSave gets a cleaned Discount and the intent (draft or live); return field errors to show them on the sentence or the rule rows, or throw to show the message in the save bar. Errors appear when a field is left, never while typing. New discounts save from the header (Save draft and Create discount). Existing ones use the shared IslandBar, which appears only when there are unsaved changes.

## Installation

### Step 1: Get HextaUI Pro

One payment unlocks every block, including future ones. [See pricing](https://hextaui.com/pricing).

### Step 2: Add the Pro registry to components.json

```json title="components.json"
{
  "registries": {
    "@hextaui-pro": {
      "url": "https://hextaui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
      }
    }
  }
}
```

### Step 3: Add your token

Create a token on your [account page](https://hextaui.com/account) and put it in `.env.local` as `HEXTAUI_PRO_TOKEN`.

### Step 4: Add the block

```bash
npx shadcn@latest add @hextaui-pro/discount-builder
```

## Usage

### Shopify Admin API

Map the Discount to discountCodeBasicCreate or discountAutomaticBxgyCreate and return Shopify’s userErrors as field errors. Drafts go to your own table, since Shopify has no draft discounts. The type comes from the route, so the type dialog is off.

```tsx
"use client"

import type { Product } from "../variant-picker/product"
import type { Discount, DiscountErrors, DiscountField } from "@/components/blocks/discount-builder/discount"
import { DiscountBuilder } from "@/components/blocks/discount-builder/discount-builder"

const basicCreate = `
  mutation discountCodeBasicCreate($basicCodeDiscount: DiscountCodeBasicInput!) {
    discountCodeBasicCreate(basicCodeDiscount: $basicCodeDiscount) {
      codeDiscountNode { id }
      userErrors { field message }
    }
  }
`

const bxgyCreate = `
  mutation discountAutomaticBxgyCreate($automaticBxgyDiscount: DiscountAutomaticBxgyInput!) {
    discountAutomaticBxgyCreate(automaticBxgyDiscount: $automaticBxgyDiscount) {
      automaticDiscountNode { id }
      userErrors { field message }
    }
  }
`

type UserError = { field: string[] | null; message: string }

function items(type: "products" | "collections", ids: string[]) {
  return type === "products" ? { products: { productsToAdd: ids } } : { collections: { add: ids } }
}

function basicInput(discount: Discount) {
  return {
    title: discount.code,
    code: discount.code,
    startsAt: discount.startsAt,
    endsAt: discount.endsAt,
    usageLimit: discount.usage.limitTotal ? discount.usage.total : null,
    appliesOncePerCustomer: discount.usage.oncePerCustomer,
    context: discount.eligibility.type === "segments" ? { customerSegments: { add: discount.eligibility.ids } } : discount.eligibility.type === "customers" ? { customers: { add: discount.eligibility.ids } } : { all: "ALL" },
    combinesWith: {
      productDiscounts: discount.combinesWith.product,
      orderDiscounts: discount.combinesWith.order,
      shippingDiscounts: discount.combinesWith.shipping,
    },
    minimumRequirement:
      discount.minimum.type === "amount"
        ? { subtotal: { greaterThanOrEqualToSubtotal: discount.minimum.value } }
        : discount.minimum.type === "quantity"
          ? { quantity: { greaterThanOrEqualToQuantity: String(discount.minimum.value) } }
          : null,
    customerGets: {
      value:
        discount.valueType === "percentage"
          ? { percentage: (discount.value ?? 0) / 100 }
          : { discountAmount: { amount: discount.value, appliesOnEachItem: discount.type === "amount_off_products" } },
      items:
        discount.type === "amount_off_order" || discount.appliesTo.type === "all"
          ? { all: true }
          : items(discount.appliesTo.type, discount.appliesTo.ids),
    },
  }
}

function bxgyInput(discount: Discount) {
  return {
    title: discount.title,
    startsAt: discount.startsAt,
    endsAt: discount.endsAt,
    usesPerOrderLimit: discount.gets.limitPerOrder ? String(discount.gets.maxUsesPerOrder) : null,
    customerBuys: {
      value:
        discount.buys.type === "quantity"
          ? { quantity: String(discount.buys.value) }
          : { amount: String(discount.buys.value) },
      items: items(discount.buys.items.type, discount.buys.items.ids),
    },
    customerGets: {
      value: {
        discountOnQuantity: {
          quantity: String(discount.gets.quantity),
          effect: { percentage: discount.gets.effect === "free" ? 1 : (discount.gets.percentage ?? 0) / 100 },
        },
      },
      items: items(discount.gets.items.type, discount.gets.items.ids),
    },
  }
}

const fieldMap: Record<string, DiscountField> = {
  code: "code",
  title: "title",
  endsAt: "endsAt",
  startsAt: "startsAt",
  usageLimit: "usageLimit",
}

async function saveToShopify(discount: Discount): Promise<DiscountErrors | void> {
  const bxgy = discount.type === "buy_x_get_y" && discount.method === "automatic"
  const response = await fetch("/api/shopify/graphql", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(
      bxgy
        ? { query: bxgyCreate, variables: { automaticBxgyDiscount: bxgyInput(discount) } }
        : { query: basicCreate, variables: { basicCodeDiscount: basicInput(discount) } }
    ),
  })
  if (!response.ok) throw new Error("Shopify didn’t respond.")
  const { data } = await response.json()
  const result = bxgy ? data.discountAutomaticBxgyCreate : data.discountCodeBasicCreate
  const errors: DiscountErrors = {}
  for (const error of result.userErrors as UserError[]) {
    const field = fieldMap[error.field?.at(-1) ?? ""]
    if (field) errors[field] = error.message
    else throw new Error(error.message)
  }
  return errors
}

async function saveDraft(discount: Discount): Promise<DiscountErrors | void> {
  const response = await fetch("/api/discount-drafts", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(discount),
  })
  if (!response.ok) throw new Error("The draft wasn’t saved.")
}

export function NewShopifyDiscount({ discount, products }: { discount: Discount; products: Product[] }) {
  return (
    <DiscountBuilder
      discount={discount}
      products={products}
      timeZone="America/New_York"
      showTypePicker={false}
      existingDiscounts={[{ code: "FREESHIP", type: "free_shipping" }]}
      onSave={(next, { intent }) => (intent === "draft" ? saveDraft(next) : saveToShopify(next))}
      onCheckCode={async (code, { signal }) => {
        const response = await fetch(`/api/discounts/check?code=${encodeURIComponent(code)}`, { signal })
        const { available } = await response.json()
        return available
      }}
    />
  )
}
```

### Stripe coupons and promotion codes

A live discount becomes a Stripe coupon plus a promotion code with its redemption limit, first-order rule and expiry. Stripe’s duplicate-code error comes back as a code field error.

```tsx
"use server"

import { toMinorUnits, money } from "../price/money"
import type { Discount, DiscountErrors } from "@/components/blocks/discount-builder/discount"

type StripeError = { code?: string; message: string }

const stripeKey = process.env.STRIPE_SECRET_KEY ?? ""

async function stripe(path: string, body: Record<string, string>) {
  const response = await fetch(`https://api.stripe.com/v1/${path}`, {
    method: "POST",
    headers: { Authorization: `Bearer ${stripeKey}`, "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams(body),
  })
  const json = await response.json()
  if (!response.ok) throw json.error as StripeError
  return json
}

export async function saveDiscount(discount: Discount): Promise<DiscountErrors | void> {
  if (discount.status === "draft") {
    await fetch(`${process.env.APP_URL}/api/discount-drafts`, { method: "POST", body: JSON.stringify(discount) })
    return
  }
  const coupon = await stripe("coupons", {
    name: discount.code,
    duration: "once",
    ...(discount.valueType === "percentage"
      ? { percent_off: String(discount.value) }
      : {
          amount_off: String(toMinorUnits(money(discount.value ?? 0, discount.currencyCode))),
          currency: discount.currencyCode.toLowerCase(),
        }),
    ...(discount.appliesTo.type === "products"
      ? Object.fromEntries(discount.appliesTo.ids.map((id, index) => [`applies_to[products][${index}]`, id]))
      : {}),
  })

  try {
    await stripe("promotion_codes", {
      coupon: coupon.id,
      code: discount.code,
      ...(discount.usage.limitTotal && discount.usage.total ? { max_redemptions: String(discount.usage.total) } : {}),
      ...(discount.endsAt ? { expires_at: String(Math.floor(Date.parse(discount.endsAt) / 1000)) } : {}),
      ...(discount.eligibility.type === "segments" && discount.eligibility.ids.includes("first-time")
        ? { "restrictions[first_time_transaction]": "true" }
        : {}),
      ...(discount.minimum.type === "amount" && discount.minimum.value
        ? {
            "restrictions[minimum_amount]": String(toMinorUnits(money(discount.minimum.value, discount.currencyCode))),
            "restrictions[minimum_amount_currency]": discount.currencyCode.toLowerCase(),
          }
        : {}),
    })
  } catch (error) {
    const { message } = error as StripeError
    if (/already exists/i.test(message)) return { code: `${discount.code} is already a promotion code in Stripe` }
    throw new Error(message)
  }
}
```

### Medusa promotions

Medusa v2 promotions take the same shape and support draft status directly. onCheckCode lists promotions by code to check that a new one is free.

```tsx
"use client"

import type { Product } from "../variant-picker/product"
import type { Discount } from "@/components/blocks/discount-builder/discount"
import { DiscountBuilder } from "@/components/blocks/discount-builder/discount-builder"

const admin = "/admin/promotions"

function toPromotion(discount: Discount) {
  const target =
    discount.type === "amount_off_order" ? "order" : discount.type === "free_shipping" ? "shipping_methods" : "items"
  return {
    code: discount.code,
    type: discount.type === "buy_x_get_y" ? "buyget" : "standard",
    is_automatic: discount.method === "automatic",
    status: discount.status === "draft" ? "draft" : "active",
    application_method: {
      type: discount.type === "free_shipping" ? "percentage" : discount.valueType === "percentage" ? "percentage" : "fixed",
      value: discount.type === "free_shipping" ? 100 : discount.value,
      currency_code: discount.currencyCode.toLowerCase(),
      target_type: target,
      allocation: discount.type === "amount_off_products" ? "each" : "across",
      target_rules:
        discount.appliesTo.type === "products"
          ? [{ attribute: "items.product.id", operator: "in", values: discount.appliesTo.ids }]
          : [],
    },
    campaign: {
      name: discount.code || discount.title,
      campaign_identifier: discount.code || discount.title,
      starts_at: discount.startsAt,
      ends_at: discount.endsAt,
      budget: discount.usage.limitTotal ? { type: "usage", limit: discount.usage.total } : undefined,
    },
  }
}

export function MedusaDiscount({ discount, products }: { discount: Discount; products: Product[] }) {
  return (
    <DiscountBuilder
      discount={discount}
      products={products}
      onCheckCode={async (code, { signal }) => {
        const response = await fetch(`${admin}?code=${encodeURIComponent(code)}&limit=1`, { signal, credentials: "include" })
        const { count } = await response.json()
        return { available: count === 0, message: `${code} is already a promotion` }
      }}
      onSave={async (next) => {
        const response = await fetch(discount.id ? `${admin}/${discount.id}` : admin, {
          method: "POST",
          credentials: "include",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(toPromotion(next)),
        })
        if (response.ok) return
        const { message } = await response.json()
        if (/code/i.test(message)) return { code: message }
        throw new Error(message)
      }}
    />
  )
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `DiscountBuilder` | The whole page: pinned header with the title, status badge and actions, the offer and rules cards, the preview rail (a collapsible strip under the header on phones) and the save bar. |
| `TypeChooser` | The “Create a discount” dialog with four types and number-key shortcuts. A bottom sheet on phones. |
| `DiscountPreview` | The summary sentence, status line, sample checkout with a qualifies toggle, warnings and, for saved discounts, performance. |
| `DiscountStatusBadge` | Draft, Scheduled, Active, Ends in 2 days, Expired or Limit reached. |
| `applyDiscount, sampleCart` | Pure helpers that apply a discount to a cart and build a cart that qualifies, or just misses. |
| `describeDiscount, discountWarnings, qualifyMessage` | Plain-English clauses, risk warnings and the storefront message for a cart that doesn’t qualify. |
| `validateDiscount, suggestCode, generateCode, cleanCode, nextCode` | Specific field errors (drafts skip missing values), code suggestions such as SAVE15 and readable random codes. |
| `schedulePresets, getDiscountStatus, fromZonedDateTime, toZonedDateTime` | End-date presets in the store’s time zone, status at a moment in time and time zone conversion. |

## API reference

### DiscountBuilder

Also takes div props. Fills its parent’s height; only the content scrolls.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `discount` | `Discount` | – | The saved discount, or createDiscount() for a new one. New discounts start now as drafts. The form edits a draft of it and adopts new values when clean. |
| `onSave` | `(discount: Discount, { intent: "draft" \| "live" }) => Promise<DiscountErrors \| void>` | – | Called with a cleaned discount. A live save resolves “now” to the current time. Return field errors to show them in place, or throw to show the message in the save bar. |
| `onCheckCode` | `(code: string, { signal }) => Promise<boolean \| { available: boolean; message?: string }>` | – | Checks that a code is free, 400 ms after typing stops. A taken code offers the next free variant, such as WELCOME11. |
| `products` | `Product[]` | – | Products for the pickers and the sample checkout, in the shared catalog shape. |
| `collections` | `DiscountCollection[]` | `[]` | Collections with an optional count, image and productIds. productIds lets the preview build carts for collection discounts. |
| `segments` | `DiscountSegment[]` | `[]` | Customer segments with an optional customer count. |
| `customers` | `DiscountCustomer[]` | `[]` | Customers with a name and email. |
| `stats` | `{ uses: number; sales: Money; orders?: number; lastUsedAt?: string }` | – | Shown as Performance for saved discounts only. |
| `existingDiscounts` | `{ code?: string; title?: string; type: DiscountType }[]` | – | Other live discounts, used to word the Combines with examples (“e.g. FREESHIP can apply on top”). |
| `showTypePicker` | `boolean` | `true` | Show the type dialog for new discounts. Turn it off when the type comes from the route. |
| `defaultTypePickerOpen` | `boolean` | `true` | Open the type dialog when a new discount mounts. |
| `sampleProductIds` | `string[]` | – | Products to prefer in the sample checkout. |
| `sampleShipping` | `Money \| null` | `$12.00` | Shipping rate in the sample checkout. |
| `timeZone` | `string` | `"UTC"` | The store’s time zone for dates, presets and the schedule note. |
| `locale` | `string` | `"en-US"` | Formats money, dates and counts. |
| `now` | `Date \| number` | – | Fixes the clock, for tests and screenshots. |
| `breadcrumb` | `ReactNode` | – | Shown above the title, such as a link back to Discounts. |
| `onDuplicate, onDeactivate` | `(discount: Discount) => void` | – | Adds Duplicate and End now to the overflow menu of saved discounts. |
| `onChange, onDiscard` | `(discount: Discount) => void, () => void` | – | Draft changes and discards. |
| `generateCode` | `() => string` | – | Replaces the built-in random code (WORD-XXXX). |
| `getProductImage` | `(image: ProductImage) => string` | – | Returns a thumbnail URL for pickers and the checkout. |
| `actionsRef` | `Ref<{ save, discard, nudge, isDirty, openTypePicker }>` | – | Imperative actions, such as nudging the save bar when someone tries to leave with unsaved changes. |
| `labels` | `Partial<DiscountBuilderLabels>` | – | Button and save bar text. |

### DiscountPreview

The rail on its own, for a list’s side panel.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `discount` | `Discount` | – | The discount to preview. |
| `products` | `Product[]` | – | Used to build the sample cart. |
| `status` | `DiscountStatusInfo \| null` | – | From getDiscountStatus. |
| `onClause` | `(id) => void` | – | Called when a sentence clause is clicked, to jump to its control. |

### applyDiscount

applyDiscount(discount, cart, { collections }) returns line discounts, subtotal, discount and shipping totals, total, qualifies and a reason when it doesn’t.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |

### sampleCart

sampleCart(discount, products, { qualifies, collections, preferredIds, shipping }) returns a cart that crosses the minimum or just misses it, or null when every cart qualifies.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |

## Keyboard

| Key | Action |
| --- | --- |
| `⌘` `S` | Creates or saves the discount. Ctrl+S on Windows and Linux. Works while typing. |
| `⌘` `⇧` `S` | Saves a new discount as a draft. Ctrl+Shift+S on Windows and Linux. |
| `⌘` `G` | Generates a new code and focuses the code field. Ctrl+G on Windows and Linux. |
| `1` `2` `3` `4` | In the type dialog, picks a type. |
| `↑` `↓` | Moves between types in the dialog and between rule rows. |
| `Tab` | In an empty code field, accepts the suggested code, such as SAVE15. |
| `Esc` | Closes the open dialog, picker or menu, or collapses the rule row you’re in. |

## Accessibility

- Every sentence token is a real input or button with a full name, such as “Percentage off” or “Applies to, Ring Vase and Glass Carafe”. Errors are linked with aria-describedby and marked aria-invalid.
- Errors show when a field is left, not while typing, and clear on the keystroke that fixes them. A failed save moves focus to the first invalid control and opens its rule row.
- Rule rows are buttons with aria-expanded and aria-controls. Their value text is real text, so the collapsed card reads as a summary.
- Code availability, generated codes and save results are announced in polite live regions. The save bar’s errors use role=alert through IslandBar.
- The checkout result line is a status region, and color is never the only signal: savings and failures have icons and words.
- Inputs are 16px on touch screens, touch targets are at least 44px and all motion has a reduced-motion variant.

## Built with

The free HextaUI components Discount Builder is made from. Each one installs on its own.

- [Avatar](https://hextaui.com/docs/avatar) - User photos with an initials fallback, status badges and stacked groups that collapse into a count.
- [Badge](https://hextaui.com/docs/badge) - Status labels with colored dots, removable tags that slide closed and counts that roll to their new value.
- [Button](https://hextaui.com/docs/button) - Buttons in every variant and size, with a built-in loading, success and error flow that skips the spinner for fast requests.
- [Card](https://hextaui.com/docs/card) - A surface for grouping content, with three variants, edge-to-edge media, concentric radii and whole-card links.
- [Checkbox](https://hextaui.com/docs/checkbox) - A checkbox whose check draws in, with indeterminate parents, groups and labels that share its hover.
- [Collapsible](https://hextaui.com/docs/collapsible) - A panel that shows and hides with height motion you can reverse mid-way, without jumping the layout.
- [Combobox](https://hextaui.com/docs/combobox) - A filterable select with chips, groups and async results, in a popup that resizes as you type.
- [Date picker](https://hextaui.com/docs/date-picker) - A button that opens a calendar in a popover, or a bottom sheet on phones, for single dates and ranges.
- [Dialog](https://hextaui.com/docs/dialog) - A window over the page for forms and focused tasks, with a pinned header and footer, nesting, and a swipeable bottom sheet on phones.
- [Dropdown menu](https://hextaui.com/docs/dropdown-menu) - A menu of actions and options behind a button, with groups, submenus, checkbox and radio items, and shortcuts.
- [Field](https://hextaui.com/docs/field) - Labels, descriptions and errors wired to their control, with validation states and layouts for forms.
- [Input](https://hextaui.com/docs/input) - A text input with three sizes, invalid and read-only states, native validation styling and a 16px touch font so phones never zoom in.
- [Input group](https://hextaui.com/docs/input-group) - An input with icons, text, buttons or a keyboard hint attached, sharing one border and focus ring.
- [Kbd](https://hextaui.com/docs/kbd) - Key caps for shortcuts that show the right symbols on every platform, read them out properly and press down with the real keys.
- [Number flow](https://hextaui.com/docs/number-flow) - Animated numbers where only the changed digits spin, with any Intl format and locale.
- [Popover](https://hextaui.com/docs/popover) - A floating panel anchored to a trigger that resizes smoothly with its content and follows the trigger’s direction.
- [Progress](https://hextaui.com/docs/progress) - A bar or ring that shows how far a task has come, eases between updates and slides while the total is unknown.
- [Separator](https://hextaui.com/docs/separator) - A hairline that divides content horizontally or vertically, with an optional label and a decorative mode for purely visual lines.
- [Spinner](https://hextaui.com/docs/spinner) - A loading indicator with Apple-style ticks or a breathing ring that can wait before showing and stay long enough not to flicker.
- [Switch](https://hextaui.com/docs/switch) - An on/off toggle you can tap, press or drag, with a thumb that stretches under your finger and an optional pending state for saves.
- [Toggle group](https://hextaui.com/docs/toggle-group) - A row of toggles for one choice or many, with a fill that slides to the picked item, joined or spaced items and arrow-key focus.
- [Tooltip](https://hextaui.com/docs/tooltip) - A short hint on hover or keyboard focus that opens after a brief rest, switches instantly between neighbours and shows shortcuts.

## Code

13 files, added to components/blocks/discount-builder.
