HextaUI

Ein Rabatt-Builder, in dem das Angebot ein einziger bearbeitbarer Satz ist, mit Live-Vorschau des Checkouts. Deckt Code-Prüfungen, Entwürfe und Zeitpläne ab.

Kategorie
E-Commerce
Genutzte Komponenten
22
Dateien
13
Anwendungsbeispiele
3
Zugang
HextaUI Pro (55 Blöcke)
Quellcode aktualisiert
Open in new tab

Teil von HextaUI Pro, alle 55 Blöcke, $79 einmalig, Pläne vergleichen

Discount Builder ist die Seite, auf der ein Händler einen Rabatt erstellt oder bearbeitet. Ein neuer Rabatt öffnet sich mit einem kurzen Typ-Dialog: Rabatt auf Produkte, Rabatt auf die Bestellung, Buy X get Y oder kostenloser Versand. Danach ist das Angebot ein Satz, den der Händler direkt bearbeitet: „Customers get [15%] off [Ring Vase and Glass Carafe]“. Jeder unterstrichene Teil ist ein echtes Control mit Label, sodass Screenreader „Percentage off, 15“ hören statt eines Satzes aus Buttons.

Alles Optionale liegt in einer Rules-Karte als eingeklappte Zeilen: Minimum purchase, Customers, Usage limits, Combines with und Schedule. Jede Zeile zeigt ihren aktuellen Wert, sodass ein Händler das ganze Setup lesen kann, ohne etwas zu öffnen, und jedes Panel erklärt seine Einstellung mit einem Beispiel. Zeitpläne starten standardmäßig jetzt und bieten Presets für 7 Tage, 30 Tage und das Monatsende, in der Zeitzone des Stores.

Die Rail ist eine Vorschau, keine Liste von Einstellungen. Sie zeigt das Angebot als einen Satz und einen Beispiel-Checkout aus deinen Produkten, mit angewendetem Rabatt und dem, was der Kunde spart. Ein Qualifies-/Doesn’t-Toggle wechselt zu einem Warenkorb knapp unter dem Minimum und zeigt dieselbe Meldung wie eine Storefront, etwa „Add $10.00 more to use SUMMER15“. Riskante Einstellungen wie 100% Rabatt ohne Limit erscheinen darunter als Warnungen.

Daten gehen rein, async Callbacks kommen raus. onSave erhält einen bereinigten Discount und den Intent (draft oder live); gib Feldfehler zurück, um sie im Satz oder in den Regelzeilen zu zeigen, oder wirf einen Fehler, um die Meldung in der Save-Bar anzuzeigen. Fehler erscheinen, wenn ein Feld verlassen wird, nie beim Tippen. Neue Rabatte werden über den Header gespeichert (Save draft und Create discount). Bestehende nutzen die gemeinsame IslandBar, die nur bei ungespeicherten Änderungen erscheint.

  1. HextaUI Pro holen

    Eine einmalige Zahlung schaltet jeden Block frei, auch künftige. Preise ansehen.

  2. Die Pro-Registry zu components.json hinzufügen

    components.json
    {
      "registries": {
        "@hextaui-pro": {
          "url": "https://hextaui.com/r/pro/{name}.json",
          "headers": {
            "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
          }
        }
      }
    }
  3. Token hinzufügen

    Erstelle auf deiner Kontoseite einen Token und trage ihn in .env.local als HEXTAUI_PRO_TOKEN ein.

  4. Den Block hinzufügen

    pnpm dlx shadcn@latest add @hextaui-pro/discount-builder

Shopify Admin API

Ordne den Discount discountCodeBasicCreate oder discountAutomaticBxgyCreate zu und gib Shopifys userErrors als Feldfehler zurück. Entwürfe landen in deiner eigenen Tabelle, da Shopify keine Rabattentwürfe kennt. Der Typ kommt aus der Route, daher ist der Typ-Dialog aus.

"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 und Promotion-Codes

Ein aktiver Rabatt wird zu einem Stripe-Coupon plus einem Promotion-Code mit Einlöselimit, Erstbestellungsregel und Ablaufdatum. Stripes Fehler für doppelte Codes kommt als Fehler am Code-Feld zurück.

"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 haben dieselbe Form und unterstützen den Entwurfsstatus direkt. onCheckCode listet Promotions nach Code, um zu prüfen, ob ein neuer frei ist.

