HextaUI

特典内容を1つの編集可能な文で表し、チェックアウトのライブプレビューを備えた割引ビルダー。コードのチェック、下書き、スケジュールに対応します。

カテゴリ
EC
使用コンポーネント
22
ファイル
13
使用例
3
利用
HextaUI Pro(55 ブロック)
ソース更新日
Open in new tab

HextaUI Pro に含まれます, 全 55 ブロック, $79 買い切り, プランを比較

Discount Builder は、マーチャントがディスカウントを作成または編集するためのページです。新しいディスカウントは、短いタイプ選択ダイアログから始まります。商品の割引、注文の割引、X を買うと Y がもらえる、送料無料のいずれかです。その後、オファーはマーチャントがその場で編集する文になります。「Customers get [15%] off [Ring Vase and Glass Carafe]」のような文です。下線の付いた各部分はラベル付きの実際のコントロールなので、スクリーンリーダーにはボタンの羅列ではなく「Percentage off, 15」と読み上げられます。

任意の設定はすべて、Rules カードに折りたたまれた行として置かれます。Minimum purchase、Customers、Usage limits、Combines with、Schedule です。各行には現在の値が表示されるため、マーチャントは何も開かずに設定全体を読み取れます。各パネルは例を使って設定を説明します。スケジュールはデフォルトで今すぐ開始し、ストアのタイムゾーンで 7 日、30 日、月末のプリセットを提供します。

レールは設定の一覧ではなく、プレビューです。オファーを 1 つの文として表示し、商品から作ったサンプルチェックアウトに、ディスカウントを適用した結果と顧客の割引額を示します。Qualifies / Doesn’t のトグルで最低額をわずかに下回るカートに切り替わり、「Add $10.00 more to use SUMMER15」のようにストアフロントと同じメッセージが表示されます。上限なしの 100% オフのような危険な設定は、その下に警告として表示されます。

データを渡すと、非同期のコールバックが返ってきます。onSave は整形された Discount と意図 (draft または live) を受け取ります。フィールドのエラーを返すと文やルール行に表示され、エラーを投げると保存バーにメッセージが表示されます。エラーはフィールドを離れたときに表示され、入力中には表示されません。新しいディスカウントはヘッダー (Save draft と Create discount) から保存します。既存のものは共有の IslandBar を使い、未保存の変更があるときだけ表示されます。

  1. HextaUI Pro を入手する

    一度の支払いで、今後追加されるものも含めてすべてのブロックが使えます。料金を見る。

  2. Proレジストリをcomponents.jsonに追加する

    components.json
    {
      "registries": {
        "@hextaui-pro": {
          "url": "https://hextaui.com/r/pro/{name}.json",
          "headers": {
            "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
          }
        }
      }
    }
  3. トークンを追加する

    アカウントページでトークンを作成し、.env.local に HEXTAUI_PRO_TOKEN として設定してください。

  4. ブロックを追加する

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

Shopify Admin API

Discount を discountCodeBasicCreate または discountAutomaticBxgyCreate に対応付け、Shopify の userErrors をフィールドのエラーとして返します。Shopify には下書きのディスカウントがないため、下書きは独自のテーブルに保存します。タイプはルートから決まるため、タイプ選択ダイアログはオフにします。

"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 のクーポンとプロモーションコード

有効なディスカウントは、Stripe のクーポンと、利用上限、初回注文ルール、有効期限を持つプロモーションコードになります。Stripe のコード重複エラーは、コードフィールドのエラーとして返されます。

"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 のプロモーション

Medusa v2 のプロモーションは同じ形をしており、下書きのステータスを直接サポートします。onCheckCode はコードでプロモーションを一覧し、新しいコードが使用可能か確認します。

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

構造

外側から内側へ組み合わせるパーツ。

パーツ説明
DiscountBuilderページ全体。タイトル、ステータスバッジ、アクションを持つ固定ヘッダー、オファーとルールのカード、プレビューのレール (スマートフォンではヘッダー下の折りたたみ可能な帯)、保存バーです。
TypeChooser4 つのタイプと数字キーのショートカットを持つ「Create a discount」ダイアログ。スマートフォンではボトムシートになります。
DiscountPreview要約の文、ステータス行、条件トグル付きのサンプルチェックアウト、警告、そして保存済みのディスカウントではパフォーマンス。
DiscountStatusBadgeDraft、Scheduled、Active、Ends in 2 days、Expired、Limit reached のいずれか。
applyDiscount, sampleCartカートにディスカウントを適用し、条件を満たすカート、またはわずかに満たさないカートを作る純粋なヘルパー。
describeDiscount, discountWarnings, qualifyMessage平易な英語の節、リスクの警告、条件を満たさないカート向けのストアフロントのメッセージ。
validateDiscount, suggestCode, generateCode, cleanCode, nextCode具体的なフィールドのエラー (下書きでは未入力の値をスキップ)、SAVE15 のようなコードの提案、読みやすいランダムコード。
schedulePresets, getDiscountStatus, fromZonedDateTime, toZonedDateTimeストアのタイムゾーンでの終了日のプリセット、特定の時点でのステータス、タイムゾーンの変換。

DiscountBuilder

div のプロップも渡せます。親の高さいっぱいに広がり、スクロールするのはコンテンツだけです。

