Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Let a merchant write a percentage ladder on the agreement itself

Damian Legawiec83ae591604db
diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.ts
index 73d5e92c86..56cb1779fa 100644
--- a/packages/dashboard-ui/src/index.ts
+++ b/packages/dashboard-ui/src/index.ts
@@ -50,6 +50,7 @@ export * from './spree/label-upload-dialog'
export * from './spree/order-cancel-dialog'
export * from './spree/post-sale-create-dialogs'
export * from './spree/post-sale-fields'
+export * from './spree/quantity-tier-editor'
export * from './spree/return-dialogs'
// JsonPreviewDrawer and JsonValueView are intentionally NOT re-exported from
diff --git a/packages/dashboard-ui/src/spree/quantity-tier-editor.tsx b/packages/dashboard-ui/src/spree/quantity-tier-editor.tsx
new file mode 100644
index 0000000000..26c4af5519
--- /dev/null
+++ b/packages/dashboard-ui/src/spree/quantity-tier-editor.tsx
@@ -0,0 +1,162 @@
+import { PlusIcon, XIcon } from 'lucide-react'
+import { Button } from '../ui/button'
+import { Input } from '../ui/input'
+import { InputGroup, InputGroupAddon, InputGroupInput } from '../ui/input-group'
+
+/**
+ * One rung of a quantity ladder: from `minQuantity` units up, the value is
+ * `value`. What the value means is the caller's business — a unit price on a
+ * price row, a percentage on a list's adjustment.
+ */
+export interface QuantityTierRow {
+ /** Stable key for React. The caller owns it; a client-side id is fine. */
+ id: string
+ /** The quantity this rung applies from, as typed. */
+ minQuantity: string
+ /** The rung's figure, as typed. */
+ value: string
+ /**
+ * Locked rungs render their quantity read-only. Used for the bottom rung of
+ * a price ladder, which is the list's ordinary price and always quantity 1.
+ */
+ locked?: boolean
+}
+
+export interface QuantityTierEditorLabels {
+ /** Column header over the quantity inputs. */
+ quantity: string
+ /** Column header over the value inputs. */
+ value: string
+ /** The "add a rung" button. */
+ add: string
+ /** Accessible name for a rung's remove button. `{quantity}` is substituted. */
+ remove: string
+ /** Shown in place of the rows when the ladder is empty. */
+ empty?: string
+ /** Shown under the rows — a validation message, or a hint. */
+ hint?: string
+}
+
+export interface QuantityTierEditorProps {
+ rows: QuantityTierRow[]
+ labels: QuantityTierEditorLabels
+ onChange: (id: string, field: 'minQuantity' | 'value', next: string) => void
+ onAdd: () => void
+ onRemove: (id: string) => void
+ /** Prefix or suffix rendered inside the value input — a currency symbol, a `%`. */
+ valueAddon?: string
+ /** Which side the addon sits on. Defaults to a leading addon. */
+ valueAddonAlign?: 'inline-start' | 'inline-end'
+ /** Hides "add" once the ladder is full, so the cap is visible rather than a surprise. */
+ canAdd?: boolean
+ disabled?: boolean
+ /** Rendered in destructive styling under the rows. */
+ error?: string
+}
+
+/**
+ * The `[Min qty | value]` ladder both halves of volume pricing are edited
+ * through: fixed breaks on a variant's price rows, and quantity bands on a
+ * price list's percentage (docs/plans/6.0-volume-pricing.md).
+ *
+ * Headless — it holds no state, fetches nothing and knows no translations.
+ * The caller owns the rows and every string.
+ */
+export function QuantityTierEditor({
+ rows,
+ labels,
+ onChange,
+ onAdd,
+ onRemove,
+ valueAddon,
+ valueAddonAlign = 'inline-start',
+ canAdd = true,
+ disabled,
+ error,
+}: QuantityTierEditorProps) {
+ return (
+ <div className="flex flex-col gap-2">
+ {rows.length === 0 ? (
+ labels.empty ? (
+ <p className="text-xs text-muted-foreground">{labels.empty}</p>
+ ) : null
+ ) : (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <span className="w-24">{labels.quantity}</span>
+ <span className="flex-1">{labels.value}</span>
+ <span className="w-8" />
+ </div>
+ {rows.map((row) => (
+ <div key={row.id} className="flex items-center gap-2">
+ <Input
+ type="number"
+ step="1"
+ min="1"
+ className="w-24"
+ value={row.minQuantity}
+ readOnly={row.locked}
+ disabled={disabled}
+ aria-label={labels.quantity}
+ onChange={(event) => onChange(row.id, 'minQuantity', event.target.value)}
+ />
+ <InputGroup className="flex-1">
+ {valueAddon && valueAddonAlign === 'inline-start' && (
+ <InputGroupAddon>{valueAddon}</InputGroupAddon>
+ )}
+ <InputGroupInput
+ type="number"
+ step="0.01"
+ value={row.value}
+ disabled={disabled}
+ aria-label={labels.value}
+ onChange={(event) => onChange(row.id, 'value', event.target.value)}
+ />
+ {valueAddon && valueAddonAlign === 'inline-end' && (
+ <InputGroupAddon align="inline-end">{valueAddon}</InputGroupAddon>
+ )}
+ </InputGroup>
+ {/* The bottom rung is the ordinary price, not a tier — removing
+ it would be removing the price itself. */}
+ {row.locked ? (
+ <span className="w-8" />
+ ) : (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-8 shrink-0"
+ disabled={disabled}
+ aria-label={labels.remove.replace('{quantity}', row.minQuantity)}
+ onClick={() => onRemove(row.id)}
+ >
+ <XIcon className="size-4" />
+ </Button>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {canAdd && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="self-start"
+ disabled={disabled}
+ onClick={onAdd}
+ >
+ <PlusIcon className="size-4" />
+ {labels.add}
+ </Button>
+ )}
+
+ {error ? (
+ <p className="text-xs text-destructive">{error}</p>
+ ) : labels.hint ? (
+ <p className="text-xs text-muted-foreground">{labels.hint}</p>
+ ) : null}
+ </div>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/catalog-pricing-fields.tsx b/packages/dashboard/src/components/spree/catalog-pricing-fields.tsx
index 7b78484c56..afed0b82fa 100644
--- a/packages/dashboard/src/components/spree/catalog-pricing-fields.tsx
+++ b/packages/dashboard/src/components/spree/catalog-pricing-fields.tsx
@@ -12,6 +12,8 @@ import {
InputGroupAddon,
InputGroupInput,
InputGroupText,
+ QuantityTierEditor,
+ type QuantityTierRow,
Select,
SelectContent,
SelectItem,
@@ -21,14 +23,14 @@ import {
} from '@spree/dashboard-ui'
import { InfoIcon, TableIcon } from '@spree/dashboard-ui/icons'
import { useState } from 'react'
-import { Controller, type UseFormReturn } from 'react-hook-form'
+import { Controller, type UseFormReturn, useFieldArray } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import {
CATALOG_PRICING_MODES,
type CatalogFormValues,
type CatalogPricingMode,
} from '../../schemas/catalog'
-import { ADJUSTMENT_DIRECTIONS } from '../../schemas/price-list'
+import { ADJUSTMENT_DIRECTIONS, MAXIMUM_QUANTITY_TIERS } from '../../schemas/price-list'
import { BulkPriceEditorDialog } from './bulk-price-editor/bulk-price-editor-dialog'
/**
@@ -237,6 +239,11 @@ export function CatalogPricingFields({
</FieldDescription>
<FieldError errors={[errors.minimum_quantity]} />
</div>
+
+ {/* Bands on the percentage above: the figure entered above is what
+ the agreement gives at one unit, and each band is what it gives
+ from its quantity up (docs/plans/6.0-volume-pricing.md). */}
+ <AdjustmentTierFields form={form} canEdit={canEdit} />
</>
)}
@@ -297,3 +304,67 @@ export function CatalogPricingFields({
</>
)
}
+
+/**
+ * The list's quantity bands. Kept beside the percentage it bands rather than
+ * in a card of its own — "10% off, 20% from fifty" is one sentence, and
+ * splitting it across two panels invites half of it to be edited alone.
+ */
+function AdjustmentTierFields({
+ form,
+ canEdit,
+}: {
+ form: UseFormReturn<CatalogFormValues>
+ canEdit: boolean
+}) {
+ const { t } = useTranslation()
+ const { fields, append, remove } = useFieldArray({
+ control: form.control,
+ name: 'adjustment_tiers',
+ })
+ const tiers = form.watch('adjustment_tiers')
+ const error = form.formState.errors.adjustment_tiers
+
+ const rows: QuantityTierRow[] = fields.map((field, index) => ({
+ id: field.id,
+ minQuantity: tiers?.[index]?.min_quantity ?? '',
+ value: tiers?.[index]?.percentage ?? '',
+ }))
+
+ return (
+ <div className="flex flex-col gap-2">
+ <FieldLabel>{t('admin.fields.price_list.adjustment_tiers.label')}</FieldLabel>
+ <QuantityTierEditor
+ rows={rows}
+ labels={{
+ quantity: t('admin.fields.price_list.adjustment_tiers.quantity'),
+ value: t('admin.fields.price_list.adjustment_tiers.percentage'),
+ add: t('admin.fields.price_list.adjustment_tiers.add'),
+ remove: t('admin.fields.price_list.adjustment_tiers.remove'),
+ empty: t('admin.fields.price_list.adjustment_tiers.empty'),
+ hint: t('admin.fields.price_list.adjustment_tiers.help'),
+ }}
+ valueAddon="%"
+ valueAddonAlign="inline-end"
+ canAdd={canEdit && fields.length < MAXIMUM_QUANTITY_TIERS}
+ disabled={!canEdit}
+ error={typeof error?.message === 'string' ? error.message : undefined}
+ onChange={(id, field, next) => {
+ const index = fields.findIndex((row) => row.id === id)
+ if (index < 0) return
+
+ form.setValue(
+ `adjustment_tiers.${index}.${field === 'minQuantity' ? 'min_quantity' : 'percentage'}`,
+ next,
+ { shouldDirty: true, shouldValidate: true },
+ )
+ }}
+ onAdd={() => append({ min_quantity: '', percentage: '' }, { shouldFocus: true })}
+ onRemove={(id) => {
+ const index = fields.findIndex((row) => row.id === id)
+ if (index >= 0) remove(index)
+ }}
+ />
+ </div>
+ )
+}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 70b1c24475..ffa2d06f90 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -1587,6 +1587,15 @@
"adjustment_magnitude": {
"label": "النسبة المئوية"
},
+ "adjustment_tiers": {
+ "add": "إضافة مستوى كمية",
+ "empty": "لا توجد مستويات — تنطبق النسبة أعلاه على كل الكميات.",
+ "help": "من كل كمية فصاعدًا تمنح الاتفاقية هذه النسبة. تُحتسب كل نسبة من السعر الأساسي، لا من المستوى الذي قبلها.",
+ "label": "مستويات الكمية",
+ "percentage": "النسبة المئوية",
+ "quantity": "من الكمية",
+ "remove": "إزالة المستوى من {quantity}"
+ },
"description": {
"label": "الوصف",
"placeholder": "وصف داخلي اختياري"
@@ -4147,7 +4156,9 @@
"adjustment_required": "أدخل نسبة مئوية.",
"adjustment_too_deep": "يجب أن تكون أقل من 100%.",
"ends_after_starts": "يجب أن يكون بعد تاريخ البدء.",
- "minimum_quantity_invalid": "أدخل عددًا صحيحًا."
+ "minimum_quantity_invalid": "أدخل عددًا صحيحًا.",
+ "tier_percentage_invalid": "كل مستوى يحتاج نسبة أقل من 100.",
+ "tier_quantity_invalid": "كل مستوى يحتاج كمية خاصة به أكبر من 1."
}
},
"product_type_adds_options_one": "يضيف هذا النوع {{options}} إلى المنتجات الجديدة.",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index ed74473fb1..4a8daa370e 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -1569,6 +1569,15 @@
"adjustment_magnitude": {
"label": "Prozentsatz"
},
+ "adjustment_tiers": {
+ "add": "Mengenstufe hinzufügen",
+ "empty": "Keine Stufen — der Prozentsatz oben gilt für jede Menge.",
+ "help": "Ab der jeweiligen Menge gilt dieser Prozentsatz. Jede Stufe wird vom Grundpreis abgezogen, nie von der Stufe darunter.",
+ "label": "Mengenstufen",
+ "percentage": "Prozentsatz",
+ "quantity": "Ab Menge",
+ "remove": "Stufe ab {quantity} entfernen"
+ },
"description": {
"label": "Beschreibung",
"placeholder": "Optionale interne Beschreibung"
@@ -4125,7 +4134,9 @@
"adjustment_required": "Bitte einen Prozentsatz eingeben.",
"adjustment_too_deep": "Muss kleiner als 100 % sein.",
"ends_after_starts": "Muss nach dem Startdatum liegen.",
- "minimum_quantity_invalid": "Geben Sie eine ganze Zahl ein."
+ "minimum_quantity_invalid": "Geben Sie eine ganze Zahl ein.",
+ "tier_percentage_invalid": "Jede Stufe braucht einen Prozentsatz unter 100.",
+ "tier_quantity_invalid": "Jede Stufe braucht eine eigene Menge über 1."
}
},
"product_type_adds_options_one": "Dieser Typ fügt neuen Produkten {{options}} hinzu.",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 9080ef71e5..58d4b631ec 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -1569,6 +1569,15 @@
"adjustment_magnitude": {
"label": "Percentage"
},
+ "adjustment_tiers": {
+ "add": "Add quantity tier",
+ "empty": "No tiers — the percentage above applies at every quantity.",
+ "help": "From each quantity up, the agreement gives this percentage instead. Each tier is taken off the base price, never off the tier below it.",
+ "label": "Quantity tiers",
+ "percentage": "Percentage",
+ "quantity": "From quantity",
+ "remove": "Remove the tier from {quantity}"
+ },
"description": {
"label": "Description",
"placeholder": "Optional internal description"
@@ -4125,7 +4134,9 @@
"adjustment_required": "Enter a percentage.",
"adjustment_too_deep": "Must be less than 100%.",
"ends_after_starts": "Must be after start date.",
- "minimum_quantity_invalid": "Enter a whole number."
+ "minimum_quantity_invalid": "Enter a whole number.",
+ "tier_percentage_invalid": "Each tier needs a percentage below 100.",
+ "tier_quantity_invalid": "Each tier needs its own quantity above 1."
}
},
"product_type_adds_options_one": "This type adds {{options}} to new products.",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 6dbcbe3fb0..6bde8ff29c 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -1569,6 +1569,15 @@
"adjustment_magnitude": {
"label": "Pourcentage"
},
+ "adjustment_tiers": {
+ "add": "Ajouter un palier",
+ "empty": "Aucun palier — le pourcentage ci-dessus s’applique à toutes les quantités.",
+ "help": "À partir de chaque quantité, l’accord applique ce pourcentage. Chaque palier se calcule sur le prix de base, jamais sur le palier précédent.",
+ "label": "Paliers de quantité",
+ "percentage": "Pourcentage",
+ "quantity": "À partir de",
+ "remove": "Supprimer le palier à partir de {quantity}"
+ },
"description": {
"label": "Description",
"placeholder": "Description interne facultative"
@@ -4125,7 +4134,9 @@
"adjustment_required": "Saisissez un pourcentage.",
"adjustment_too_deep": "Doit être inférieur à 100 %.",
"ends_after_starts": "Doit être postérieur à la date de début.",
- "minimum_quantity_invalid": "Saisissez un nombre entier."
+ "minimum_quantity_invalid": "Saisissez un nombre entier.",
+ "tier_percentage_invalid": "Chaque palier a besoin d’un pourcentage inférieur à 100.",
+ "tier_quantity_invalid": "Chaque palier a besoin de sa propre quantité, supérieure à 1."
}
},
"product_type_adds_options_one": "Ce type ajoute {{options}} aux nouveaux produits.",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 662bac64dc..5fea943751 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -1583,6 +1583,15 @@
"adjustment_magnitude": {
"label": "Procent"
},
+ "adjustment_tiers": {
+ "add": "Dodaj próg ilościowy",
+ "empty": "Brak progów — procent powyżej obowiązuje dla każdej ilości.",
+ "help": "Od danej ilości w górę umowa daje ten procent. Każdy próg liczy się od ceny bazowej, nigdy od progu niższego.",
+ "label": "Progi ilościowe",
+ "percentage": "Procent",
+ "quantity": "Od ilości",
+ "remove": "Usuń próg od {quantity}"
+ },
"description": {
"label": "Opis",
"placeholder": "Opcjonalny opis wewnętrzny"
@@ -4175,7 +4184,9 @@
"adjustment_required": "Podaj wartość procentową.",
"adjustment_too_deep": "Musi być mniejsza niż 100%.",
"ends_after_starts": "Musi być po dacie rozpoczęcia.",
- "minimum_quantity_invalid": "Podaj liczbę całkowitą."
+ "minimum_quantity_invalid": "Podaj liczbę całkowitą.",
+ "tier_percentage_invalid": "Każdy próg potrzebuje procentu poniżej 100.",
+ "tier_quantity_invalid": "Każdy próg potrzebuje własnej ilości większej niż 1."
}
},
"product_type_adds_options_few": "Ten typ dodaje {{options}} do nowych produktów.",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 43d55b0b0b..affc6c1841 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -1564,6 +1564,15 @@
"adjustment_magnitude": {
"label": "百分比"
},
+ "adjustment_tiers": {
+ "add": "添加数量阶梯",
+ "empty": "暂无阶梯——上面的百分比适用于所有数量。",
+ "help": "达到各档数量后,协议改用该百分比。每档都按基础价格计算,而不是在上一档的基础上叠加。",
+ "label": "数量阶梯",
+ "percentage": "百分比",
+ "quantity": "起订量",
+ "remove": "删除 {quantity} 起的阶梯"
+ },
"description": {
"label": "描述",
"placeholder": "可选的内部描述"
@@ -4116,7 +4125,9 @@
"adjustment_required": "请输入百分比。",
"adjustment_too_deep": "必须小于 100%。",
"ends_after_starts": "必须晚于开始日期。",
- "minimum_quantity_invalid": "请输入整数。"
+ "minimum_quantity_invalid": "请输入整数。",
+ "tier_percentage_invalid": "每一档的百分比都需要小于 100。",
+ "tier_quantity_invalid": "每一档都需要各自大于 1 的数量。"
}
},
"product_type_adds_options_one": "此类型会为新商品添加{{options}}。",
diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.ts
index bc7e084666..c98f192b6d 100644
--- a/packages/dashboard/src/schemas/catalog.ts
+++ b/packages/dashboard/src/schemas/catalog.ts
@@ -20,6 +20,18 @@ import {
* (docs/plans/6.0-catalog-agreement-rework.md).
*/
export const CATALOG_PRICING_MODES = ['base', ...PRICING_MODES] as const
+
+/**
+ * One quantity band as the form edits it: strings, so an unusable entry can
+ * be reported rather than silently coerced. Declared here rather than read
+ * off `CatalogFormValues` — the validators below take it as a parameter, and
+ * inferring it from the schema they belong to would make the schema's own
+ * type circular (docs/plans/6.0-volume-pricing.md).
+ */
+export interface AdjustmentTierValue {
+ min_quantity: string
+ percentage: string
+}
export type CatalogPricingMode = (typeof CATALOG_PRICING_MODES)[number]
/** Validation for the catalog create sheet and the agreement editor. */
@@ -50,6 +62,15 @@ export const catalogFormSchema = z
* (docs/plans/6.0-price-list-automatic-pricing.md).
*/
minimum_quantity: z.string().trim().optional(),
+ /**
+ * Quantity bands on the percentage: "5% off, 10% from ten, 20% from
+ * fifty" as one agreement, rather than one catalog per tier. Strings so
+ * an unusable entry can be reported rather than silently coerced
+ * (docs/plans/6.0-volume-pricing.md).
+ */
+ adjustment_tiers: z
+ .array(z.object({ min_quantity: z.string().trim(), percentage: z.string().trim() }))
+ .default([]),
/**
* The catalog-wide quantity terms — the middle of the three levels a
* buyer's rules resolve through. Blank means this agreement is silent,
@@ -128,6 +149,23 @@ export const catalogFormSchema = z
error: () => i18n.t('admin.products.price_lists.validation.adjustment_too_deep'),
},
)
+ // A band at 1 would shadow the percentage itself, and two bands at one
+ // quantity are one intent stated twice — the server refuses both, so the
+ // form says so before the round trip.
+ .refine(
+ (v) => v.pricing_mode !== 'automatic' || adjustmentTiersAreWellFormed(v.adjustment_tiers),
+ {
+ path: ['adjustment_tiers'],
+ error: () => i18n.t('admin.products.price_lists.validation.tier_quantity_invalid'),
+ },
+ )
+ .refine(
+ (v) => v.pricing_mode !== 'automatic' || v.adjustment_tiers.every(tierPercentageIsUsable),
+ {
+ path: ['adjustment_tiers'],
+ error: () => i18n.t('admin.products.price_lists.validation.tier_percentage_invalid'),
+ },
+ )
/**
* A product's quantity terms as typed. Both fields are strings so an
@@ -190,6 +228,7 @@ export const CATALOG_DEFAULTS: CatalogFormValues = {
adjustment_magnitude: '',
adjust_compare_at: false,
minimum_quantity: '',
+ adjustment_tiers: [],
minimum_order_quantity: '',
order_multiple: '',
staged_products: { adds: [], removes: [] },
@@ -264,7 +303,16 @@ function priceListPayload(values: CatalogFormValues, previousMode?: CatalogPrici
// A minimum quantity rides as the list's volume rule; dropping it from the
// list of rules is what clears it, so removing the threshold is a real
// edit rather than a silent no-op.
- const withRule = { ...base, rules: volumeRulePayload(values.minimum_quantity) }
+ const withRule = {
+ ...base,
+ rules: volumeRulePayload(values.minimum_quantity),
+ // The payload is the whole ladder, so a band the merchant deleted is a
+ // band absent from this array rather than one marked for removal.
+ price_adjustment_tiers: adjustmentTiersPayload(
+ values.adjustment_tiers,
+ values.adjustment_direction,
+ ),
+ }
// Switching away from hand-entered prices clears them. An explicit amount
// beats the adjustment by design, so leaving the old rows behind would
@@ -272,6 +320,43 @@ function priceListPayload(values: CatalogFormValues, previousMode?: CatalogPrici
return previousMode === 'fixed' ? { ...withRule, prices: [] } : withRule
}
+/**
+ * Bands as the API takes them: signed percentages, matching the direction
+ * chosen for the list's own figure. A band a merchant enters as "20" under
+ * "decrease" is -20, exactly like the magnitude above it — one control for
+ * direction, so a ladder cannot half-discount and half-mark-up.
+ */
+function adjustmentTiersPayload(
+ tiers: AdjustmentTierValue[],
+ direction: (typeof ADJUSTMENT_DIRECTIONS)[number],
+) {
+ return tiers.flatMap((tier) => {
+ const quantity = parseMinimumQuantity(tier.min_quantity)
+ const magnitude = parsePercentage(tier.percentage)
+ if (quantity === null || quantity < 2 || magnitude === null) return []
+
+ return [
+ {
+ min_quantity: quantity,
+ percentage: String(direction === 'decrease' ? -magnitude : magnitude),
+ },
+ ]
+ })
+}
+
+/** Every band above one unit, and no quantity used twice. */
+function adjustmentTiersAreWellFormed(tiers: AdjustmentTierValue[]): boolean {
+ const quantities = tiers.map((tier) => parseMinimumQuantity(tier.min_quantity))
+ if (quantities.some((quantity) => quantity === null || quantity < 2)) return false
+
+ return new Set(quantities).size === quantities.length
+}
+
+function tierPercentageIsUsable(tier: AdjustmentTierValue): boolean {
+ const magnitude = parsePercentage(tier.percentage)
+ return magnitude !== null && magnitude < 100
+}
+
function volumeRulePayload(minimumQuantity: string | undefined) {
const quantity = parseMinimumQuantity(minimumQuantity)
// A threshold of 1 gates nothing, which is exactly what blank means, so
@@ -287,7 +372,13 @@ function volumeRulePayload(minimumQuantity: string | undefined) {
*/
export function catalogPricingValues(
priceList:
- | Pick<PriceList, 'price_adjustment_percentage' | 'adjust_compare_at' | 'price_rules'>
+ | Pick<
+ PriceList,
+ | 'price_adjustment_percentage'
+ | 'adjust_compare_at'
+ | 'price_rules'
+ | 'price_adjustment_tiers'
+ >
| null
| undefined,
): {
@@ -296,6 +387,7 @@ export function catalogPricingValues(
adjustment_magnitude: string
adjust_compare_at: boolean
minimum_quantity: string
+ adjustment_tiers: AdjustmentTierValue[]
} {
if (!priceList) {
return {
@@ -304,6 +396,7 @@ export function catalogPricingValues(
adjustment_magnitude: '',
adjust_compare_at: false,
minimum_quantity: '',
+ adjustment_tiers: [],
}
}
@@ -317,6 +410,12 @@ export function catalogPricingValues(
adjustment_magnitude,
adjust_compare_at: priceList.adjust_compare_at ?? false,
minimum_quantity: minimumQuantityOf(priceList.price_rules),
+ // Shown as magnitudes, like the list's own figure: the direction select
+ // above them carries the sign for the whole ladder.
+ adjustment_tiers: (priceList.price_adjustment_tiers ?? []).map((tier) => ({
+ min_quantity: String(tier.min_quantity),
+ percentage: String(Math.abs(Number(tier.percentage))),
+ })),
}
}
diff --git a/packages/dashboard/src/schemas/price-list.ts b/packages/dashboard/src/schemas/price-list.ts
index 6b63ec78d1..4116f4d1bb 100644
--- a/packages/dashboard/src/schemas/price-list.ts
+++ b/packages/dashboard/src/schemas/price-list.ts
@@ -27,6 +27,14 @@ export type PricingMode = (typeof PRICING_MODES)[number]
* a merchant thinks "15% off", not "-15".
*/
export const ADJUSTMENT_DIRECTIONS = ['decrease', 'increase'] as const
+
+/**
+ * How many quantity tiers one ladder may hold — bands on a list's percentage
+ * or breaks on a variant's price rows. Mirrors the server's cap, so the
+ * editor stops offering "add" rather than letting a save be refused
+ * (docs/plans/6.0-volume-pricing.md).
+ */
+export const MAXIMUM_QUANTITY_TIERS = 10
export type AdjustmentDirection = (typeof ADJUSTMENT_DIRECTIONS)[number]
/**