"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)
      }}
    />
  )
}

Aufbau

Die Teile, die du zusammensetzt, von außen nach innen.

PartBeschreibung
DiscountBuilderDie ganze Seite: fixierter Header mit Titel, Status-Badge und Aktionen, die Angebots- und Regelkarten, die Vorschau-Rail (auf Smartphones ein einklappbarer Streifen unter dem Header) und die Save-Bar.
TypeChooserDer Dialog „Create a discount“ mit vier Typen und Zifferntasten-Kürzeln. Auf Smartphones ein Bottom Sheet.
DiscountPreviewDer Zusammenfassungssatz, die Statuszeile, der Beispiel-Checkout mit Qualifies-Toggle, Warnungen und bei gespeicherten Rabatten die Performance.
DiscountStatusBadgeDraft, Scheduled, Active, Ends in 2 days, Expired oder Limit reached.
applyDiscount, sampleCartReine Helfer, die einen Rabatt auf einen Warenkorb anwenden und einen Warenkorb bauen, der qualifiziert oder knapp scheitert.
describeDiscount, discountWarnings, qualifyMessageSatzteile in einfachem Englisch, Risikowarnungen und die Storefront-Meldung für einen Warenkorb, der nicht qualifiziert.
validateDiscount, suggestCode, generateCode, cleanCode, nextCodeKonkrete Feldfehler (Entwürfe überspringen fehlende Werte), Code-Vorschläge wie SAVE15 und lesbare Zufallscodes.
schedulePresets, getDiscountStatus, fromZonedDateTime, toZonedDateTimeEnddatum-Presets in der Zeitzone des Stores, Status zu einem Zeitpunkt und Zeitzonenumrechnung.

DiscountBuilder

Nimmt außerdem div-Props an. Füllt die Höhe des Elternelements; nur der Inhalt scrollt.

PropTypStandard
discountDer gespeicherte Rabatt oder createDiscount() für einen neuen. Neue Rabatte starten jetzt als Entwürfe. Das Formular bearbeitet einen Entwurf davon und übernimmt neue Werte, wenn es unverändert ist.
Discount–
onSaveWird mit einem bereinigten Rabatt aufgerufen. Ein Live-Speichern löst „now“ in die aktuelle Zeit auf. Gib Feldfehler zurück, um sie an Ort und Stelle zu zeigen, oder wirf einen Fehler, um die Meldung in der Save-Bar anzuzeigen.
(discount: Discount, { intent: "draft" | "live" }) => Promise<DiscountErrors | void>–
onCheckCodePrüft 400 ms nach dem Tippen, ob ein Code frei ist. Bei einem vergebenen Code wird die nächste freie Variante angeboten, etwa WELCOME11.
(code: string, { signal }) => Promise<boolean | { available: boolean; message?: string }>–
productsProdukte für die Picker und den Beispiel-Checkout, in der gemeinsamen Katalogform.
Product[]–
collectionsCollections mit optionalem count, image und productIds. Mit productIds kann die Vorschau Warenkörbe für Collection-Rabatte bauen.
DiscountCollection[][]
segmentsKundensegmente mit optionaler Kundenanzahl.
DiscountSegment[][]
customersKunden mit Name und E-Mail.
DiscountCustomer[][]
statsWird nur bei gespeicherten Rabatten als Performance angezeigt.
{ uses: number; sales: Money; orders?: number; lastUsedAt?: string }–
existingDiscountsAndere aktive Rabatte, mit denen die Beispiele für Combines with formuliert werden („e.g. FREESHIP can apply on top“).
{ code?: string; title?: string; type: DiscountType }[]–
showTypePickerZeigt den Typ-Dialog für neue Rabatte. Schalte ihn aus, wenn der Typ aus der Route kommt.
booleantrue
defaultTypePickerOpenÖffnet den Typ-Dialog, wenn ein neuer Rabatt gemountet wird.
booleantrue
sampleProductIdsProdukte, die im Beispiel-Checkout bevorzugt werden.
string[]–
sampleShippingVersandkosten im Beispiel-Checkout.
Money | null$12.00
timeZoneDie Zeitzone des Stores für Datumsangaben, Presets und den Zeitplanhinweis.
string"UTC"
localeFormatiert Geldbeträge, Datumsangaben und Anzahlen.
string"en-US"
nowFixiert die Uhr, für Tests und Screenshots.
Date | number–
breadcrumbWird über dem Titel angezeigt, etwa ein Link zurück zu Discounts.
ReactNode–
onDuplicate, onDeactivateFügt dem Overflow-Menü gespeicherter Rabatte Duplicate und End now hinzu.
(discount: Discount) => void–
onChange, onDiscardEntwurfsänderungen und Verwerfen.
(discount: Discount) => void, () => void–
generateCodeErsetzt den eingebauten Zufallscode (WORD-XXXX).
() => string–
getProductImageGibt eine Thumbnail-URL für Picker und den Checkout zurück.
(image: ProductImage) => string–
actionsRefImperative Aktionen, etwa die Save-Bar anzustupsen, wenn jemand mit ungespeicherten Änderungen gehen will.
Ref<{ save, discard, nudge, isDirty, openTypePicker }>–
labelsText für Buttons und Save-Bar.
Partial<DiscountBuilderLabels>–

