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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Make a quantity ladder part of the spreadsheet, not a dialog over it
Damian Legawiecf6522d24f161
diff --git a/packages/dashboard-ui/src/spree/bulk-price-table.tsx b/packages/dashboard-ui/src/spree/bulk-price-table.tsxindex 26bc216bd3..5150186e6b 100644--- a/packages/dashboard-ui/src/spree/bulk-price-table.tsx+++ b/packages/dashboard-ui/src/spree/bulk-price-table.tsx@@ -1,14 +1,20 @@import type { ColumnDef } from '@tanstack/react-table'+import { PlusIcon, XIcon } from 'lucide-react'import { useMemo } from 'react'import { Button } from '../ui/button'-import { DataGrid, editableRowIndex, MoneyCell, ReadOnlyCell } from './data-grid'+import { DataGrid, DecimalCell, editableRowIndex, MoneyCell, ReadOnlyCell } from './data-grid'import { SearchInput } from './search-input'export interface BulkPriceRow {// Unique row id. For header rows use a synthetic key (e.g. `header:<groupId>`);// the table renders headers via `renderSectionHeader` without an editable cell.id: string- kind: 'header' | 'item'+ // `tier` rows are a variant's quantity breaks. They are editable rows like+ // any other, so Tab and the arrow keys flow through them rather than+ // stopping at the variant. The last one is always blank and waiting — a+ // ladder is grown by typing in it, not by asking for a row first+ // (docs/plans/6.0-volume-pricing.md).+ kind: 'header' | 'item' | 'tier'// Header rows: the section title (typically the product name).groupLabel?: string// Item rows.@@ -18,10 +24,11 @@ export interface BulkPriceRow {// user input or the API's canonical decimal. The table passes them through.amount?: string | nullcompareAt?: string | null- // How many quantity breaks sit above this row's price. Renders the tier- // button when the caller opted into the column- // (docs/plans/6.0-volume-pricing.md).- breakCount?: number+ // On a `tier` row: the quantity it applies from, as typed.+ minQuantity?: string+ // The trailing blank row a variant always carries. It commits to a real+ // break the moment it holds a quantity and a price.+ blank?: boolean}export interface BulkPriceTableLabels {@@ -59,15 +66,14 @@ export interface BulkPriceTableLabels {priceAriaTemplate?: string/** Aria-label template for the compare-at input. `{label}` is replaced with the variant label. */compareAtAriaTemplate?: string- /** Column header over the quantity-break buttons. Omit to hide the column. */- tiers?: string- /**- * Labels a row's tier button. Called with the break count so the caller's- * own translator picks the plural form — a pre-substituted template cannot.- */- tiersWithCount?: (count: number) => string- /** Label on a row's tier button when the row carries no breaks yet. */- tiersEmpty?: string+ /** Column header over the quantity column. Omit to hide the column. */+ tierFrom?: string+ /** The "add a break" row's label. */+ tierAdd?: string+ /** Accessible name for a tier row's remove button. */+ tierRemove?: string+ /** Accessible name for a tier row's quantity input. */+ tierQuantity?: string}export interface BulkPriceTableProps {@@ -80,12 +86,12 @@ export interface BulkPriceTableProps {labels: BulkPriceTableLabels/** Called when the user commits a value to a cell. The id is the row id. */onChange: (rowId: string, field: 'amount' | 'compareAt', value: string | null) => void- /**- * Opens the row's quantity ladder. Supplying it (with `labels.tiers`) adds- * the tier column; the panel itself is the caller's — the table only says- * which row was asked for.- */- onOpenTiers?: (rowId: string) => void+ /** Edits a tier row's quantity. */+ onTierQuantityChange?: (rowId: string, value: string) => void+ /** Appends a break to the variant the `tier-add` row belongs to. */+ onTierAdd?: (rowId: string) => void+ /** Removes a tier row. */+ onTierRemove?: (rowId: string) => void// Optional state for the toolbar + pagination footer. Omitting all of these// hides the toolbar/pagination entirely (use for in-memory single-page lists).@@ -110,7 +116,9 @@ export function BulkPriceTable({decimal,labels,onChange,- onOpenTiers,+ onTierQuantityChange,+ onTierAdd,+ onTierRemove,search,onSearchChange,page,@@ -125,6 +133,11 @@ export function BulkPriceTable({header: labels.variant,cell: ({ row }) => {const r = row.original++ // A break belongs to the variant above it, so it says nothing here+ // — the indent and the quantity column carry the relationship.+ if (r.kind === 'tier') return null+if (r.kind !== 'item') return nullreturn (<ReadOnlyCell className="text-muted-foreground">@@ -146,14 +159,61 @@ export function BulkPriceTable({)},},+ // The quantity a row's price applies from. A variant's own price is the+ // ladder's first rung and always reads 1 — which is why this is a+ // column rather than a panel: every price in the sheet has a quantity,+ // and only the breaks have one worth typing+ // (docs/plans/6.0-volume-pricing.md).+ ...(labels.tierFrom+ ? [+ {+ id: 'min_quantity',+ header: () => <span className="block text-right">{labels.tierFrom}</span>,+ cell: ({ row, table }) => {+ const r = row.original+ if (r.kind === 'item') {+ // justify-end, not text-right: ReadOnlyCell is a flex row,+ // so the quantity would otherwise sit left of every editable+ // quantity below it.+ return (+ <ReadOnlyCell className="justify-end text-muted-foreground tabular-nums">+ 1+ </ReadOnlyCell>+ )+ }++ if (r.kind !== 'tier') return null++ const coords = { row: editableRowIndex(table.getRowModel().rows, r.id), col: 2 }+ return (+ // Decimal rather than number: a rung being typed has no+ // quantity yet, and a numeric cell would show that as 0 —+ // a value nobody chose and the server refuses.+ <DecimalCell+ coords={coords}+ value={r.minQuantity || null}+ onChange={(next) => onTierQuantityChange?.(r.id, next ?? '')}+ decimal={decimal}+ ariaLabel={labels.tierQuantity ?? labels.tierFrom ?? ''}+ />+ )+ },+ } satisfies ColumnDef<BulkPriceRow>,+ ]+ : []),{id: 'amount',header: () => <span className="block text-right">{labels.price}</span>,cell: ({ row, table }) => {const r = row.original- if (r.kind !== 'item') return null- const coords = { row: editableRowIndex(table.getRowModel().rows, row.id), col: 2 }- const label = r.variantLabel ?? labels.variantDefault+ // A break's unit price sits in the price column, under the price it+ // replaces from that quantity up.+ if (r.kind !== 'item' && r.kind !== 'tier') return null+ const coords = { row: editableRowIndex(table.getRowModel().rows, row.id), col: 3 }+ const label =+ r.kind === 'tier'+ ? `${labels.tierFrom ?? ''} ${r.minQuantity ?? ''}`.trim()+ : (r.variantLabel ?? labels.variantDefault)return (<MoneyCellcoords={coords}@@ -171,8 +231,10 @@ export function BulkPriceTable({header: () => <span className="block text-right">{labels.compareAt}</span>,cell: ({ row, table }) => {const r = row.original+ // Variants only: a break is a contracted unit price, never a claim+ // about a former one.if (r.kind !== 'item') return null- const coords = { row: editableRowIndex(table.getRowModel().rows, row.id), col: 3 }+ const coords = { row: editableRowIndex(table.getRowModel().rows, row.id), col: 4 }const label = r.variantLabel ?? labels.variantDefaultreturn (<MoneyCell@@ -186,36 +248,49 @@ export function BulkPriceTable({)},},- ...(onOpenTiers && labels.tiers+ // A break removes itself where it sits; the trailing blank row offers+ // the plus that starts another. Both fill the cell, so the whole square+ // is the target rather than a small glyph inside it.+ ...(onTierRemove? [{- id: 'tiers',- header: () => <span className="block text-right">{labels.tiers}</span>,+ id: 'tier_actions',+ header: () => <span className="sr-only">{labels.tierRemove}</span>,cell: ({ row }) => {const r = row.original- if (r.kind !== 'item') return null- const count = r.breakCount ?? 0- return (- <div className="flex justify-end pr-1">+ if (r.kind !== 'tier') return null++ if (r.blank) {+ return (<Buttontype="button"- size="sm"- variant={count > 0 ? 'outline' : 'ghost'}- className="h-7 px-2 text-xs"- onClick={() => onOpenTiers(r.id)}+ variant="ghost"+ aria-label={labels.tierAdd}+ className="size-full min-h-9 rounded-none text-muted-foreground"+ onClick={() => onTierAdd?.(r.id)}>- {count > 0- ? (labels.tiersWithCount?.(count) ?? String(count))- : (labels.tiersEmpty ?? '+')}+ <PlusIcon className="size-4" /></Button>- </div>+ )+ }++ return (+ <Button+ type="button"+ variant="ghost"+ aria-label={labels.tierRemove}+ className="size-full min-h-9 rounded-none text-muted-foreground"+ onClick={() => onTierRemove(r.id)}+ >+ <XIcon className="size-4" />+ </Button>)},} satisfies ColumnDef<BulkPriceRow>,]: []),],- [symbol, decimal, onChange, onOpenTiers, labels],+ [symbol, decimal, onChange, onTierQuantityChange, onTierAdd, onTierRemove, labels],)const showToolbar =diff --git a/packages/dashboard-ui/src/spree/data-grid/helpers.ts b/packages/dashboard-ui/src/spree/data-grid/helpers.tsindex 99ee7d2717..f3a9abf7d9 100644--- a/packages/dashboard-ui/src/spree/data-grid/helpers.ts+++ b/packages/dashboard-ui/src/spree/data-grid/helpers.ts@@ -3,14 +3,18 @@* the cell at that position has stable grid coords that exclude section* headers. Used by every spreadsheet that mixes a `renderSectionHeader`* with `<NumberCell>` / `<MoneyCell>` etc.+ *+ * Every kind but `header` counts, so a sheet that indents child rows under a+ * parent — a variant's quantity breaks, say — keeps Tab and the arrow keys+ * flowing through them in the order they are read.*/-export function editableRowIndex<T extends { kind: 'header' | 'item'; id: string }>(+export function editableRowIndex<T extends { kind: string; id: string }>(rows: ReadonlyArray<{ id: string; original: T }>,rowId: string,): number {let i = 0for (const row of rows) {- if (row.original.kind !== 'item') continue+ if (row.original.kind === 'header') continueif (row.id === rowId) return ii++}diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsxindex 453c8e5749..d041e86c08 100644--- a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx+++ b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx@@ -7,12 +7,11 @@ import {} from '@spree/dashboard-core'import { type BulkPriceRow, BulkPriceTable, toastManager } from '@spree/dashboard-ui'import { useQuery } from '@tanstack/react-query'-import { useCallback, useDeferredValue, useEffect, useMemo, useState } from 'react'+import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { useCurrencyLocale } from '../../../hooks/use-currency-locale'import { useBulkUpsertPrices } from '../../../hooks/use-prices'import { MAXIMUM_QUANTITY_TIERS } from '../../../schemas/price-list'-import { VariantTierDialog } from './variant-tier-dialog'const PAGE_SIZE = 50// The API caps a page at 100 rows, so the break sweep asks for exactly that@@ -41,17 +40,27 @@ interface CellEdit {// page 1: the save loop resolves variant_id via `baselineRows`, which// only holds the current page's server result.variantId: string+ // Present on a quantity break, absent on the variant's own price — which+ // is the ladder's bottom rung and needs no quantity on the wire.+ minQuantity?: stringamount: string | nullcompareAt: string | null}-// BulkPriceRow extended with the server-side variantId so save can ship-// the canonical (variant_id, currency, price_list_id) upsert triple.+// BulkPriceRow extended with the server-side variantId so save can ship the+// canonical (variant_id, currency, price_list_id, min_quantity) upsert key.interface BaselineRow extends BulkPriceRow {priceId?: stringvariantId?: string- /** Shown in the tier dialog's title, so the merchant knows which row. */- tierLabel?: string+}++// A break the merchant added that has no stored row yet. Carries its own+// client id so the grid can key it before the server assigns one.+interface DraftRung {+ id: string+ variantId: string+ minQuantity: string+ amount: string | null}type FilterShape = Record<string, string | number | boolean | string[] | null | undefined>@@ -226,14 +235,25 @@ export function BulkPriceEditor({enabled: !!priceListId && pageVariantIds.length > 0,})- const breakCounts = useMemo(() => {- const counts = new Map<string, number>()+ // Grouped by variant and ordered by quantity, so a ladder renders in the+ // order it is read (docs/plans/6.0-volume-pricing.md).+ const breaksByVariant = useMemo(() => {+ const grouped = new Map<string, PriceListRowFromServer[]>()for (const row of breakRows ?? []) {- counts.set(row.variant_id, (counts.get(row.variant_id) ?? 0) + 1)+ const rungs = grouped.get(row.variant_id) ?? []+ rungs.push(row)+ grouped.set(row.variant_id, rungs)}- return counts+ for (const rungs of grouped.values()) rungs.sort((a, b) => a.min_quantity - b.min_quantity)+ return grouped}, [breakRows])+ // Rungs added in this session that have no stored row yet. They live beside+ // the fetched ones until Save writes them.+ const [draftRungs, setDraftRungs] = useState<DraftRung[]>([])+ // Monotonic, so two rungs added in the same millisecond cannot collide.+ const nextDraftId = useRef(0)+const baselineRows = useMemo<BaselineRow[]>(() => {if (!data) return []const out: BaselineRow[] = []@@ -248,26 +268,59 @@ export function BulkPriceEditor({})lastProductId = variant.product_id}+ const rungs = breaksByVariant.get(row.variant_id) ?? []+out.push({id: row.id,kind: 'item',priceId: row.id,variantId: row.variant_id,variantLabel: variant.options_text ?? null,- tierLabel: [variant.product_name, variant.options_text].filter(Boolean).join(' — '),sku: variant.sku ?? null,amount: row.amount,compareAt: row.compare_at_amount,- breakCount: breakCounts.get(row.variant_id) ?? 0,+ })++ // The rungs are ordinary rows of this sheet. A variant's own price is+ // the ladder's first rung — which is why quantity is a column and these+ // are simply the rows below it (docs/plans/6.0-volume-pricing.md).+ for (const rung of rungs) {+ out.push({+ id: rung.id,+ kind: 'tier',+ priceId: rung.id,+ variantId: row.variant_id,+ minQuantity: String(rung.min_quantity),+ amount: rung.amount,+ })+ }++ for (const draft of draftRungs.filter((entry) => entry.variantId === row.variant_id)) {+ out.push({+ id: draft.id,+ kind: 'tier',+ variantId: row.variant_id,+ minQuantity: draft.minQuantity,+ amount: draft.amount,+ })+ }++ // Every variant ends with an empty rung waiting to be typed into, so+ // growing a ladder is filling in the next line rather than asking for+ // one first (docs/plans/6.0-volume-pricing.md).+ out.push({+ id: `blank:${row.variant_id}`,+ kind: 'tier',+ blank: true,+ variantId: row.variant_id,+ minQuantity: '',+ amount: null,})}return out- }, [data, breakCounts])+ }, [data, breaksByVariant, draftRungs])const [edits, setEdits] = useState<Map<string, CellEdit>>(() => new Map())- // Which row's ladder is open. Held by row id rather than variant id so the- // dialog can name the product the merchant clicked.- const [tierRowId, setTierRowId] = useState<string | null>(null)// Reset page + edits whenever the upstream filters change — a different// list, currency, or product scope is a different working set; carrying@@ -277,25 +330,47 @@ export function BulkPriceEditor({useEffect(() => {setPage(1)setEdits(new Map())+ setDraftRungs([])}, [priceListId, currency, filterKey])const rows = useMemo<BulkPriceRow[]>(() =>baselineRows.map((r) => {- if (r.kind !== 'item' || !r.priceId) return r- const edit = edits.get(r.priceId)+ if (r.kind === 'header') return r+ const edit = edits.get(r.priceId ?? r.id)if (!edit) return r- return { ...r, amount: edit.amount, compareAt: edit.compareAt }+ // A tier row edits the same two things a variant row does, minus the+ // compare-at it has no column for.+ return r.kind === 'tier'+ ? { ...r, amount: edit.amount }+ : { ...r, amount: edit.amount, compareAt: edit.compareAt }}),[baselineRows, edits],)+ // Typing in a variant's trailing blank row turns it into a real draft rung,+ // and the row builder immediately puts a fresh blank one below it — so the+ // ladder always has somewhere to grow (docs/plans/6.0-volume-pricing.md).+ //+ // @returns the draft's id, so the caller can record the edit against it+ const promoteBlankRow = useCallback((rowId: string): string | null => {+ if (!rowId.startsWith('blank:')) return null++ const variantId = rowId.slice('blank:'.length)+ const draftId = `draft:${variantId}:${nextDraftId.current++}`+ setDraftRungs((prev) => [...prev, { id: draftId, variantId, minQuantity: '', amount: null }])+ return draftId+ }, [])+const handleChange = useCallback((rowId: string, field: 'amount' | 'compareAt', next: string | null) => {+ // Typing a price into the trailing blank row is what creates the rung.+ const promoted = promoteBlankRow(rowId)+ const targetId = promoted ?? rowId+setEdits((prev) => {- const baseline = baselineRows.find(- (r): r is BaselineRow & { kind: 'item' } => r.kind === 'item' && r.priceId === rowId,- )+ // A draft rung has no stored row, so it is found by its own id.+ const baseline = baselineRows.find((r) => (r.priceId ?? r.id) === rowId)if (!baseline?.variantId) return prev// Baseline is the API's canonical decimal (`12.50`); the cell// ships the user's raw locale-formatted input (`12,50`). Seed the@@ -306,23 +381,96 @@ export function BulkPriceEditor({const displayBaseCompare = baseline.compareAt? baseline.compareAt.replace('.', decimal): null- const current = prev.get(rowId) ?? {+ const current = prev.get(targetId) ?? {variantId: baseline.variantId,+ minQuantity: baseline.minQuantity,amount: displayBaseAmount,compareAt: displayBaseCompare,}- const merged = { ...current, [field]: next }+ // Re-read the quantity on every merge: a draft rung's quantity is+ // typed after its price cell may already hold an edit, and the save+ // payload needs whatever it says now.+ const merged = { ...current, minQuantity: baseline.minQuantity, [field]: next }if (merged.amount === displayBaseAmount && merged.compareAt === displayBaseCompare) {const out = new Map(prev)- out.delete(rowId)+ out.delete(targetId)return out}const out = new Map(prev)- out.set(rowId, merged)+ out.set(targetId, merged)return out})},- [baselineRows, decimal],+ [baselineRows, decimal, promoteBlankRow],+ )++ // The plus on the blank row does the same thing a keystroke does — it is+ // there for discoverability, not because a row has to be asked for.+ const addTier = useCallback(+ (rowId: string) => {+ promoteBlankRow(rowId)+ },+ [promoteBlankRow],+ )++ const changeTierQuantity = useCallback(+ (rowId: string, value: string) => {+ const promoted = promoteBlankRow(rowId)+ const targetId = promoted ?? rowId++ setDraftRungs((prev) =>+ prev.map((rung) => (rung.id === targetId ? { ...rung, minQuantity: value } : rung)),+ )+ setEdits((prev) => {+ const row = baselineRows.find((entry) => (entry.priceId ?? entry.id) === rowId)+ if (!row?.variantId) return prev++ const existing = prev.get(targetId)+ const out = new Map(prev)+ // Moving a stored rung's quantity is an edit in its own right, and a+ // draft's quantity is what makes it addressable at all — so either+ // way the row joins the sheet's unsaved changes.+ out.set(targetId, {+ variantId: row.variantId,+ minQuantity: value,+ amount: existing?.amount ?? row.amount ?? null,+ compareAt: existing?.compareAt ?? null,+ })+ return out+ })+ },+ [baselineRows, promoteBlankRow],+ )++ const removeTier = useCallback(+ (rowId: string) => {+ // A draft rung has nothing stored to remove; a saved one is cleared by+ // sending a blank amount, which the bulk endpoint reads as "delete this".+ if (rowId.startsWith('draft:')) {+ setDraftRungs((prev) => prev.filter((rung) => rung.id !== rowId))+ setEdits((prev) => {+ const out = new Map(prev)+ out.delete(rowId)+ return out+ })+ return+ }++ setEdits((prev) => {+ const row = baselineRows.find((entry) => entry.priceId === rowId)+ if (!row?.variantId) return prev++ const out = new Map(prev)+ out.set(rowId, {+ variantId: row.variantId,+ minQuantity: row.minQuantity,+ amount: null,+ compareAt: null,+ })+ return out+ })+ },+ [baselineRows],)const save = useCallback(async (): Promise<boolean> => {@@ -331,7 +479,12 @@ export function BulkPriceEditor({// the mutation is in-flight, so concurrent edits the user makes// during the round-trip must survive the post-save clear. After a// successful upsert we drop only the keys that were in the snapshot.- const savedKeys = Array.from(edits.keys())+ // A rung the merchant started and left empty is not a price — it carries+ // neither a quantity nor an amount, and the server would refuse it.+ const savedKeys = Array.from(edits.entries())+ .filter(([id, edit]) => !(id.startsWith('draft:') && !edit.minQuantity && !edit.amount))+ .map(([id]) => id)+ if (savedKeys.length === 0) return false// Ship the unique-key triple `(variant_id, currency, price_list_id)`// — that's what the server upserts on. `id` is not used by the bulk// endpoint; we already have the lookup columns on screen so there's@@ -351,8 +504,12 @@ export function BulkPriceEditor({variant_id: edit.variantId,currency,...(priceListId ? { price_list_id: priceListId } : {}),+ // Absent on a variant's own price, which is the ladder's bottom rung.+ ...(edit.minQuantity ? { min_quantity: Number(edit.minQuantity) } : {}),amount: toCanonical(edit.amount),- compare_at_amount: toCanonical(edit.compareAt),+ // A break carries no compare-at; sending one would claim a former+ // price for a contracted figure.+ ...(edit.minQuantity ? {} : { compare_at_amount: toCanonical(edit.compareAt) }),}})try {@@ -368,6 +525,8 @@ export function BulkPriceEditor({for (const key of savedKeys) out.delete(key)return out})+ // The drafts now exist as stored rows, and the refetch renders them.+ setDraftRungs((prev) => prev.filter((rung) => !savedKeys.includes(rung.id)))return true} catch (err) {const message =@@ -406,76 +565,52 @@ export function BulkPriceEditor({{ search },)- const tierRow = tierRowId- ? baselineRows.find((row) => row.kind === 'item' && row.id === tierRowId)- : undefined-return (- <>- <BulkPriceTable- rows={rows}- symbol={symbol}- decimal={decimal}- onChange={handleChange}- // Ladders live on a price list; base prices carry no breaks in v1, so- // the column simply does not appear there.- onOpenTiers={priceListId ? setTierRowId : undefined}- search={search}- onSearchChange={(next) => {- setSearch(next)- setPage(1)- }}- page={page}- totalPages={totalPages}- onPageChange={setPage}- isLoading={isLoading}- labels={{- variant: t('admin.pages.products.price_lists.edit_prices.columns.variant'),- sku: t('admin.pages.products.price_lists.edit_prices.columns.sku'),- price: t('admin.pages.products.price_lists.edit_prices.columns.price'),- compareAt: t('admin.pages.products.price_lists.edit_prices.columns.compare_at_price'),- variantDefault: t('admin.pages.products.price_lists.edit_prices.variant_default'),- searchPlaceholder: t('admin.pages.products.price_lists.edit_prices.search_placeholder'),- countSummary,- loading: t('admin.common.loading'),- pageOf: t('admin.common.page_of', { page: '{page}', total: '{total}' }),- prev: t('admin.common.prev'),- next: t('admin.common.next'),- emptyMessage,- emptySearchMessage,- gridAriaLabel: t('admin.pages.products.price_lists.edit_prices.grid_aria'),- priceAriaTemplate: t('admin.pages.products.price_lists.edit_prices.price_aria', {- label: '{label}',- }),- compareAtAriaTemplate: t('admin.pages.products.price_lists.edit_prices.compare_at_aria', {- label: '{label}',- }),- tiers: priceListId- ? t('admin.pages.products.price_lists.edit_prices.columns.tiers')- : undefined,- tiersWithCount: (count: number) =>- t('admin.pages.products.price_lists.tiers.count_badge', { count }),- tiersEmpty: t('admin.pages.products.price_lists.tiers.add_short'),- }}- />-- {priceListId && tierRow?.variantId && (- <VariantTierDialog- open- onOpenChange={(next) => {- if (!next) setTierRowId(null)- }}- variantId={tierRow.variantId}- variantLabel={- tierRow.tierLabel || t('admin.pages.products.price_lists.edit_prices.variant_default')- }- priceListId={priceListId}- currency={currency}- decimal={decimal}- marketLocale={marketLocale}- symbol={symbol}- />- )}- </>+ <BulkPriceTable+ rows={rows}+ symbol={symbol}+ decimal={decimal}+ onChange={handleChange}+ // Ladders live on a price list; base prices carry no breaks in v1, so+ // neither the quantity column nor the rung rows appear there.+ onTierQuantityChange={priceListId ? changeTierQuantity : undefined}+ onTierAdd={priceListId ? addTier : undefined}+ onTierRemove={priceListId ? removeTier : undefined}+ search={search}+ onSearchChange={(next) => {+ setSearch(next)+ setPage(1)+ }}+ page={page}+ totalPages={totalPages}+ onPageChange={setPage}+ isLoading={isLoading}+ labels={{+ variant: t('admin.pages.products.price_lists.edit_prices.columns.variant'),+ sku: t('admin.pages.products.price_lists.edit_prices.columns.sku'),+ price: t('admin.pages.products.price_lists.edit_prices.columns.price'),+ compareAt: t('admin.pages.products.price_lists.edit_prices.columns.compare_at_price'),+ variantDefault: t('admin.pages.products.price_lists.edit_prices.variant_default'),+ searchPlaceholder: t('admin.pages.products.price_lists.edit_prices.search_placeholder'),+ countSummary,+ loading: t('admin.common.loading'),+ pageOf: t('admin.common.page_of', { page: '{page}', total: '{total}' }),+ prev: t('admin.common.prev'),+ next: t('admin.common.next'),+ emptyMessage,+ emptySearchMessage,+ gridAriaLabel: t('admin.pages.products.price_lists.edit_prices.grid_aria'),+ priceAriaTemplate: t('admin.pages.products.price_lists.edit_prices.price_aria', {+ label: '{label}',+ }),+ compareAtAriaTemplate: t('admin.pages.products.price_lists.edit_prices.compare_at_aria', {+ label: '{label}',+ }),+ tierFrom: priceListId ? t('admin.pages.products.price_lists.tiers.from') : undefined,+ tierAdd: t('admin.pages.products.price_lists.tiers.add'),+ tierRemove: t('admin.pages.products.price_lists.tiers.remove_short'),+ tierQuantity: t('admin.pages.products.price_lists.tiers.quantity'),+ }}+ />)}diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsxdeleted file mode 100644index 0ba6373c74..0000000000--- a/packages/dashboard/src/components/spree/bulk-price-editor/variant-tier-dialog.tsx+++ /dev/null@@ -1,249 +0,0 @@-import type { PriceBulkUpsertRow } from '@spree/admin-sdk'-import { adminClient, normalizeMoneyInput, useResourceKey } from '@spree/dashboard-core'-import {- Button,- Dialog,- DialogBody,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,- QuantityTierEditor,- type QuantityTierRow,- toastManager,-} from '@spree/dashboard-ui'-import { useQuery, useQueryClient } from '@tanstack/react-query'-import { useEffect, useId, useMemo, useRef, useState } from 'react'-import { useTranslation } from 'react-i18next'-import { useBulkUpsertPrices } from '../../../hooks/use-prices'-import { MAXIMUM_QUANTITY_TIERS } from '../../../schemas/price-list'--interface StoredRung {- id: string- min_quantity: number- amount: string | null-}--interface DraftRung extends QuantityTierRow {- /** The stored row this rung came from, absent for one the merchant added. */- priceId?: string-}--export interface VariantTierDialogProps {- open: boolean- onOpenChange: (next: boolean) => void- /** The variant whose ladder this is, as a prefixed id. */- variantId: string- /** Shown in the title so the merchant knows which row they opened. */- variantLabel: string- priceListId: string- currency: string- /** Decimal separator of the currency's market locale, for display. */- decimal: string- /** The locale amounts are normalized back through on save. */- marketLocale: string- symbol: string-}--/**- * One variant's quantity ladder on one price list: the rungs it is charged at- * as an order grows (docs/plans/6.0-volume-pricing.md).- *- * Opened from the price spreadsheet's tier column, and saved on its own- * rather than with the grid — a ladder is a shape, not a cell, and half of- * one is not a state worth persisting.- */-export function VariantTierDialog({- open,- onOpenChange,- variantId,- variantLabel,- priceListId,- currency,- decimal,- marketLocale,- symbol,-}: VariantTierDialogProps) {- const { t } = useTranslation()- const queryClient = useQueryClient()- const rowIdPrefix = useId()- const { mutateAsync: bulkUpsertAsync, isPending: isSaving } = useBulkUpsertPrices()- const [draft, setDraft] = useState<DraftRung[]>([])- const [nextLocalId, setNextLocalId] = useState(0)-- const queryKey = useResourceKey('prices', { ladder: variantId, priceListId, currency })- const { data, isLoading } = useQuery({- queryKey,- queryFn: () =>- adminClient.prices.list({- variant_id_eq: variantId,- price_list_id_eq: priceListId,- currency_eq: currency,- sort: 'min_quantity',- limit: MAXIMUM_QUANTITY_TIERS + 1,- } as never),- enabled: open,- })-- const stored = useMemo<StoredRung[]>(() => (data?.data ?? []) as unknown as StoredRung[], [data])-- // Seeded once per opening, not on every change to `stored`: TanStack- // refetches on window focus, and re-seeding from that would discard a- // half-typed ladder the moment the merchant tabbed away and back. Closing- // and reopening is what re-reads the server.- const seededFor = useRef<string | null>(null)- useEffect(() => {- if (!open) {- seededFor.current = null- return- }- if (isLoading || seededFor.current === variantId) return-- seededFor.current = variantId- setDraft(- stored.map((rung) => ({- id: `${rowIdPrefix}-stored-${rung.id}`,- priceId: rung.id,- minQuantity: String(rung.min_quantity),- value: rung.amount ? rung.amount.replace('.', decimal) : '',- // The bottom rung is the list's ordinary price for this variant. It- // is edited in the grid behind this dialog; here it is only context- // for the rungs above it.- locked: rung.min_quantity === 1,- })),- )- }, [open, isLoading, stored, decimal, rowIdPrefix, variantId])-- const toCanonical = (value: string) => {- const normalized = normalizeMoneyInput(value, marketLocale || 'en')- return normalized === '' ? null : normalized- }-- const invalidRung = draft.find((rung) => {- if (rung.locked) return false- const quantity = Number(rung.minQuantity)- return !Number.isInteger(quantity) || quantity < 2 || toCanonical(rung.value) === null- })- // Compared as numbers: "10" and "010" address the same rung, and letting- // both through means the batch silently keeps one and drops the other.- const duplicateQuantity =- new Set(draft.map((rung) => Number(rung.minQuantity))).size !== draft.length-- async function handleSave() {- const upserts: PriceBulkUpsertRow[] = draft- .filter((rung) => !rung.locked)- .map((rung) => ({- variant_id: variantId,- currency,- price_list_id: priceListId,- min_quantity: Number(rung.minQuantity),- amount: toCanonical(rung.value),- }))-- // A rung is identified by its quantity, not by the row it came from:- // moving a break from 24 to 30 writes a new row, so keying the removals on- // the row id would leave the 24 behind and charge it to orders of 24-29- // (docs/plans/6.0-volume-pricing.md).- const keptQuantities = new Set(upserts.map((rung) => rung.min_quantity))-- // Removals ride in the same batch as a blank amount, which is what the- // bulk endpoint reads as "clear this price". One request rather than two:- // the server then sees the whole ladder at once, so it neither refuses a- // rewrite for rungs it is about to drop nor leaves the ladder half erased- // when a write is refused.- const removals: PriceBulkUpsertRow[] = stored- .filter((rung) => rung.min_quantity > 1 && !keptQuantities.has(rung.min_quantity))- .map((rung) => ({- variant_id: variantId,- currency,- price_list_id: priceListId,- min_quantity: rung.min_quantity,- amount: null,- }))-- try {- await bulkUpsertAsync({ prices: [...upserts, ...removals] })-- await queryClient.invalidateQueries({ queryKey: ['prices'] })- toastManager.add({- type: 'success',- title: t('admin.pages.products.price_lists.tiers.save_success', { count: upserts.length }),- })- onOpenChange(false)- } catch (error) {- toastManager.add({- type: 'error',- title:- error instanceof Error- ? error.message- : t('admin.pages.products.price_lists.tiers.save_failed'),- })- }- }-- const tierCount = draft.filter((rung) => !rung.locked).length-- return (- <Dialog open={open} onOpenChange={onOpenChange} modal>- <DialogContent className="sm:max-w-lg">- <DialogHeader>- <DialogTitle>- {t('admin.pages.products.price_lists.tiers.title', { variant: variantLabel })}- </DialogTitle>- </DialogHeader>- <DialogBody>- {isLoading ? (- <p className="text-sm text-muted-foreground">{t('admin.common.loading')}</p>- ) : (- <QuantityTierEditor- rows={draft}- labels={{- quantity: t('admin.pages.products.price_lists.tiers.quantity'),- value: t('admin.pages.products.price_lists.tiers.unit_price'),- add: t('admin.pages.products.price_lists.tiers.add'),- remove: t('admin.pages.products.price_lists.tiers.remove'),- empty: t('admin.pages.products.price_lists.tiers.empty'),- hint: t('admin.pages.products.price_lists.tiers.help'),- }}- valueAddon={symbol}- canAdd={tierCount < MAXIMUM_QUANTITY_TIERS}- disabled={isSaving}- error={- duplicateQuantity- ? t('admin.pages.products.price_lists.tiers.duplicate_quantity')- : invalidRung- ? t('admin.pages.products.price_lists.tiers.invalid_rung')- : undefined- }- onChange={(id, field, next) =>- setDraft((prev) =>- prev.map((rung) => (rung.id === id ? { ...rung, [field]: next } : rung)),- )- }- onAdd={() => {- setDraft((prev) => [- ...prev,- { id: `${rowIdPrefix}-new-${nextLocalId}`, minQuantity: '', value: '' },- ])- setNextLocalId((previous) => previous + 1)- }}- onRemove={(id) => setDraft((prev) => prev.filter((rung) => rung.id !== id))}- />- )}- </DialogBody>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>- {t('admin.common.cancel')}- </Button>- <Button- type="button"- onClick={handleSave}- disabled={isSaving || isLoading || !!invalidRung || duplicateQuantity}- >- {t('admin.common.save')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- )-}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 1f01c3462f..06064dbfff 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -3349,7 +3349,6 @@"price": "سعر","product": "منتج","sku": "SKU",- "tiers": "المستويات","variant": "البديل"},"compare_at_aria": "Compare-at price لـ {{label}}",@@ -3427,20 +3426,9 @@"subtitle": "تسعير مستهدف لمجموعات العملاء أو المناطق أو شرائح الحجم.","tiers": {"add": "إضافة مستوى كمية",- "add_short": "إضافة",- "count_badge_one": "مستوى {{count}}",- "count_badge_other": "{{count}} مستويات",- "duplicate_quantity": "لا يمكن أن يبدأ مستويان من الكمية نفسها.",- "empty": "لا توجد مستويات — يُحتسب هذا المتغير بسعر واحد مهما كان حجم الطلب.",- "help": "من كل كمية فصاعدًا يُحتسب السطر بسعر الوحدة هذا. المتغير الذي له مستويات يُسعَّر بها وحدها — ولا تنطبق عليه نسبة القائمة.",- "invalid_rung": "كل مستوى يحتاج كمية أكبر من 1 وسعر وحدة.",+ "from": "من الكمية","quantity": "من الكمية",- "remove": "إزالة المستوى من {quantity}",- "save_failed": "تعذّر حفظ مستويات الكمية.",- "save_success_one": "تم حفظ مستوى كمية واحد.",- "save_success_other": "تم حفظ {{count}} مستويات كمية.",- "title": "مستويات الكمية — {{variant}}",- "unit_price": "سعر الوحدة"+ "remove_short": "إزالة مستوى الكمية هذا"},"title": "Price Lists","unschedule": "إلغاء الجدول الزمني",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 4d7f014053..dc50845c86 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -3332,7 +3332,6 @@"price": "Preis","product": "Produkt","sku": "SKU",- "tiers": "Staffeln","variant": "Variante"},"compare_at_aria": "Vergleichspreis für {{label}}",@@ -3410,20 +3409,9 @@"subtitle": "Gezielte Preisgestaltung für Kundengruppen, Regionen oder Mengenstaffeln.","tiers": {"add": "Mengenstaffel hinzufügen",- "add_short": "Hinzufügen",- "count_badge_one": "{{count}} Staffel",- "count_badge_other": "{{count}} Staffeln",- "duplicate_quantity": "Zwei Staffeln können nicht bei derselben Menge beginnen.",- "empty": "Keine Staffeln — diese Variante kostet unabhängig von der Bestellmenge dasselbe.",- "help": "Ab der jeweiligen Menge gilt dieser Stückpreis. Eine Variante mit Staffeln wird ausschließlich danach berechnet — der Prozentsatz der Liste gilt für sie nicht.",- "invalid_rung": "Jede Staffel braucht eine Menge über 1 und einen Stückpreis.",+ "from": "Ab Menge","quantity": "Ab Menge",- "remove": "Staffel ab {quantity} entfernen",- "save_failed": "Die Mengenstaffeln konnten nicht gespeichert werden.",- "save_success_one": "{{count}} Mengenstaffel gespeichert.",- "save_success_other": "{{count}} Mengenstaffeln gespeichert.",- "title": "Mengenstaffeln — {{variant}}",- "unit_price": "Stückpreis"+ "remove_short": "Diese Mengenstaffel entfernen"},"title": "Preislisten","unschedule": "Planung aufheben",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 90da211515..917f524b8d 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -3332,7 +3332,6 @@"price": "Price","product": "Product","sku": "SKU",- "tiers": "Tiers","variant": "Variant"},"compare_at_aria": "Compare-at price for {{label}}",@@ -3410,20 +3409,9 @@"subtitle": "Targeted pricing for customer groups, regions, or volume tiers.","tiers": {"add": "Add quantity break",- "add_short": "Add",- "count_badge_one": "{{count}} tier",- "count_badge_other": "{{count}} tiers",- "duplicate_quantity": "Two breaks cannot start at the same quantity.",- "empty": "No breaks — this variant is charged one price whatever the order size.",- "help": "From each quantity up, a line is charged this unit price. A variant with breaks is priced by them alone — the list’s percentage does not apply to it.",- "invalid_rung": "Each break needs a quantity above 1 and a unit price.",+ "from": "From qty","quantity": "From quantity",- "remove": "Remove the break from {quantity}",- "save_failed": "Could not save the quantity breaks.",- "save_success_one": "Saved {{count}} quantity break.",- "save_success_other": "Saved {{count}} quantity breaks.",- "title": "Quantity breaks — {{variant}}",- "unit_price": "Unit price"+ "remove_short": "Remove this quantity break"},"title": "Price Lists","unschedule": "Unschedule",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 7afbae93d7..6f0acbe8f2 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -3332,7 +3332,6 @@"price": "Prix","product": "Produit","sku": "SKU",- "tiers": "Paliers","variant": "Variante"},"compare_at_aria": "Prix de comparaison pour {{label}}",@@ -3410,20 +3409,9 @@"subtitle": "Tarification ciblée pour des groupes de clients, des régions ou des paliers de volume.","tiers": {"add": "Ajouter un palier de quantité",- "add_short": "Ajouter",- "count_badge_one": "{{count}} palier",- "count_badge_other": "{{count}} paliers",- "duplicate_quantity": "Deux paliers ne peuvent pas commencer à la même quantité.",- "empty": "Aucun palier — cette déclinaison est facturée au même prix quelle que soit la quantité.",- "help": "À partir de chaque quantité, la ligne est facturée à ce prix unitaire. Une déclinaison à paliers est facturée uniquement ainsi — le pourcentage de la liste ne s’y applique pas.",- "invalid_rung": "Chaque palier a besoin d’une quantité supérieure à 1 et d’un prix unitaire.",+ "from": "Dès qté","quantity": "À partir de",- "remove": "Supprimer le palier à partir de {quantity}",- "save_failed": "Impossible d’enregistrer les paliers de quantité.",- "save_success_one": "{{count}} palier de quantité enregistré.",- "save_success_other": "{{count}} paliers de quantité enregistrés.",- "title": "Paliers de quantité — {{variant}}",- "unit_price": "Prix unitaire"+ "remove_short": "Supprimer ce palier de quantité"},"title": "Listes de prix","unschedule": "Déplanifier",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 64577ae9b8..3fdc2be500 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -3362,7 +3362,6 @@"price": "Cena","product": "Produkt","sku": "SKU",- "tiers": "Progi","variant": "Wariant"},"compare_at_aria": "Cena porównawcza dla {{label}}",@@ -3448,24 +3447,9 @@"subtitle": "Ceny ukierunkowane na grupy klientów, regiony lub progi ilościowe.","tiers": {"add": "Dodaj próg ilościowy",- "add_short": "Dodaj",- "count_badge_few": "progi: {{count}}",- "count_badge_many": "progów: {{count}}",- "count_badge_one": "próg: {{count}}",- "count_badge_other": "progów: {{count}}",- "duplicate_quantity": "Dwa progi nie mogą zaczynać się od tej samej ilości.",- "empty": "Brak progów — ten wariant kosztuje tyle samo niezależnie od wielkości zamówienia.",- "help": "Od danej ilości w górę linia jest liczona po tej cenie jednostkowej. Wariant z progami jest wyceniany wyłącznie przez nie — procent listy go nie dotyczy.",- "invalid_rung": "Każdy próg potrzebuje ilości powyżej 1 i ceny jednostkowej.",+ "from": "Od ilości","quantity": "Od ilości",- "remove": "Usuń próg od {quantity}",- "save_failed": "Nie udało się zapisać progów ilościowych.",- "save_success_few": "Zapisano {{count}} progi ilościowe.",- "save_success_many": "Zapisano {{count}} progów ilościowych.",- "save_success_one": "Zapisano {{count}} próg ilościowy.",- "save_success_other": "Zapisano {{count}} progów ilościowych.",- "title": "Progi ilościowe — {{variant}}",- "unit_price": "Cena jednostkowa"+ "remove_short": "Usuń ten próg ilościowy"},"title": "Cenniki","unschedule": "Anuluj harmonogram",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex c96e8a21f7..85902ee70f 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -3324,7 +3324,6 @@"price": "价格","product": "商品","sku": "SKU",- "tiers": "阶梯","variant": "变体"},"compare_at_aria": "{{label}} 的对比价",@@ -3402,20 +3401,9 @@"subtitle": "针对客户群体、地区或批量层级的定向定价。","tiers": {"add": "添加数量阶梯",- "add_short": "添加",- "count_badge_one": "{{count}} 档",- "count_badge_other": "{{count}} 档",- "duplicate_quantity": "两档不能从同一数量开始。",- "empty": "暂无阶梯——无论订购多少,此变体都按同一价格计费。",- "help": "达到各档数量后,该行按此单价计费。设有阶梯的变体只按阶梯定价,列表的百分比对它不适用。",- "invalid_rung": "每一档都需要大于 1 的数量和有效的单价。",+ "from": "起订量","quantity": "起订量",- "remove": "删除 {quantity} 起的阶梯",- "save_failed": "无法保存数量阶梯。",- "save_success_one": "已保存 {{count}} 个数量阶梯。",- "save_success_other": "已保存 {{count}} 个数量阶梯。",- "title": "数量阶梯 — {{variant}}",- "unit_price": "单价"+ "remove_short": "删除此数量阶梯"},"title": "价格表","unschedule": "取消安排",