プロパティ型デフォルト
discount保存済みのディスカウント、または新規の場合は createDiscount()。新しいディスカウントは今すぐ開始の下書きとして始まります。フォームはその下書きを編集し、未変更のときは新しい値を取り込みます。
Discount–
onSave整形されたディスカウントとともに呼ばれます。有効として保存すると、「now」は現在時刻に解決されます。フィールドのエラーを返すとその場に表示され、エラーを投げると保存バーにメッセージが表示されます。
(discount: Discount, { intent: "draft" | "live" }) => Promise<DiscountErrors | void>–
onCheckCode入力が止まってから 400 ms 後に、コードが使用可能か確認します。使用済みのコードには、WELCOME11 のような次に使用可能な候補が提示されます。
(code: string, { signal }) => Promise<boolean | { available: boolean; message?: string }>–
productsピッカーとサンプルチェックアウト用の商品。共有カタログの形式です。
Product[]–
collections任意で件数、画像、productIds を持つコレクション。productIds があると、プレビューでコレクションのディスカウント用のカートを作れます。
DiscountCollection[][]
segments任意で顧客数を持つ顧客セグメント。
DiscountSegment[][]
customers名前とメールアドレスを持つ顧客。
DiscountCustomer[][]
stats保存済みのディスカウントでのみ Performance として表示されます。
{ uses: number; sales: Money; orders?: number; lastUsedAt?: string }–
existingDiscountsほかの有効なディスカウント。Combines with の例 (「e.g. FREESHIP can apply on top」) の文言に使われます。
{ code?: string; title?: string; type: DiscountType }[]–
showTypePicker新しいディスカウントでタイプ選択ダイアログを表示します。タイプがルートから決まる場合はオフにします。
booleantrue
defaultTypePickerOpen新しいディスカウントがマウントされたときにタイプ選択ダイアログを開きます。
booleantrue
sampleProductIdsサンプルチェックアウトで優先する商品。
string[]–
sampleShippingサンプルチェックアウトの送料。
Money | null$12.00
timeZone日付、プリセット、スケジュールの注記に使うストアのタイムゾーン。
string"UTC"
locale金額、日付、件数をフォーマットします。
string"en-US"
nowテストやスクリーンショット用に時刻を固定します。
Date | number–
breadcrumbDiscounts に戻るリンクなど、タイトルの上に表示されます。
ReactNode–
onDuplicate, onDeactivate保存済みディスカウントのオーバーフローメニューに Duplicate と End now を追加します。
(discount: Discount) => void–
onChange, onDiscard下書きの変更と破棄。
(discount: Discount) => void, () => void–
generateCode組み込みのランダムコード (WORD-XXXX) を置き換えます。
() => string–
getProductImageピッカーとチェックアウト用のサムネイル URL を返します。
(image: ProductImage) => string–
actionsRef未保存の変更があるままページを離れようとしたときに保存バーを揺らすなどの、命令的なアクション。
Ref<{ save, discard, nudge, isDirty, openTypePicker }>–
labelsボタンと保存バーのテキスト。
Partial<DiscountBuilderLabels>–

DiscountPreview

一覧のサイドパネル用の、レール単体。

プロパティ型デフォルト
discountプレビューするディスカウント。
Discount–
productsサンプルカートの作成に使われます。
Product[]–
statusgetDiscountStatus から。
DiscountStatusInfo | null–
onClause文の節がクリックされたときに、そのコントロールへ移動するために呼ばれます。
(id) => void–

applyDiscount

applyDiscount(discount, cart, { collections }) は、行ごとの割引、小計、割引と送料の合計、合計、qualifies、そして条件を満たさない場合はその理由を返します。

プロパティ型デフォルト

sampleCart

sampleCart(discount, products, { qualifies, collections, preferredIds, shipping }) は、最低額を超えるカート、またはわずかに届かないカートを返します。どのカートも条件を満たす場合は null を返します。

プロパティ型デフォルト
キーアクション
⌘Sディスカウントを作成または保存します。Windows と Linux では Ctrl+S です。入力中も機能します。
⌘⇧S新しいディスカウントを下書きとして保存します。Windows と Linux では Ctrl+Shift+S です。
⌘G新しいコードを生成し、コードフィールドにフォーカスします。Windows と Linux では Ctrl+G です。
1234タイプ選択ダイアログで、タイプを選びます。
↑↓ダイアログ内のタイプ間と、ルール行間を移動します。
Tab空のコードフィールドで、SAVE15 のような提案されたコードを受け入れます。
Esc開いているダイアログ、ピッカー、メニューを閉じるか、現在のルール行を折りたたみます。
  • 文の各トークンは、「Percentage off」や「Applies to, Ring Vase and Glass Carafe」のような完全な名前を持つ実際の入力欄またはボタンです。エラーは aria-describedby で関連付けられ、aria-invalid が付きます。
  • エラーは入力中ではなくフィールドを離れたときに表示され、修正するキー入力の時点で消えます。保存に失敗すると、最初の無効なコントロールにフォーカスが移り、そのルール行が開きます。
  • ルール行は aria-expanded と aria-controls を持つボタンです。値のテキストは実際のテキストなので、折りたたまれたカードは要約として読み上げられます。
  • コードの使用可否、生成されたコード、保存結果は、polite なライブリージョンで読み上げられます。保存バーのエラーは IslandBar を通じて role=alert を使います。
  • チェックアウトの結果行は status リージョンで、色だけで伝えることはありません。割引額と失敗にはアイコンと言葉が付きます。
  • タッチスクリーンでは入力欄は 16px、タッチターゲットは 44px 以上で、すべてのモーションに視差効果を減らす設定用のバリエーションがあります。

使用技術

Discount Builder を構成する無料のHextaUIコンポーネントです。それぞれ単独でインストールできます。

コード

13 個のファイルを components/blocks/discount-builder に追加しました。