DiscountPreview

Die Rail allein, für das Seitenpanel einer Liste.

PropTypStandard
discountDer Rabatt für die Vorschau.
Discount–
productsWird zum Bauen des Beispiel-Warenkorbs verwendet.
Product[]–
statusAus getDiscountStatus.
DiscountStatusInfo | null–
onClauseWird aufgerufen, wenn ein Satzteil angeklickt wird, um zu seinem Control zu springen.
(id) => void–

applyDiscount

applyDiscount(discount, cart, { collections }) gibt Zeilenrabatte, Zwischensumme, Rabatt- und Versandsummen, Gesamtsumme, qualifies und einen Grund zurück, falls nicht qualifiziert.

PropTypStandard

sampleCart

sampleCart(discount, products, { qualifies, collections, preferredIds, shipping }) gibt einen Warenkorb zurück, der das Minimum überschreitet oder knapp verfehlt, oder null, wenn jeder Warenkorb qualifiziert.

PropTypStandard
TasteAktion
⌘SErstellt oder speichert den Rabatt. Ctrl+S unter Windows und Linux. Funktioniert auch beim Tippen.
⌘⇧SSpeichert einen neuen Rabatt als Entwurf. Ctrl+Shift+S unter Windows und Linux.
⌘GGeneriert einen neuen Code und fokussiert das Code-Feld. Ctrl+G unter Windows und Linux.
1234Wählt im Typ-Dialog einen Typ.
↑↓Wechselt im Dialog zwischen Typen und zwischen Regelzeilen.
TabÜbernimmt in einem leeren Code-Feld den vorgeschlagenen Code, etwa SAVE15.
EscSchließt den offenen Dialog, Picker oder das Menü oder klappt die Regelzeile ein, in der du bist.
  • Jedes Satz-Token ist ein echtes Input oder ein Button mit vollständigem Namen, etwa „Percentage off“ oder „Applies to, Ring Vase and Glass Carafe“. Fehler sind per aria-describedby verknüpft und mit aria-invalid markiert.
  • Fehler erscheinen, wenn ein Feld verlassen wird, nicht beim Tippen, und verschwinden mit dem Tastendruck, der sie behebt. Ein fehlgeschlagenes Speichern setzt den Fokus auf das erste ungültige Control und öffnet seine Regelzeile.
  • Regelzeilen sind Buttons mit aria-expanded und aria-controls. Ihr Werttext ist echter Text, sodass sich die eingeklappte Karte wie eine Zusammenfassung liest.
  • Code-Verfügbarkeit, generierte Codes und Speicherergebnisse werden in höflichen Live-Regions angesagt. Die Fehler der Save-Bar nutzen role=alert über IslandBar.
  • Die Ergebniszeile des Checkouts ist eine Status-Region, und Farbe ist nie das einzige Signal: Ersparnisse und Fehlschläge haben Icons und Worte.
  • Inputs sind auf Touchscreens 16px groß, Touch-Ziele mindestens 44px, und jede Bewegung hat eine Reduced-Motion-Variante.

Gebaut mit

Die kostenlosen HextaUI-Komponenten, aus denen Discount Builder besteht. Jede lässt sich einzeln installieren.

Code

13 Dateien, hinzugefügt zu components/blocks/discount-builder.