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
Added Price Lists admin UI to dashboard with Prices bulk editor
Damian Legawiecdfca5db9086e
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 39f4814f95..a0c1c145e5 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -978,10 +978,11 @@ export class AdminClient {* CRUD plus lifecycle (`activate` / `deactivate`) for `Spree::PriceList`.* Membership (`product_ids: [...]`), rules (`rules: [...]`), and per-row* price overrides (`prices: [...]`) all ride along on the normal- * `update` payload — one PATCH saves the entire editor. `prices(id)`- * fetches the spreadsheet's initial render data. Price lists are- * admin-only; the storefront only ever sees the resolved price (see- * `PriceSerializer#price_list_id`).+ * `update` payload — one PATCH saves the entire editor. The+ * spreadsheet's initial render data is fetched via+ * `prices.list({ price_list_id_eq: …, currency_eq: … })`. Price lists+ * are admin-only; the storefront only ever sees the resolved price+ * (see `PriceSerializer#price_list_id`).*/readonly priceLists = {list: (diff --git a/packages/admin/e2e/price-lists.spec.ts b/packages/admin/e2e/price-lists.spec.tsnew file mode 100644index 0000000000..e809b9928f--- /dev/null+++ b/packages/admin/e2e/price-lists.spec.ts@@ -0,0 +1,258 @@+import { expect, type Page, test } from '@playwright/test'+import { FIXTURE_PROMO_PRODUCT, gotoIndex, login, openRowMenu, rowButton } from './helpers'++const PRICE_LISTS_PATH = (storeId: string) => `/${storeId}/products/price-lists`+const PRODUCTS_PATH = (storeId: string) => `/${storeId}/products`+const CTA = /new price list/i++async function startNewPriceList(page: Page, storeId: string, name: string) {+ await page.getByRole('button', { name: CTA }).click()+ await expect(page).toHaveURL(new RegExp(`/${storeId}/products/price-lists/new`), {+ timeout: 15_000,+ })+ await expect(page.getByRole('heading', { name: /create price list/i })).toBeVisible({+ timeout: 15_000,+ })+ await page.locator('#name').fill(name)+}++async function submitCreate(page: Page, name: string) {+ await page.getByRole('button', { name: /^create$/i }).click()+ // On success the route navigates to the edit page whose header title+ // is the list's name.+ await expect(page.getByRole('heading', { name })).toBeVisible({ timeout: 15_000 })+}++async function pickRule(page: Page, ruleLabel: RegExp) {+ await page.getByRole('button', { name: /^add rule$/i }).click()+ await expect(page.getByRole('heading', { name: /^add rule$/i })).toBeVisible()+ // Scope to the picker dialog — page already has rule rows with the same+ // label after a list has rules.+ await page.getByRole('dialog').getByRole('button', { name: ruleLabel }).click()+}++async function saveEditor(page: Page) {+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^save$/i })+ .click()+}++async function saveForm(page: Page) {+ // Top-of-page Save (the one in the PageHeader, which renders inside+ // <main>). Scope to <main> so we don't hit a Save button inside a+ // dialog or footer.+ await page+ .getByRole('main')+ .getByRole('button', { name: /^save$/i })+ .first()+ .click()+}++// Pick a product from the Products card's `<ResourceMultiAutocomplete>`.+// Unlike the promotions spec's helper, the picker lives on the page (not+// inside a dialog), so we scope to `main` to skip any open Sheet/Dialog.+async function pickProductOnPage(page: Page, optionLabel: string) {+ const input = page.locator('main').getByPlaceholder(/search products by name/i)+ await input.fill(optionLabel)+ await page+ .getByRole('option', { name: new RegExp(optionLabel, 'i') })+ .first()+ .click()+ // Close the listbox so the next focus (the bulk-prices button) lands cleanly.+ await input.press('Escape')+}++async function openBulkPriceEditor(page: Page) {+ // Single "Edit prices" button on both surfaces (price-list PricesCard+ // and product PageHeader).+ await page.getByRole('button', { name: /^edit prices$/i }).click()+ await expect(page.getByRole('dialog')).toBeVisible({ timeout: 15_000 })+ await expect(page.getByRole('heading', { name: /^edit prices —/i })).toBeVisible()+}++test.describe('price lists', () => {+ test('lists price lists', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, PRICE_LISTS_PATH(creds.store_id), CTA)+ })++ test('creates a price list', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, PRICE_LISTS_PATH(creds.store_id), CTA)++ const name = `E2E PL ${Date.now()}`+ await startNewPriceList(page, creds.store_id, name)+ await submitCreate(page, name)++ await page.goto(PRICE_LISTS_PATH(creds.store_id))+ await expect(rowButton(page, name)).toBeVisible({ timeout: 15_000 })+ })++ test('row click opens the edit page', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, PRICE_LISTS_PATH(creds.store_id), CTA)++ const name = `E2E PL Edit ${Date.now()}`+ await startNewPriceList(page, creds.store_id, name)+ await submitCreate(page, name)++ await page.goto(PRICE_LISTS_PATH(creds.store_id))+ await rowButton(page, name).click()++ await expect(page).toHaveURL(/\/products\/price-lists\/pl_/, { timeout: 15_000 })+ await expect(page.getByRole('heading', { name })).toBeVisible({ timeout: 15_000 })+ await expect(page.locator('#name')).toHaveValue(name)+ })++ test('adds a Volume Rule via the rule editor', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, PRICE_LISTS_PATH(creds.store_id), CTA)++ const name = `E2E PL Rule ${Date.now()}`+ await startNewPriceList(page, creds.store_id, name)+ await submitCreate(page, name)++ // Rule-picker buttons include label + description; match by label only.+ await pickRule(page, /^volume rule\b/i)+ await expect(page.getByRole('heading', { name: /^volume rule$/i })).toBeVisible({+ timeout: 5_000,+ })+ await page+ .getByRole('dialog')+ .getByLabel(/min quantity/i)+ .fill('10')+ await saveEditor(page)++ await expect(page.getByText(/min quantity: 10/i)).toBeVisible({ timeout: 5_000 })++ await saveForm(page)++ await expect(page.getByText(/volume rule/i).first()).toBeVisible({ timeout: 15_000 })+ })++ test('bulk-edits a price-list override via the dialog', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, PRICE_LISTS_PATH(creds.store_id), CTA)++ const name = `E2E PL Prices ${Date.now()}`+ await startNewPriceList(page, creds.store_id, name)+ await submitCreate(page, name)++ // Attach a seeded product so the bulk editor has a row to edit.+ // Saving creates a placeholder price the editor can fill in.+ await pickProductOnPage(page, FIXTURE_PROMO_PRODUCT)+ await expect(page.getByText(/1 product selected/i)).toBeVisible({ timeout: 5_000 })+ await saveForm(page)+ // Card-counter help text updates once the placeholder price exists.+ await expect(page.getByText(/price configured/i)).toBeVisible({ timeout: 15_000 })++ await openBulkPriceEditor(page)++ // MoneyCell's editable input carries `aria-label="Price for <label>"`.+ // The fixture is a master variant with empty `options_text`, so the+ // suffix may be empty or "Default" depending on null-vs-empty handling.+ const priceInput = page+ .getByRole('dialog')+ .getByLabel(/^price for/i)+ .first()+ await expect(priceInput).toBeVisible({ timeout: 15_000 })+ // MoneyCell is a spreadsheet cell — readonly until you double-click+ // (or focus + press Enter) to enter edit mode.+ await priceInput.dblclick()+ await priceInput.fill('33.33')+ await priceInput.press('Enter')++ // Header surfaces the unsaved-change summary as soon as the cell commits.+ await expect(page.getByRole('dialog').getByText(/1 unsaved change/i)).toBeVisible()++ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^save prices$/i })+ .click()++ // The dirty-summary chip disappears once the upsert resolves and the+ // editor flushes its in-memory edits map. The Sonner save-success+ // toast auto-dismisses too quickly to be a reliable signal.+ await expect(page.getByRole('dialog').getByText(/unsaved change/i)).toBeHidden({+ timeout: 15_000,+ })+ await expect(+ page+ .getByRole('dialog')+ .getByLabel(/^price for/i)+ .first(),+ ).toHaveValue('33.33')+ })++ test('bulk-edits a product base price from the product page', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, PRODUCTS_PATH(creds.store_id), /add product/i)++ // Land on the seeded product's edit page via the index row click.+ // Product table renders the name cell as a `<Link>` (not a button).+ await page+ .getByRole('link', { name: new RegExp(FIXTURE_PROMO_PRODUCT, 'i') })+ .first()+ .click()+ await expect(page).toHaveURL(/\/products\/prod_/, { timeout: 15_000 })+ await expect(page.getByRole('heading', { name: FIXTURE_PROMO_PRODUCT })).toBeVisible({+ timeout: 15_000,+ })++ // Header "Edit prices" button (the InventoryCard one would also work).+ await openBulkPriceEditor(page)+ // Title carries the product name on this surface.+ await expect(+ page.getByRole('heading', {+ name: new RegExp(`edit prices — ${FIXTURE_PROMO_PRODUCT}`, 'i'),+ }),+ ).toBeVisible()++ const priceInput = page+ .getByRole('dialog')+ .getByLabel(/^price for/i)+ .first()+ await expect(priceInput).toBeVisible({ timeout: 15_000 })+ await priceInput.dblclick()+ await priceInput.fill('29.95')+ await priceInput.press('Enter')++ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^save prices$/i })+ .click()++ await expect(page.getByRole('dialog').getByText(/unsaved change/i)).toBeHidden({+ timeout: 15_000,+ })+ await expect(+ page+ .getByRole('dialog')+ .getByLabel(/^price for/i)+ .first(),+ ).toHaveValue('29.95')+ })++ test('deletes a price list', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, PRICE_LISTS_PATH(creds.store_id), CTA)++ const name = `E2E PL Delete ${Date.now()}`+ await startNewPriceList(page, creds.store_id, name)+ await submitCreate(page, name)++ await page.goto(PRICE_LISTS_PATH(creds.store_id))+ await expect(rowButton(page, name)).toBeVisible({ timeout: 15_000 })++ await openRowMenu(page, name)+ await page.getByRole('menuitem', { name: /^delete$/i }).click()+ await expect(page.getByRole('heading', { name: /delete price list\?/i })).toBeVisible()+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^delete$/i })+ .click()++ await expect(rowButton(page, name)).toHaveCount(0, { timeout: 15_000 })+ })+})diff --git a/packages/admin/src/components/spree/bulk-price-editor/bulk-price-editor-dialog.tsx b/packages/admin/src/components/spree/bulk-price-editor/bulk-price-editor-dialog.tsxnew file mode 100644index 0000000000..9b57106688--- /dev/null+++ b/packages/admin/src/components/spree/bulk-price-editor/bulk-price-editor-dialog.tsx@@ -0,0 +1,238 @@+import type { PriceList, Product } from '@spree/admin-sdk'+import { XIcon } from 'lucide-react'+import { useCallback, useEffect, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import {+ BulkPriceEditor,+ type BulkPriceEditorState,+} from '@/components/spree/bulk-price-editor/bulk-price-editor'+import { useConfirm } from '@/components/spree/confirm-dialog'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { useStore } from '@/providers/store-provider'++/**+ * Discriminator for what the dialog edits.+ *+ * - `price_list`: override prices for one price list. Editor filters to+ * `price_list_id_eq` and ships `price_list_id` on save.+ * - `product`: base prices (no price list) restricted to one product's+ * variants. Editor filters to `variant_product_id_eq` + `price_list_id_null`+ * and omits `price_list_id` on save.+ */+export type BulkPriceEditorScope =+ | { kind: 'price_list'; priceList: PriceList }+ | { kind: 'product'; product: Pick<Product, 'id' | 'name'> }++interface BulkPriceEditorDialogProps {+ open: boolean+ onOpenChange: (open: boolean) => void+ scope: BulkPriceEditorScope+}++/**+ * Modal bulk price editor. The dialog chrome (header, currency picker,+ * discard/save buttons, dirty-close guard) is identical regardless of+ * scope — only the title and the predicates forwarded to the editor+ * change. `kind: 'price_list'` edits overrides for one list; `kind:+ * 'product'` edits the base prices (price_list_id IS NULL) of one+ * product's variants.+ *+ * Why a dialog instead of a route: editing prices is "deeper into this+ * thing", not "leave this thing to go elsewhere". The dialog preserves+ * the form's state behind it (no remount on close).+ */+export function BulkPriceEditorDialog({ open, onOpenChange, scope }: BulkPriceEditorDialogProps) {+ const { t } = useTranslation()+ const { currencies, defaultCurrency } = useStore()+ const confirm = useConfirm()++ const [currency, setCurrency] = useState(defaultCurrency)+ const [editorState, setEditorState] = useState<BulkPriceEditorState>({+ dirtyCount: 0,+ saving: false,+ save: async () => false,+ discard: () => {},+ })++ const isDirty = editorState.dirtyCount > 0++ // Switch (not ternary) so adding a third `kind` becomes a TS error+ // instead of silently falling into the product branch.+ const { title, priceListId, editorFilter } = useMemo(() => {+ switch (scope.kind) {+ case 'price_list':+ return {+ title: t('admin.pages.products.price_lists.edit_prices.title', {+ name: scope.priceList.name,+ }),+ priceListId: scope.priceList.id,+ editorFilter: undefined,+ }+ case 'product':+ return {+ title: t('admin.pages.products.edit.bulk_prices.dialog_title', {+ name: scope.product.name,+ }),+ priceListId: undefined,+ editorFilter: { variant_product_id_eq: scope.product.id },+ }+ }+ }, [scope, t])++ const onStateChange = useCallback((next: BulkPriceEditorState) => {+ setEditorState(next)+ }, [])++ // Reset currency to the store default whenever the dialog reopens.+ // Stale currency state from a prior open would otherwise survive the+ // remount-less close+reopen.+ useEffect(() => {+ if (open) setCurrency(defaultCurrency)+ }, [open, defaultCurrency])++ // Guarded close — ESC / backdrop click / X button all funnel through+ // `onOpenChange(false)`. If there are dirty edits, confirm first.+ const handleOpenChange = useCallback(+ async (next: boolean) => {+ if (next) {+ onOpenChange(true)+ return+ }+ if (!isDirty) {+ onOpenChange(false)+ return+ }+ const ok = await confirm({+ title: t('admin.pages.products.price_lists.edit_prices.discard_confirm.title'),+ message: t('admin.pages.products.price_lists.edit_prices.discard_confirm.message_close', {+ count: editorState.dirtyCount,+ }),+ variant: 'destructive',+ confirmLabel: t('admin.pages.products.price_lists.edit_prices.discard_confirm.confirm'),+ })+ if (ok) {+ // Drop pending edits before closing — the dialog isn't remounted+ // on close, so stale edits would otherwise survive a reopen.+ editorState.discard()+ onOpenChange(false)+ }+ },+ [isDirty, editorState, confirm, onOpenChange, t],+ )++ const handleCurrencyChange = useCallback(+ async (next: string) => {+ if (next === currency) return+ if (isDirty) {+ const ok = await confirm({+ title: t('admin.pages.products.price_lists.edit_prices.discard_confirm.title'),+ message: t(+ 'admin.pages.products.price_lists.edit_prices.discard_confirm.message_currency',+ ),+ variant: 'destructive',+ confirmLabel: t('admin.pages.products.price_lists.edit_prices.discard_confirm.confirm'),+ })+ if (!ok) return+ // Same reason as the close path — strand the pending edits or+ // they'd persist across the currency switch.+ editorState.discard()+ }+ setCurrency(next)+ },+ [currency, isDirty, editorState, confirm, t],+ )++ return (+ <Dialog open={open} onOpenChange={(next) => handleOpenChange(next)} modal>+ <DialogContent+ // Edge-to-edge minus a 3-unit (0.75rem) gutter on all sides.+ // The primitive ships `top-1/2 left-1/2 -translate-1/2` (centered+ // popup) and inline `maxHeight: 90vh`. We override all four+ // insets with `!` utilities, zero the translate, and pass+ // `maxHeight: 'none'` to beat the inline style — together those+ // let the popup actually stretch between top-3 / bottom-3 / left-3+ // / right-3 instead of collapsing to its content size.+ className="!inset-3 !w-auto !max-w-none !translate-x-0 !translate-y-0 flex flex-col p-0"+ style={{ maxHeight: 'none' }}+ showCloseButton={false}+ >+ <DialogHeader className="flex flex-row items-center justify-between gap-3 space-y-0 border-b p-3">+ <div className="min-w-0">+ <DialogTitle className="truncate">{title}</DialogTitle>+ {isDirty && (+ <p className="mt-0.5 text-xs text-muted-foreground">+ {t('admin.pages.products.price_lists.edit_prices.dirty_summary', {+ count: editorState.dirtyCount,+ })}+ </p>+ )}+ </div>+ <div className="flex items-center gap-2">+ <Select value={currency} onValueChange={handleCurrencyChange}>+ <SelectTrigger size="sm" className="w-24">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {currencies.map((c) => (+ <SelectItem key={c} value={c}>+ {c}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={!isDirty || editorState.saving}+ onClick={() => editorState.discard()}+ >+ {t('admin.actions.discard')}+ </Button>+ <Button+ type="button"+ size="sm"+ disabled={!isDirty || editorState.saving}+ onClick={() => editorState.save()}+ >+ {editorState.saving+ ? t('admin.actions.saving')+ : t('admin.pages.products.price_lists.edit_prices.save_cta')}+ </Button>+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ onClick={() => handleOpenChange(false)}+ aria-label={t('admin.actions.close')}+ >+ <XIcon />+ </Button>+ </div>+ </DialogHeader>+ <DialogBody className="flex min-h-0 flex-1 flex-col p-3">+ <BulkPriceEditor+ priceListId={priceListId}+ currency={currency}+ filter={editorFilter}+ onStateChange={onStateChange}+ />+ </DialogBody>+ </DialogContent>+ </Dialog>+ )+}diff --git a/packages/admin/src/components/spree/bulk-price-editor/bulk-price-editor.tsx b/packages/admin/src/components/spree/bulk-price-editor/bulk-price-editor.tsxnew file mode 100644index 0000000000..0cbbaef50f--- /dev/null+++ b/packages/admin/src/components/spree/bulk-price-editor/bulk-price-editor.tsx@@ -0,0 +1,480 @@+import type { PriceBulkUpsertRow } from '@spree/admin-sdk'+import { useQuery } from '@tanstack/react-query'+import type { ColumnDef } from '@tanstack/react-table'+import { useCallback, useDeferredValue, useEffect, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { adminClient } from '@/client'+import { DataGrid, editableRowIndex, MoneyCell, ReadOnlyCell } from '@/components/spree/data-grid'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { useBulkUpsertPrices } from '@/hooks/use-prices'++const PAGE_SIZE = 50++interface PriceRowState {+ id: string+ kind: 'header' | 'item'+ productName?: string+ productId?: string+ priceId?: string+ variantId?: string+ variantLabel?: string | null+ sku?: string | null+ amount?: string | null+ compareAt?: string | null+}++interface PriceListRowFromServer {+ id: string+ variant_id: string+ amount: string | null+ compare_at_amount: string | null+ variant?: {+ product_id?: string+ product_name?: string+ options_text?: string | null+ sku?: string | null+ }+}++interface CellEdit {+ // Stash the variantId at write time. Without it, edits made on page 2+ // would lose their identifier as soon as the user paginates back to+ // page 1: the save loop resolves variant_id via `baselineRows`, which+ // only holds the current page's server result.+ variantId: string+ amount: string | null+ compareAt: string | null+}++type FilterShape = Record<string, string | number | boolean | null | undefined>++// Strip predicates the editor owns + drop empty values, then serialize+// in a key-sorted form so reference churn from the parent doesn't+// trigger spurious refetches / edits resets but real shape changes do.+function sanitizeFilter(filter: FilterShape | undefined): FilterShape {+ if (!filter) return {}+ const out: FilterShape = {}+ for (const [k, v] of Object.entries(filter)) {+ if (k.startsWith('price_list_id')) continue+ if (v === undefined || v === null || v === '') continue+ out[k] = v+ }+ return out+}++function stableFilterKey(filter: FilterShape): string {+ const entries = Object.entries(filter).sort(([a], [b]) => a.localeCompare(b))+ return entries.length === 0 ? '' : JSON.stringify(entries)+}++function currencyParts(currencyCode: string, locale: string): { symbol: string; decimal: string } {+ try {+ const parts = new Intl.NumberFormat(locale, {+ style: 'currency',+ currency: currencyCode,+ }).formatToParts(1234.56)+ return {+ symbol: parts.find((p) => p.type === 'currency')?.value ?? currencyCode,+ decimal: parts.find((p) => p.type === 'decimal')?.value ?? '.',+ }+ } catch {+ return { symbol: currencyCode, decimal: '.' }+ }+}++export interface BulkPriceEditorProps {+ /** Filter by a specific price list. Omit to edit base prices. */+ priceListId?: string+ currency: string+ /** Extra Ransack predicates spread into the index call — e.g.+ * `{ variant_product_id_eq: 'prod_xxx' }` for a per-product editor.+ * Keys starting with `price_list_id` are stripped (the editor owns+ * that predicate via `priceListId`). Memoize in the parent to avoid+ * refetch + edits-reset churn on every render. */+ filter?: Record<string, string | number | boolean | null | undefined>+ /** Notifies the parent of dirty count + save handle so the route can+ * render a sticky footer bar and a router-leave guard. */+ onStateChange?: (state: BulkPriceEditorState) => void+}++export interface BulkPriceEditorState {+ dirtyCount: number+ saving: boolean+ /** Resolves to `true` if the upsert succeeded, `false` on error (the+ * editor already toasted) or no-op (nothing dirty). Lets the dialog+ * decide whether to close without inspecting post-save state. */+ save: () => Promise<boolean>+ discard: () => void+}++/**+ * Generic prices spreadsheet. Reads via `GET /admin/prices?…&expand=variant`+ * (server-side pagination, SKU search) and saves via+ * `POST /admin/prices/bulk_upsert`. Filters are owned by the caller so+ * the same component drives both the "edit one price list" route and a+ * future "edit base prices" route.+ */+export function BulkPriceEditor({+ priceListId,+ currency,+ filter,+ onStateChange,+}: BulkPriceEditorProps) {+ const { t, i18n } = useTranslation()+ // Destructure the stable handles off `useMutation` (mutateAsync is+ // stable across renders; the wrapper object is not). Closing over the+ // wrapper would put a fresh reference in every callback's dep array+ // and tank the parent via the `onStateChange` effect below.+ const { mutateAsync: bulkUpsertAsync, isPending: isSaving } = useBulkUpsertPrices()+ const [page, setPage] = useState(1)+ const [search, setSearch] = useState('')+ const deferredSearch = useDeferredValue(search)++ const sanitizedFilter = useMemo(() => sanitizeFilter(filter), [filter])+ const filterKey = useMemo(() => stableFilterKey(sanitizedFilter), [sanitizedFilter])++ const { symbol, decimal } = useMemo(+ () => currencyParts(currency, i18n.language || 'en'),+ [currency, i18n.language],+ )++ const { data, isLoading } = useQuery({+ queryKey: [+ 'prices',+ { priceListId: priceListId ?? null, currency, filter: filterKey, page, q: deferredSearch },+ ],+ queryFn: () =>+ adminClient.prices.list({+ // Caller-supplied predicates first, then the editor's own — the+ // sanitizer above strips any `price_list_id_*` keys so callers+ // can't override our scope distinction.+ ...sanitizedFilter,+ ...(priceListId ? { price_list_id_eq: priceListId } : { price_list_id_null: true }),+ currency_eq: currency,+ // `search` is a Ransack-whitelisted scope on Price that ORs+ // across the variant's SKU, parent product name, and option-value+ // presentations ("Red", "XL", …). 3-char floor lives in the scope.+ search: deferredSearch || undefined,+ expand: 'variant',+ page,+ limit: PAGE_SIZE,+ sort: 'variant_product_name,variant_id',+ } as never),+ enabled: !!currency,+ })++ const totalPages = data?.meta?.pages ?? 1+ const totalCount = data?.meta?.count ?? 0++ const baselineRows = useMemo<PriceRowState[]>(() => {+ if (!data) return []+ const out: PriceRowState[] = []+ let lastProductId: string | null = null+ for (const row of data.data as unknown as PriceListRowFromServer[]) {+ const variant = row.variant ?? {}+ if (variant.product_id && variant.product_id !== lastProductId) {+ out.push({+ id: `header:${variant.product_id}`,+ kind: 'header',+ productName: variant.product_name,+ productId: variant.product_id,+ })+ lastProductId = variant.product_id+ }+ out.push({+ id: row.id,+ kind: 'item',+ priceId: row.id,+ variantId: row.variant_id,+ variantLabel: variant.options_text ?? null,+ sku: variant.sku ?? null,+ amount: row.amount,+ compareAt: row.compare_at_amount,+ })+ }+ return out+ }, [data])++ const [edits, setEdits] = useState<Map<string, CellEdit>>(() => new Map())++ // Reset page + edits whenever the upstream filters change — a different+ // list, currency, or product scope is a different working set; carrying+ // old edits across would be confusing and could collide on the+ // bulk-upsert ids.+ // biome-ignore lint/correctness/useExhaustiveDependencies: reset is bound to filter identity+ useEffect(() => {+ setPage(1)+ setEdits(new Map())+ }, [priceListId, currency, filterKey])++ const rows = useMemo<PriceRowState[]>(+ () =>+ baselineRows.map((r) => {+ if (r.kind !== 'item' || !r.priceId) return r+ const edit = edits.get(r.priceId)+ if (!edit) return r+ return { ...r, amount: edit.amount, compareAt: edit.compareAt }+ }),+ [baselineRows, edits],+ )++ const setCell = useCallback(+ (priceId: string, field: 'amount' | 'compareAt', next: string | null) => {+ setEdits((prev) => {+ const baseline = baselineRows.find(+ (r): r is PriceRowState & { kind: 'item' } => r.kind === 'item' && r.priceId === priceId,+ )+ 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+ // baseline in display form so an untouched field naturally matches+ // when the other field is edited — otherwise an edit to `compareAt`+ // alone would falsely mark `amount` dirty under a comma-decimal locale.+ const displayBaseAmount = baseline.amount ? baseline.amount.replace('.', decimal) : null+ const displayBaseCompare = baseline.compareAt+ ? baseline.compareAt.replace('.', decimal)+ : null+ const current = prev.get(priceId) ?? {+ variantId: baseline.variantId,+ amount: displayBaseAmount,+ compareAt: displayBaseCompare,+ }+ const merged = { ...current, [field]: next }+ if (merged.amount === displayBaseAmount && merged.compareAt === displayBaseCompare) {+ const out = new Map(prev)+ out.delete(priceId)+ return out+ }+ const out = new Map(prev)+ out.set(priceId, merged)+ return out+ })+ },+ [baselineRows, decimal],+ )++ const save = useCallback(async (): Promise<boolean> => {+ if (edits.size === 0) return false+ // Snapshot the keys we're about to ship; cells stay editable while+ // 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())+ // 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+ // no point making the server backfill them.+ const payload: PriceBulkUpsertRow[] = savedKeys.map((priceId) => {+ const edit = edits.get(priceId) as CellEdit+ return {+ variant_id: edit.variantId,+ currency,+ ...(priceListId ? { price_list_id: priceListId } : {}),+ amount: edit.amount,+ compare_at_amount: edit.compareAt,+ }+ })+ try {+ const res = await bulkUpsertAsync({ prices: payload })+ toast.success(+ t('admin.pages.products.price_lists.edit_prices.save_success', { count: res.price_count }),+ )+ setEdits((prev) => {+ const out = new Map(prev)+ for (const key of savedKeys) out.delete(key)+ return out+ })+ return true+ } catch (err) {+ const message =+ err instanceof Error+ ? err.message+ : t('admin.pages.products.price_lists.edit_prices.save_failed')+ toast.error(message)+ return false+ }+ }, [edits, currency, priceListId, bulkUpsertAsync, t])++ const discard = useCallback(() => {+ setEdits(new Map())+ }, [])++ // Surface dirty/save/discard to the parent route so it can render a+ // sticky footer and gate router navigation on unsaved edits.+ useEffect(() => {+ onStateChange?.({ dirtyCount: edits.size, saving: isSaving, save, discard })+ }, [edits.size, isSaving, save, discard, onStateChange])++ const columns = useMemo<ColumnDef<PriceRowState>[]>(+ () => [+ {+ id: 'variant',+ header: t('admin.pages.products.price_lists.edit_prices.columns.variant'),+ cell: ({ row }) => {+ const r = row.original+ if (r.kind !== 'item') return null+ return (+ <ReadOnlyCell className="text-muted-foreground">+ {r.variantLabel ?? t('admin.pages.products.price_lists.edit_prices.variant_default')}+ </ReadOnlyCell>+ )+ },+ },+ {+ id: 'sku',+ header: t('admin.pages.products.price_lists.edit_prices.columns.sku'),+ cell: ({ row }) => {+ const r = row.original+ if (r.kind !== 'item') return null+ return (+ <ReadOnlyCell className="font-mono text-xs text-muted-foreground">+ {r.sku ?? '—'}+ </ReadOnlyCell>+ )+ },+ },+ {+ id: 'amount',+ header: () => (+ <span className="block text-right">+ {t('admin.pages.products.price_lists.edit_prices.columns.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 ?? t('admin.pages.products.price_lists.edit_prices.variant_default')+ return (+ <MoneyCell+ coords={coords}+ value={r.amount ?? null}+ onChange={(next) => r.priceId && setCell(r.priceId, 'amount', next)}+ symbol={symbol}+ decimal={decimal}+ ariaLabel={t('admin.pages.products.price_lists.edit_prices.price_aria', { label })}+ />+ )+ },+ },+ {+ id: 'compare_at',+ header: () => (+ <span className="block text-right">+ {t('admin.pages.products.price_lists.edit_prices.columns.compare_at_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: 3 }+ const label =+ r.variantLabel ?? t('admin.pages.products.price_lists.edit_prices.variant_default')+ return (+ <MoneyCell+ coords={coords}+ value={r.compareAt ?? null}+ onChange={(next) => r.priceId && setCell(r.priceId, 'compareAt', next)}+ symbol={symbol}+ decimal={decimal}+ ariaLabel={t('admin.pages.products.price_lists.edit_prices.compare_at_aria', {+ label,+ })}+ />+ )+ },+ },+ ],+ [symbol, decimal, setCell, t],+ )++ const isEmpty = !isLoading && rows.length === 0++ return (+ <div className="flex h-full flex-col gap-3">+ {/* Always-mounted toolbar. Conditionally rendering the search+ input would unmount it mid-keystroke whenever the deferred+ query refetches into the loading state, blurring the field+ and dropping the user's text cursor. */}+ <div className="flex shrink-0 items-center justify-between gap-3">+ <p className="text-xs text-muted-foreground">+ {totalCount > 0+ ? t('admin.pages.products.price_lists.edit_prices.count_summary', {+ count: totalCount,+ currency,+ })+ : t('admin.pages.products.price_lists.edit_prices.no_matches_for_filters')}+ </p>+ <Input+ type="search"+ placeholder={t('admin.pages.products.price_lists.edit_prices.search_placeholder')}+ value={search}+ onChange={(e) => {+ setSearch(e.target.value)+ setPage(1)+ }}+ className="h-9 max-w-sm"+ />+ </div>++ {/* The flex-1 + min-h-0 combo lets the grid scroll within its+ container instead of pushing the toolbar/pagination off-screen.+ Loading and empty states fill the same space so the dialog+ never visually collapses around small content. */}+ <div className="min-h-0 flex-1 overflow-auto">+ {isLoading ? (+ <p className="text-sm text-muted-foreground">{t('admin.common.loading')}</p>+ ) : isEmpty ? (+ <p className="text-sm text-muted-foreground">+ {search+ ? t('admin.pages.products.price_lists.edit_prices.no_matches_for_search', { search })+ : priceListId+ ? t('admin.pages.products.price_lists.edit_prices.empty_pick_products')+ : t('admin.pages.products.price_lists.edit_prices.empty_no_base_prices')}+ </p>+ ) : (+ <DataGrid<PriceRowState>+ rows={rows}+ columns={columns}+ getRowId={(row) => row.id}+ renderSectionHeader={(row) =>+ row.kind === 'header' ? (+ <div className="truncate font-medium">{row.productName}</div>+ ) : null+ }+ aria-label={t('admin.pages.products.price_lists.edit_prices.grid_aria')}+ />+ )}+ </div>++ {totalPages > 1 && (+ <div className="flex shrink-0 items-center justify-between gap-2 text-xs text-muted-foreground">+ <span>{t('admin.common.page_of', { page, total: totalPages })}</span>+ <div className="flex gap-1">+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => setPage((p) => Math.max(1, p - 1))}+ disabled={page === 1 || isLoading}+ >+ {t('admin.common.prev')}+ </Button>+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => setPage((p) => Math.min(totalPages, p + 1))}+ disabled={page === totalPages || isLoading}+ >+ {t('admin.common.next')}+ </Button>+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/packages/admin/src/components/spree/data-grid/cells.tsx b/packages/admin/src/components/spree/data-grid/cells.tsxindex 538d68b109..448573111b 100644--- a/packages/admin/src/components/spree/data-grid/cells.tsx+++ b/packages/admin/src/components/spree/data-grid/cells.tsx@@ -138,6 +138,161 @@ export function NumberCell({)}+interface MoneyCellProps extends BaseCellProps {+ /** Canonical decimal string (`12.50`) coming back from the API, or+ * `null`/blank for unset. */+ value: string | null+ /** Receives the user's raw input — locale-formatted strings like+ * `"12,50"` are fine, the backend's `Spree::LocalizedNumber` does the+ * parsing. `null` only when the user explicitly blanks the field. */+ onChange: (next: string | null) => void+ /** Currency symbol rendered as a non-editable prefix (`$`, `€`, `kr`, …). */+ symbol: string+ /**+ * Locale decimal separator used only for display (canonical `.` →+ * locale char). Whatever the user types is shipped as-is; the+ * backend handles thousands separators, grouped digits, and so on.+ * Default `.`.+ */+ decimal?: string+}++/**+ * Editable money cell. Like `NumberCell` but keeps decimals (no truncation)+ * and renders a currency-symbol prefix. Mirrors the rails admin's+ * `edit_prices` bulk editor: format the API's canonical value with the+ * locale's decimal mark for display, but ship the user's raw input+ * untouched on save. `Spree::LocalizedNumber.parse` on the backend handles+ * locale-aware parsing (thousands separators, decimal comma, etc.) so the+ * SPA doesn't have to reimplement it.+ */+export function MoneyCell({+ coords,+ value,+ onChange,+ symbol,+ decimal = '.',+ ariaLabel,+}: MoneyCellProps) {+ const ctx = useDataGridContext()+ const inputRef = useRef<HTMLInputElement | null>(null)++ const formatDisplay = (v: string | null): string =>+ v == null || v === '' ? '' : v.replace('.', decimal)++ const [draft, setDraft] = useState(formatDisplay(value))+ const isSelected = ctx.isSelected(coords)+ const mode = modeFor(ctx.editing, coords)+ const isEditing = mode === 'edit'+ const isFocused = ctx.anchor?.row === coords.row && ctx.anchor?.col === coords.col++ // Resync draft with external value when not editing.+ // biome-ignore lint/correctness/useExhaustiveDependencies: intentional resync+ useEffect(() => {+ if (!isEditing) setDraft(formatDisplay(value))+ }, [value, isEditing, decimal])++ // Auto-focus + select when entering edit mode.+ useEffect(() => {+ if (isEditing) {+ const el = inputRef.current+ if (el) {+ el.focus()+ el.select()+ }+ }+ }, [isEditing])++ // The wrapping div is what the FillHandle measures and what+ // elementFromPoint hits during a fill drag — register it as the+ // cell's element. The input itself is what we focus.+ const wrapRef = useRef<HTMLDivElement | null>(null)+ useStableCellRegistration(coords, {+ focus: () => inputRef.current?.focus(),+ read: () => formatDisplay(value),+ write: (next) => onChange(next.trim() ? next : null),+ canWrite: () => true,+ getElement: () => wrapRef.current,+ })++ function commit() {+ // Ship the user's raw input; the backend's `Spree::LocalizedNumber`+ // handles locale-aware parsing. Empty string is the only "clear"+ // signal we generate frontend-side.+ onChange(draft.trim() ? draft : null)+ }++ function onKeyDown(event: KeyboardEvent<HTMLInputElement>) {+ if (!isEditing) return+ if (event.key === 'Enter') {+ event.preventDefault()+ commit()+ ctx.setEditing(null)+ const next = { row: coords.row + 1, col: coords.col }+ ctx.setAnchor(next)+ ctx.setExtent(next)+ ctx.cells.get(`${next.row}.${next.col}`)?.focus()+ } else if (event.key === 'Escape') {+ event.preventDefault()+ setDraft(formatDisplay(value))+ ctx.setEditing(null)+ } else if (event.key === 'Tab') {+ event.preventDefault()+ commit()+ ctx.setEditing(null)+ const dx = event.shiftKey ? -1 : 1+ const next = { row: coords.row, col: coords.col + dx }+ ctx.setAnchor(next)+ ctx.setExtent(next)+ ctx.cells.get(`${next.row}.${next.col}`)?.focus()+ }+ }++ return (+ <div+ ref={wrapRef}+ className={cn(+ 'flex h-9 w-full items-center transition-colors',+ isSelected && 'bg-blue-500/10',+ isFocused && !isEditing && 'ring-2 ring-blue-500 ring-inset',+ isEditing && 'bg-card ring-2 ring-blue-500 ring-inset',+ )}+ >+ <span+ className="pl-3 text-muted-foreground pointer-events-none select-none tabular-nums"+ aria-hidden+ >+ {symbol}+ </span>+ <input+ ref={inputRef}+ type="text"+ inputMode="decimal"+ value={isEditing ? draft : formatDisplay(value)}+ readOnly={!isEditing}+ onChange={(e) => setDraft(e.target.value)}+ onFocus={() => {+ ctx.setAnchor(coords)+ ctx.setExtent(coords)+ }}+ onDoubleClick={() => ctx.setEditing(coords)}+ onKeyDown={onKeyDown}+ onBlur={() => {+ if (isEditing) {+ commit()+ ctx.setEditing(null)+ }+ }}+ aria-label={ariaLabel}+ className={cn(+ 'block h-9 w-full cursor-cell border-0 bg-transparent pl-1 pr-3 text-right tabular-nums outline-none',+ isEditing && 'cursor-text',+ )}+ />+ </div>+ )+}+interface SwitchCellProps extends BaseCellProps {value: booleanonChange: (next: boolean) => voiddiff --git a/packages/admin/src/components/spree/data-grid/data-grid.tsx b/packages/admin/src/components/spree/data-grid/data-grid.tsxindex 86e17df10e..c39a3d1df6 100644--- a/packages/admin/src/components/spree/data-grid/data-grid.tsx+++ b/packages/admin/src/components/spree/data-grid/data-grid.tsx@@ -9,6 +9,7 @@ import {import { useCallback, useMemo, useRef, useState } from 'react'import { cn } from '@/lib/utils'import { coordsInRect, DataGridContext, type DataGridContextValue } from './context'+import { FillHandle } from './fill-handle'import type { CellCoords, CellKey, CellRegistration, RenderSectionHeader } from './types'import { cellKey } from './types'import { useDataGridKeyboard } from './use-data-grid-keyboard'@@ -129,7 +130,7 @@ function DataGridShell<T>({return (<DataGridContext.Provider value={ctx}><DataGridKeyboardMount gridRef={gridRef} />- <div className="overflow-hidden rounded-md">+ <div className="relative overflow-hidden rounded-md"><tableref={gridRef}className={cn(@@ -171,6 +172,7 @@ function DataGridShell<T>({))}</tbody></table>+ <FillHandle gridRef={gridRef} /></div></DataGridContext.Provider>)diff --git a/packages/admin/src/components/spree/data-grid/fill-handle.tsx b/packages/admin/src/components/spree/data-grid/fill-handle.tsxnew file mode 100644index 0000000000..56ea8d0784--- /dev/null+++ b/packages/admin/src/components/spree/data-grid/fill-handle.tsx@@ -0,0 +1,153 @@+import { useEffect, useState } from 'react'+import { useDataGridContext } from './context'+import type { CellCoords, CellKey } from './types'+import { cellKey } from './types'++/**+ * Excel-style fill handle. Renders a 9×9 square anchored to the+ * bottom-right of the cell that's the current selection's far corner.+ * Pointer-drag from the handle expands the selection rectangle; on+ * release we copy the anchor cell's value into every other cell in+ * the rectangle (skipping cells whose `canWrite` rejects the value).+ *+ * Positioning is absolute over the grid's `<table>`. The handle reads+ * the far-corner cell's bounding rect via `getElement()` (provided by+ * each cell's registration) and the table's own rect, then offsets so+ * the handle sits inside the cell's corner.+ */+export function FillHandle({ gridRef }: { gridRef: React.RefObject<HTMLElement | null> }) {+ const ctx = useDataGridContext()+ const { anchor, extent, cells, editing } = ctx++ // Local drag state — null when idle.+ const [drag, setDrag] = useState<{+ sourceKey: CellKey+ sourceValue: string+ /** The current rect we're previewing as the fill target. */+ preview: { row: number; col: number } | null+ } | null>(null)+ const [tick, setTick] = useState(0)+ // Re-measure on scroll/resize so the handle follows the cell.+ useEffect(() => {+ function bump() {+ setTick((t) => t + 1)+ }+ window.addEventListener('resize', bump)+ window.addEventListener('scroll', bump, true)+ return () => {+ window.removeEventListener('resize', bump)+ window.removeEventListener('scroll', bump, true)+ }+ }, [])++ // Hide the handle while editing or when there's no selection.+ if (!anchor || !extent || editing) return null++ // Far corner of the current selection (the cell whose bottom-right+ // gets the handle). Drag previews use the same anchor as the source.+ const farRow = Math.max(anchor.row, extent.row)+ const farCol = Math.max(anchor.col, extent.col)+ const farReg = cells.get(cellKey({ row: farRow, col: farCol }))+ const farEl = farReg?.getElement?.()+ const gridEl = gridRef.current+ if (!farEl || !gridEl) return null++ // Position relative to the gridEl's positioning context. Use offsetParent+ // math through getBoundingClientRect for portability.+ const farRect = farEl.getBoundingClientRect()+ const gridRect = gridEl.getBoundingClientRect()+ // Sit the handle so its center is exactly on the cell's bottom-right corner.+ const left = farRect.right - gridRect.left - 4+ const top = farRect.bottom - gridRect.top - 4++ function onPointerDown(e: React.PointerEvent<HTMLDivElement>) {+ e.preventDefault()+ e.stopPropagation()+ // Source is always the *anchor* — that's what users instinctively+ // expect to be copied. If they had a multi-cell selection going,+ // we still copy from the anchor (top-left), matching Excel.+ const sourceReg = cells.get(cellKey(anchor!))+ if (!sourceReg) return+ const sourceValue = sourceReg.read()+ setDrag({+ sourceKey: cellKey(anchor!),+ sourceValue,+ preview: { row: farRow, col: farCol },+ })+ // Capture pointer so we keep getting move events even outside the+ // handle div.+ e.currentTarget.setPointerCapture(e.pointerId)+ }++ function onPointerMove(e: React.PointerEvent<HTMLDivElement>) {+ if (!drag) return+ // Hit-test the cell under the pointer.+ const target = document.elementFromPoint(e.clientX, e.clientY)+ if (!target) return+ // Walk up from the hit target looking for a cell with a known+ // coords attribute. We don't tag DOM nodes, so do it by linear scan+ // through the registry — small (<a few hundred cells per grid).+ let hit: CellCoords | null = null+ for (const reg of cells.values()) {+ const el = reg.getElement?.()+ if (el && el.contains(target as Node)) {+ hit = reg.coords+ break+ }+ }+ if (!hit) return+ // Constrain to the same column as the source (Excel: fill flows+ // down a column by default). Allow row movement only.+ setDrag({+ ...drag,+ preview: { row: hit.row, col: anchor!.col },+ })+ // Drive the grid's extent so the standard selection highlight+ // matches the preview region.+ ctx.setExtent({ row: hit.row, col: anchor!.col })+ }++ function onPointerUp() {+ if (!drag) return+ const preview = drag.preview+ if (preview) {+ const minRow = Math.min(anchor!.row, preview.row)+ const maxRow = Math.max(anchor!.row, preview.row)+ // Copy into every cell in the column range, skipping the source.+ for (let r = minRow; r <= maxRow; r += 1) {+ if (r === anchor!.row) continue+ const reg = cells.get(cellKey({ row: r, col: anchor!.col }))+ if (!reg) continue+ if (reg.canWrite(drag.sourceValue)) reg.write(drag.sourceValue)+ }+ }+ setDrag(null)+ }++ // The `tick` value forces position re-measurement when the table+ // reflows. Read it once so React doesn't optimize the var away.+ void tick++ return (+ <div+ // biome-ignore lint/a11y/useSemanticElements: this is a drag handle, not actionable on its own+ role="presentation"+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ style={{+ position: 'absolute',+ left,+ top,+ width: 9,+ height: 9,+ zIndex: 20,+ background: 'rgb(59 130 246)',+ border: '1px solid white',+ cursor: 'crosshair',+ boxShadow: '0 0 0 1px rgba(0,0,0,0.1)',+ }}+ aria-hidden+ />+ )+}diff --git a/packages/admin/src/components/spree/data-grid/helpers.ts b/packages/admin/src/components/spree/data-grid/helpers.tsnew file mode 100644index 0000000000..99ee7d2717--- /dev/null+++ b/packages/admin/src/components/spree/data-grid/helpers.ts@@ -0,0 +1,18 @@+/**+ * Counts editable (non-header) rows up to and including the given row id so+ * 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.+ */+export function editableRowIndex<T extends { kind: 'header' | 'item'; id: string }>(+ rows: ReadonlyArray<{ id: string; original: T }>,+ rowId: string,+): number {+ let i = 0+ for (const row of rows) {+ if (row.original.kind !== 'item') continue+ if (row.id === rowId) return i+ i+++ }+ return i+}diff --git a/packages/admin/src/components/spree/data-grid/index.ts b/packages/admin/src/components/spree/data-grid/index.tsindex f3967a5e30..6037b2ef7e 100644--- a/packages/admin/src/components/spree/data-grid/index.ts+++ b/packages/admin/src/components/spree/data-grid/index.ts@@ -1,4 +1,5 @@-export { NumberCell, ReadOnlyCell, SelectCell, SwitchCell } from './cells'+export { MoneyCell, NumberCell, ReadOnlyCell, SelectCell, SwitchCell } from './cells'export { useDataGridContext } from './context'export { DataGrid } from './data-grid'+export { editableRowIndex } from './helpers'export type { CellCoords, RenderSectionHeader } from './types'diff --git a/packages/admin/src/components/spree/data-grid/types.ts b/packages/admin/src/components/spree/data-grid/types.tsindex 0f93dd340b..0f2d43a439 100644--- a/packages/admin/src/components/spree/data-grid/types.ts+++ b/packages/admin/src/components/spree/data-grid/types.ts@@ -27,6 +27,9 @@ export interface CellRegistration {/** Whether this cell accepts a write — Switch cells, for example, only* accept "true" / "false" / "" so we can no-op on non-boolean pastes. */canWrite: (value: string) => boolean+ /** Resolve the cell's interactive root element. Used by the fill+ * handle to measure positions and hit-test drag targets. */+ getElement?: () => HTMLElement | null}/** Public render-prop API for grouped rows (e.g. "Variant: Small / Navy"). */diff --git a/packages/admin/src/components/spree/data-grid/use-stable-cell-registration.ts b/packages/admin/src/components/spree/data-grid/use-stable-cell-registration.tsindex 0e629dcb19..c292d504e6 100644--- a/packages/admin/src/components/spree/data-grid/use-stable-cell-registration.ts+++ b/packages/admin/src/components/spree/data-grid/use-stable-cell-registration.ts@@ -7,6 +7,7 @@ interface CellHandlers {read: () => stringwrite: (value: string) => voidcanWrite: (value: string) => boolean+ getElement?: () => HTMLElement | null}/**@@ -38,6 +39,7 @@ export function useStableCellRegistration(coords: CellCoords, handlers: CellHandread: () => handlersRef.current.read(),write: (v) => handlersRef.current.write(v),canWrite: (v) => handlersRef.current.canWrite(v),+ getElement: () => handlersRef.current.getElement?.() ?? null,})}, [row, col])}diff --git a/packages/admin/src/components/spree/price-list-editors/price-list-form.tsx b/packages/admin/src/components/spree/price-list-editors/price-list-form.tsxnew file mode 100644index 0000000000..90d46b36fd--- /dev/null+++ b/packages/admin/src/components/spree/price-list-editors/price-list-form.tsx@@ -0,0 +1,875 @@+import { zodResolver } from '@hookform/resolvers/zod'+import type { PriceList, PriceRule, ResourceTypeDefinition } from '@spree/admin-sdk'+import { parseISO } from 'date-fns'+import { formatInTimeZone } from 'date-fns-tz'+import {+ CalendarOffIcon,+ PauseIcon,+ PencilIcon,+ PlayIcon,+ PlusIcon,+ TableIcon,+ TrashIcon,+} from 'lucide-react'+import { useEffect, useState } from 'react'+import { Controller, type UseFormReturn, useFieldArray, useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import { adminClient } from '@/client'+import { BulkPriceEditorDialog } from '@/components/spree/bulk-price-editor/bulk-price-editor-dialog'+import { Can } from '@/components/spree/can'+import { useConfirm } from '@/components/spree/confirm-dialog'+import { PageHeader } from '@/components/spree/page-header'+import { PreferencesForm } from '@/components/spree/preferences-form'+import { PriceListStatusBadge } from '@/components/spree/price-list-editors/status-badge'+import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'+import { useStore } from '@/providers/store-provider'+// Side-effect import — registers per-rule editors (customer, customer+// group, …) into the slot registry. Must run before any RuleEditSheet+// mounts.+import '@/components/spree/price-list-editors/register'+import {+ type PriceRuleEditorContext,+ ruleFormSlot,+} from '@/components/spree/price-list-editors/types'+import { EditorShell } from '@/components/spree/promotion-editors/editor-shell'+import { ResourceLayout } from '@/components/spree/resource-layout'+import { Slot } from '@/components/spree/slot'+import { StoreDatePicker } from '@/components/spree/store-date-picker'+import { Button } from '@/components/ui/button'+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'+import { Input } from '@/components/ui/input'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import {+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+} from '@/components/ui/sheet'+import { Textarea } from '@/components/ui/textarea'+import {+ useActivatePriceList,+ useDeactivatePriceList,+ usePriceRuleTypes,+} from '@/hooks/use-price-lists'+import { mapSpreeErrorsToForm } from '@/lib/form-errors'+import { Subject } from '@/lib/permissions'+import {+ MATCH_POLICIES,+ PRICE_LIST_DEFAULTS,+ type PriceListFormValues,+ type PriceRuleFormDraft,+ priceListFormSchema,+ priceListValuesToParams,+ ruleDraftFromRule,+ ruleDraftFromType,+} from '@/schemas/price-list'++// =============================================================================+// Public API+// =============================================================================++interface PriceListFormProps {+ mode: 'create' | 'edit'+ /** Existing record (edit mode only). */+ priceList?: PriceList+ /** Existing rules (edit mode only) — fetched separately, the price list serializer doesn't embed them by default. */+ initialRules?: PriceRule[]+ /** Called on Save. Receives the full payload — rules included. */+ onSubmit: (payload: ReturnType<typeof priceListValuesToParams>) => Promise<void>+ /** Edit-mode only: when supplied, the header gains a Delete button. */+ onDelete?: () => void+ deletePending?: boolean+}++// =============================================================================+// Component+// =============================================================================++export function PriceListForm({+ mode,+ priceList,+ initialRules,+ onSubmit,+ onDelete,+ deletePending = false,+}: PriceListFormProps) {+ const { t } = useTranslation()++ const form = useForm<PriceListFormValues>({+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ resolver: zodResolver(priceListFormSchema) as any,+ defaultValues: PRICE_LIST_DEFAULTS,+ })++ const rulesArray = useFieldArray<PriceListFormValues, 'rules', '_key'>({+ control: form.control,+ name: 'rules',+ keyName: '_key',+ })++ // biome-ignore lint/correctness/useExhaustiveDependencies: form is stable+ useEffect(() => {+ if (mode !== 'edit') return+ if (!priceList || !initialRules) return+ form.reset({+ name: priceList.name,+ description: priceList.description ?? '',+ starts_at: priceList.starts_at,+ ends_at: priceList.ends_at,+ match_policy: (priceList.match_policy as 'all' | 'any') ?? 'all',+ rules: initialRules.map(ruleDraftFromRule),+ product_ids: priceList.product_ids ?? [],+ })+ }, [mode, priceList, initialRules])++ async function handleSubmit(values: PriceListFormValues) {+ try {+ await onSubmit(priceListValuesToParams(values))+ } catch (err) {+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ }+ }++ const isLoading = mode === 'edit' && (!priceList || !initialRules)+ if (isLoading) {+ return (+ <ResourceLayout+ header={<PageHeader title={t('admin.common.loading')} backTo="products/price-lists" />}+ main={<div className="text-sm text-muted-foreground">{t('admin.common.loading')}</div>}+ />+ )+ }++ return (+ <form onSubmit={form.handleSubmit(handleSubmit)}>+ <ResourceLayout+ header={+ <PageHeader+ title={+ mode === 'create'+ ? t('admin.pages.products.price_lists.sheet_title_create')+ : (priceList?.name ?? '')+ }+ backTo="products/price-lists"+ badges={priceList && <PriceListStatusBadge priceList={priceList} />}+ actions={+ <div className="flex gap-2">+ {mode === 'edit' && priceList && <ActivationButtons priceList={priceList} />}+ {mode === 'edit' && onDelete && (+ <Can I="destroy" a={Subject.PriceList}>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ onClick={onDelete}+ disabled={deletePending}+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"+ >+ {t('admin.actions.delete')}+ </Button>+ </Can>+ )}+ <Button+ type="submit"+ size="sm"+ disabled={+ form.formState.isSubmitting || (mode === 'edit' && !form.formState.isDirty)+ }+ >+ {form.formState.isSubmitting+ ? mode === 'create'+ ? t('admin.actions.creating')+ : t('admin.actions.saving')+ : mode === 'create'+ ? t('admin.actions.create')+ : t('admin.actions.save')}+ </Button>+ </div>+ }+ />+ }+ main={+ <>+ {form.formState.errors.root?.message && (+ <p+ className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive"+ role="alert"+ >+ {form.formState.errors.root.message}+ </p>+ )}+ <RulesCard form={form} rulesArray={rulesArray} />+ <ProductsCard form={form} />+ {mode === 'edit' && priceList && <PricesCard priceList={priceList} />}+ </>+ }+ sidebar={+ <>+ <BasicsCard form={form} />+ <ScheduleCard form={form} />+ </>+ }+ />+ </form>+ )+}++// =============================================================================+// Sidebar cards+// =============================================================================++function BasicsCard({ form }: { form: UseFormReturn<PriceListFormValues> }) {+ const { t } = useTranslation()+ const { errors } = form.formState+ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.products.price_lists.basics_section')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="name">{t('admin.fields.price_list.name.label')}</FieldLabel>+ <Input+ id="name"+ autoFocus+ placeholder={t('admin.fields.price_list.name.placeholder')}+ aria-invalid={!!errors.name || undefined}+ {...form.register('name')}+ />+ <p className="text-xs text-muted-foreground">+ {t('admin.fields.price_list.name.help')}+ </p>+ <FieldError errors={[errors.name]} />+ </Field>+ <Field>+ <FieldLabel htmlFor="description">+ {t('admin.fields.price_list.description.label')}+ </FieldLabel>+ <Textarea+ id="description"+ rows={3}+ placeholder={t('admin.fields.price_list.description.placeholder')}+ {...form.register('description')}+ />+ </Field>+ </FieldGroup>+ </CardContent>+ </Card>+ )+}++function ScheduleCard({ form }: { form: UseFormReturn<PriceListFormValues> }) {+ const { t } = useTranslation()+ const { errors } = form.formState+ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.products.price_lists.schedule_section')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="pl-starts-at">+ {t('admin.fields.price_list.starts_at.label')}+ </FieldLabel>+ <Controller+ name="starts_at"+ control={form.control}+ render={({ field }) => (+ <StoreDatePicker+ value={field.value ?? null}+ onChange={(v) => field.onChange(v ?? null)}+ includeTime+ placeholder={t('admin.fields.price_list.starts_at.placeholder')}+ />+ )}+ />+ <p className="text-xs text-muted-foreground">+ {t('admin.fields.price_list.starts_at.help')}+ </p>+ </Field>+ <Field>+ <FieldLabel htmlFor="pl-ends-at">+ {t('admin.fields.price_list.ends_at.label')}+ </FieldLabel>+ <Controller+ name="ends_at"+ control={form.control}+ render={({ field }) => (+ <StoreDatePicker+ value={field.value ?? null}+ onChange={(v) => field.onChange(v ?? null)}+ includeTime+ placeholder={t('admin.fields.price_list.ends_at.placeholder')}+ />+ )}+ />+ <p className="text-xs text-muted-foreground">+ {t('admin.fields.price_list.ends_at.help')}+ </p>+ <FieldError errors={[errors.ends_at]} />+ </Field>+ </FieldGroup>+ </CardContent>+ </Card>+ )+}++// =============================================================================+// Activation header buttons+// =============================================================================++function ActivationButtons({ priceList }: { priceList: PriceList }) {+ const { t } = useTranslation()+ const { timezone } = useStore()+ const confirm = useConfirm()+ const activate = useActivatePriceList(priceList.id)+ const deactivate = useDeactivatePriceList(priceList.id)+ const isActive = priceList.status === 'active' || priceList.status === 'scheduled'++ const formatStoreDateTime = (iso: string) => formatInTimeZone(parseISO(iso), timezone, 'PPP p')++ async function handleDeactivate() {+ const isScheduled = priceList.status === 'scheduled'+ const namespace = isScheduled+ ? 'admin.pages.products.price_lists.unschedule_confirm'+ : 'admin.pages.products.price_lists.deactivate_confirm'+ const ok = await confirm({+ title: t(`${namespace}.title`),+ message: t(`${namespace}.message`, { name: priceList.name }),+ // Not destructive — flips status; primary confirm button keeps default styling.+ confirmLabel: t(+ isScheduled+ ? 'admin.pages.products.price_lists.unschedule'+ : 'admin.pages.products.price_lists.deactivate',+ ),+ })+ if (!ok) return+ deactivate.mutate()+ }++ async function handleActivate(willSchedule: boolean) {+ const startsAt = priceList.starts_at ? formatStoreDateTime(priceList.starts_at) : ''+ const endsAt = priceList.ends_at ? formatStoreDateTime(priceList.ends_at) : ''+ const ok = await confirm({+ title: t(+ willSchedule+ ? 'admin.pages.products.price_lists.schedule_confirm.title'+ : 'admin.pages.products.price_lists.activate_confirm.title',+ ),+ message: willSchedule+ ? t('admin.pages.products.price_lists.schedule_confirm.message', {+ name: priceList.name,+ starts_at: startsAt,+ })+ : t(+ endsAt+ ? 'admin.pages.products.price_lists.activate_confirm.message_with_end'+ : 'admin.pages.products.price_lists.activate_confirm.message',+ { name: priceList.name, ends_at: endsAt },+ ),+ confirmLabel: t(+ willSchedule+ ? 'admin.pages.products.price_lists.schedule'+ : 'admin.pages.products.price_lists.activate',+ ),+ })+ if (!ok) return+ activate.mutate()+ }++ if (isActive) {+ return (+ <Can I="update" a={Subject.PriceList}>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={handleDeactivate}+ disabled={deactivate.isPending}+ >+ {priceList.status === 'scheduled' ? (+ <CalendarOffIcon className="size-4" />+ ) : (+ <PauseIcon className="size-4" />+ )}+ {t(+ priceList.status === 'scheduled'+ ? 'admin.pages.products.price_lists.unschedule'+ : 'admin.pages.products.price_lists.deactivate',+ )}+ </Button>+ </Can>+ )+ }++ const willSchedule = !!priceList.starts_at && new Date(priceList.starts_at) > new Date()+ return (+ <Can I="update" a={Subject.PriceList}>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => handleActivate(willSchedule)}+ disabled={activate.isPending}+ >+ <PlayIcon className="size-4" />+ {willSchedule+ ? t('admin.pages.products.price_lists.schedule')+ : t('admin.pages.products.price_lists.activate')}+ </Button>+ </Can>+ )+}++// =============================================================================+// Main column — Rules+// =============================================================================++type RulesArray = ReturnType<typeof useFieldArray<PriceListFormValues, 'rules', '_key'>>++function RulesCard({+ form,+ rulesArray,+}: {+ form: UseFormReturn<PriceListFormValues>+ rulesArray: RulesArray+}) {+ const { t } = useTranslation()+ // Rule types come from the live price list (preferred — that's the+ // authoritative scope for "what's available here"). When that's missing+ // (create mode), we'll still get the same registry list because the+ // backend uses a single global `Spree.pricing.rules`.+ const { data: typesData } = usePriceRuleTypes()+ const [pickerOpen, setPickerOpen] = useState(false)+ const [editingIndex, setEditingIndex] = useState<number | null>(null)++ const types = typesData?.data ?? []+ const watchedRules = (form.watch('rules') ?? []) as PriceRuleFormDraft[]++ return (+ <Card>+ <CardHeader>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <CardTitle>{t('admin.pages.products.price_lists.rules_section')}</CardTitle>+ <p className="text-sm text-muted-foreground">+ {t('admin.pages.products.price_lists.rules_help')}+ </p>+ </div>+ <Controller+ name="match_policy"+ control={form.control}+ render={({ field }) => {+ const items = MATCH_POLICIES.map((value) => ({+ value,+ label: t(`admin.fields.price_list.match_policy.${value}`),+ }))+ return (+ <Select items={items as never} value={field.value} onValueChange={field.onChange}>+ <SelectTrigger data-size="sm" className="w-auto">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {items.map((o) => (+ <SelectItem key={o.value} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+ }}+ />+ </div>+ </CardHeader>+ <CardContent>+ <div className="space-y-2">+ {rulesArray.fields.length === 0 ? (+ <p className="text-sm text-muted-foreground">+ {t('admin.pages.products.price_lists.rules_empty')}+ </p>+ ) : (+ rulesArray.fields.map((field, index) => (+ <RuleRow+ key={field._key}+ draft={(watchedRules[index] ?? field) as unknown as PriceRuleFormDraft}+ onEdit={() => setEditingIndex(index)}+ onRemove={() => rulesArray.remove(index)}+ />+ ))+ )}+ <Can I="create" a={Subject.PriceRule}>+ <Button type="button" variant="outline" size="sm" onClick={() => setPickerOpen(true)}>+ <PlusIcon className="size-4" />+ {t('admin.pages.products.price_lists.add_rule')}+ </Button>+ </Can>+ </div>++ {pickerOpen && (+ <RulePickerSheet+ types={types}+ open+ onOpenChange={(o) => !o && setPickerOpen(false)}+ onPicked={(type) => {+ const draft = ruleDraftFromType(type)+ rulesArray.append(draft)+ setPickerOpen(false)+ // Newly-appended index is the OLD length (append happens after+ // we read .fields), which is exactly the right index for the+ // edit sheet to point at.+ setEditingIndex(rulesArray.fields.length)+ }}+ />+ )}++ {editingIndex !== null && rulesArray.fields[editingIndex] && (+ <RuleEditSheet+ draft={+ (watchedRules[editingIndex] ??+ rulesArray.fields[editingIndex]) as unknown as PriceRuleFormDraft+ }+ open+ onOpenChange={(o) => !o && setEditingIndex(null)}+ onSave={(next) => rulesArray.update(editingIndex, next)}+ />+ )}+ </CardContent>+ </Card>+ )+}++function RuleRow({+ draft,+ onEdit,+ onRemove,+}: {+ draft: PriceRuleFormDraft+ onEdit: () => void+ onRemove: () => void+}) {+ const { t } = useTranslation()+ const confirm = useConfirm()++ async function handleRemove(e: React.MouseEvent) {+ e.stopPropagation()+ const ok = await confirm({+ title: t('admin.pages.products.price_lists.remove_rule_confirm.title'),+ message: t('admin.pages.products.price_lists.remove_rule_confirm.message'),+ variant: 'destructive',+ confirmLabel: t('admin.actions.remove'),+ })+ if (!ok) return+ onRemove()+ }++ return (+ <div className="flex w-full items-stretch rounded-md border bg-card hover:bg-muted/50">+ <button+ type="button"+ onClick={onEdit}+ className="min-w-0 flex-1 px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-l-md"+ >+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">{draft.label}</span>+ <PencilIcon className="size-3 text-muted-foreground" />+ </div>+ <RuleSummary draft={draft} />+ </button>+ <Can I="destroy" a={Subject.PriceRule}>+ <div className="flex items-center pr-1.5">+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ onClick={handleRemove}+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"+ >+ <TrashIcon className="size-4" />+ </Button>+ </div>+ </Can>+ </div>+ )+}++// Preference keys that are surfaced via display embeds elsewhere on the+// draft. We skip them in the schema walk below so the row preview reads+// "VIPs, Wholesale" via the embed instead of "Customer group ids: cg_…".+const PREFS_SHOWN_VIA_EMBED = new Set(['customer_group_ids', 'user_ids'])++function RuleSummary({ draft }: { draft: PriceRuleFormDraft }) {+ const { t } = useTranslation()+ const parts: string[] = []++ // Embeds first — these are the human-readable name lists set by the+ // per-rule editors (customer-group autocomplete, customer autocomplete).+ const groups = nameList(draft.customer_groups, (g) => g.name ?? g.id, t)+ if (groups) parts.push(groups)+ const customers = nameList(draft.customers, (c) => c.email ?? c.id, t)+ if (customers) parts.push(customers)++ // Fall back to the generic preferences dump for everything else+ // (Volume Rule's min_quantity, etc.). Skip keys already covered above.+ for (const field of draft.preference_schema ?? []) {+ if (PREFS_SHOWN_VIA_EMBED.has(field.key)) continue+ const value = draft.preferences?.[field.key]+ if (value === null || value === undefined || value === '') continue+ if (Array.isArray(value) && value.length === 0) continue+ parts.push(`${humanize(field.key)}: ${formatPreferenceValue(value, t)}`)+ }++ if (parts.length === 0) {+ return (+ <div className="truncate text-xs text-muted-foreground">+ {draft.description || t('admin.pages.products.price_lists.rule_click_to_configure')}+ </div>+ )+ }+ return <div className="truncate text-xs text-muted-foreground">{parts.join(' · ')}</div>+}++/**+ * Joins up to 3 names; collapses the tail into "+N more". Returns null+ * when the embed is missing/empty — caller falls back to the preferences+ * dump.+ */+type Translator = (key: string, options?: Record<string, unknown>) => string++function nameList<T>(+ items: T[] | undefined,+ getLabel: (item: T) => string,+ t: Translator,+): string | null {+ if (!items?.length) return null+ const labels = items.map(getLabel).filter(Boolean)+ if (labels.length === 0) return null+ if (labels.length <= 3) return labels.join(', ')+ return t('admin.pages.products.price_lists.rule_name_overflow', {+ names: labels.slice(0, 3).join(', '),+ count: labels.length - 3,+ })+}++function formatPreferenceValue(value: unknown, t: Translator): string {+ if (Array.isArray(value)) return value.join(', ')+ if (typeof value === 'boolean') return t(value ? 'admin.common.yes' : 'admin.common.no')+ return String(value)+}++function humanize(key: string): string {+ const spaced = key.replace(/_/g, ' ').trim()+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)+}++function RulePickerSheet({+ types,+ open,+ onOpenChange,+ onPicked,+}: {+ types: ResourceTypeDefinition[]+ open: boolean+ onOpenChange: (open: boolean) => void+ onPicked: (type: ResourceTypeDefinition) => void+}) {+ const { t } = useTranslation()+ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent>+ <SheetHeader>+ <SheetTitle>{t('admin.pages.products.price_lists.add_rule')}</SheetTitle>+ <SheetDescription>{t('admin.pages.products.price_lists.add_rule_help')}</SheetDescription>+ </SheetHeader>+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-4">+ {types.length === 0 ? (+ <p className="text-sm text-muted-foreground">+ {t('admin.pages.products.price_lists.rule_types_empty')}+ </p>+ ) : (+ types.map((tt) => (+ <button+ key={tt.type}+ type="button"+ onClick={() => onPicked(tt)}+ className="flex flex-col items-start rounded-md border p-3 text-left transition-colors hover:bg-muted/50"+ >+ <span className="text-sm font-medium">{tt.label}</span>+ {tt.description && (+ <span className="text-xs text-muted-foreground">{tt.description}</span>+ )}+ </button>+ ))+ )}+ </div>+ </SheetContent>+ </Sheet>+ )+}++function RuleEditSheet({+ draft,+ open,+ onOpenChange,+ onSave,+}: {+ draft: PriceRuleFormDraft+ open: boolean+ onOpenChange: (open: boolean) => void+ onSave: (next: PriceRuleFormDraft) => void+}) {+ const { t } = useTranslation()+ const onClose = () => onOpenChange(false)+ const ctx: PriceRuleEditorContext = { draft, onSave, onClose }++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent>+ <SheetHeader>+ <SheetTitle>{draft.label}</SheetTitle>+ <SheetDescription>+ {draft.description || t('admin.pages.products.price_lists.rule_default_description')}+ </SheetDescription>+ </SheetHeader>+ <Slot+ name={ruleFormSlot(draft.type)}+ context={ctx}+ fallback={<DefaultRuleEditor {...ctx} />}+ />+ </SheetContent>+ </Sheet>+ )+}++/**+ * Generic preferences editor used when a rule type doesn't ship its own+ * editor. Works for VolumeRule (integer min/max inputs) and any future+ * rule whose configuration fits the `<PreferencesForm>` shape.+ */+function DefaultRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {+ const { t } = useTranslation()+ const [values, setValues] = useState<Record<string, unknown>>(draft.preferences ?? {})+ // Re-seed when the user switches between rules without closing.+ useEffect(() => {+ setValues(draft.preferences ?? {})+ }, [draft])++ const hasPreferences = !!draft.preference_schema?.length++ function handleSave() {+ onSave({ ...draft, preferences: values })+ onClose()+ }++ return (+ <EditorShell+ onSave={handleSave}+ onCancel={onClose}+ pending={false}+ saveDisabled={!hasPreferences && draft.preferences == null}+ >+ {hasPreferences ? (+ <PreferencesForm schema={draft.preference_schema} values={values} onChange={setValues} />+ ) : (+ <p className="text-sm text-muted-foreground">+ {t('admin.pages.products.price_lists.rule_no_options')}+ </p>+ )}+ </EditorShell>+ )+}++// =============================================================================+// Products card — inline multi-autocomplete + link to spreadsheet+// =============================================================================++/**+ * Products that belong to the price list. The picker writes directly to+ * the form's `product_ids` field — on Save the whole list ships in the+ * same PATCH that handles name, schedule, and rules. No separate+ * add/remove endpoints, no sheet.+ *+ * The spreadsheet for filling in the actual amounts is rendered as a+ * sibling card below, so adding a product here causes its variant rows+ * to appear (after Save) in the Prices card without any navigation.+ */+function ProductsCard({ form }: { form: UseFormReturn<PriceListFormValues> }) {+ const { t } = useTranslation()+ const productIds = form.watch('product_ids')++ return (+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.products.price_lists.products_section')}</CardTitle>+ <p className="mt-1 text-xs text-muted-foreground">+ {t('admin.pages.products.price_lists.products_help')}+ </p>+ </CardHeader>+ <CardContent>+ <Controller+ name="product_ids"+ control={form.control}+ render={({ field }) => (+ <ResourceMultiAutocomplete+ queryKey="price-list-products"+ value={field.value}+ onChange={field.onChange}+ search={(q) => adminClient.products.list({ name_cont: q, limit: 10, sort: 'name' })}+ hydrate={(ids) => adminClient.products.list({ id_in: ids, limit: ids.length })}+ getOptionLabel={(p) => p.name ?? p.id}+ placeholder={t('admin.pages.products.price_lists.products_search_placeholder')}+ emptyText={t('admin.pages.products.price_lists.products_empty_search')}+ />+ )}+ />+ {productIds.length > 0 && (+ <p className="mt-2 text-xs text-muted-foreground">+ {t('admin.pages.products.price_lists.products_selected', {+ count: productIds.length,+ })}+ </p>+ )}+ </CardContent>+ </Card>+ )+}++function PricesCard({ priceList }: { priceList: PriceList }) {+ const { t } = useTranslation()+ const [editorOpen, setEditorOpen] = useState(false)+ const count = priceList.prices_count ?? 0++ return (+ <>+ <Card>+ <CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">+ <div>+ <CardTitle>{t('admin.common.prices')}</CardTitle>+ <p className="mt-1 text-xs text-muted-foreground">+ {t('admin.pages.products.price_lists.prices_help', { count })}+ </p>+ </div>+ <Button type="button" size="sm" variant="outline" onClick={() => setEditorOpen(true)}>+ <TableIcon className="mr-1 size-4" />+ {t('admin.pages.products.price_lists.edit_prices_cta')}+ </Button>+ </CardHeader>+ </Card>+ <BulkPriceEditorDialog+ open={editorOpen}+ onOpenChange={setEditorOpen}+ scope={{ kind: 'price_list', priceList }}+ />+ </>+ )+}diff --git a/packages/admin/src/components/spree/price-list-editors/register.ts b/packages/admin/src/components/spree/price-list-editors/register.tsnew file mode 100644index 0000000000..1c47c2fa35--- /dev/null+++ b/packages/admin/src/components/spree/price-list-editors/register.ts@@ -0,0 +1,29 @@+import { registerSlot } from '@/lib/slot-registry'+import { CustomerRuleEditor } from './rule-customer'+import { CustomerGroupRuleEditor } from './rule-customer-group'+import { ruleFormSlot } from './types'++/**+ * Built-in editors for price rules whose configuration goes beyond a+ * simple integer / boolean / text preference. Imported once for its+ * side effects from the price-list detail route — extensions can+ * call `removeSlot(name, 'builtin')` to replace any of these with+ * their own.+ *+ * VolumeRule's two integer preferences (`min_quantity`, `max_quantity`)+ * render fine via the generic `<PreferencesForm>` fallback, so it+ * doesn't need a custom editor here.+ */++// `user_rule` is the legacy wire shorthand for Spree::PriceRules::UserRule —+// the SPA calls it "Customer rule" but the wire name and `user_ids`+// preference are unchanged for backwards compatibility.+registerSlot(ruleFormSlot('user_rule'), {+ id: 'builtin',+ component: CustomerRuleEditor,+})++registerSlot(ruleFormSlot('customer_group_rule'), {+ id: 'builtin',+ component: CustomerGroupRuleEditor,+})diff --git a/packages/admin/src/components/spree/price-list-editors/rule-customer-group.tsx b/packages/admin/src/components/spree/price-list-editors/rule-customer-group.tsxnew file mode 100644index 0000000000..8588d7df6f--- /dev/null+++ b/packages/admin/src/components/spree/price-list-editors/rule-customer-group.tsx@@ -0,0 +1,47 @@+import type { CustomerGroup } from '@spree/admin-sdk'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { EditorShell } from '@/components/spree/promotion-editors/editor-shell'+import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { customerGroupAutocompleteProps } from '@/hooks/use-customer-groups'+import type { PriceRuleEditorContext } from './types'++export function CustomerGroupRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {+ const { t } = useTranslation()+ const [groupIds, setGroupIds] = useState<string[]>(+ () => (draft.preferences?.customer_group_ids ?? []) as string[],+ )+ // Display-only embed echoed back onto the draft so the row summary+ // can render group names instead of prefixed IDs. Stripped at payload+ // time (see priceListValuesToParams).+ const [customerGroups, setCustomerGroups] = useState<CustomerGroup[]>(draft.customer_groups ?? [])++ function handleSave() {+ onSave({+ ...draft,+ preferences: { ...draft.preferences, customer_group_ids: groupIds },+ customer_groups: customerGroups,+ })+ onClose()+ }++ return (+ <EditorShell onSave={handleSave} onCancel={onClose} pending={false}>+ <FieldGroup>+ <Field>+ <FieldLabel>{t('admin.fields.price_rule.customer_groups.label')}</FieldLabel>+ <ResourceMultiAutocomplete+ {...customerGroupAutocompleteProps('price-rule-customer-groups')}+ value={groupIds}+ onChange={setGroupIds}+ onResolvedOptionsChange={setCustomerGroups}+ />+ <p className="text-xs text-muted-foreground">+ {t('admin.fields.price_rule.customer_groups.help')}+ </p>+ </Field>+ </FieldGroup>+ </EditorShell>+ )+}diff --git a/packages/admin/src/components/spree/price-list-editors/rule-customer.tsx b/packages/admin/src/components/spree/price-list-editors/rule-customer.tsxnew file mode 100644index 0000000000..0da531d809--- /dev/null+++ b/packages/admin/src/components/spree/price-list-editors/rule-customer.tsx@@ -0,0 +1,51 @@+import type { Customer } from '@spree/admin-sdk'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { EditorShell } from '@/components/spree/promotion-editors/editor-shell'+import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { customerAutocompleteProps } from '@/hooks/use-customers'+import type { PriceRuleEditorContext } from './types'++/**+ * Customer picker for `Spree::PriceRules::UserRule`. The preference key+ * is still `user_ids` on the wire (backend stays unchanged for backwards+ * compatibility); only the SPA surface reads "Customer".+ */+export function CustomerRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {+ const { t } = useTranslation()+ const [customerIds, setCustomerIds] = useState<string[]>(+ () => (draft.preferences?.user_ids ?? []) as string[],+ )+ // Display-only embed echoed back onto the draft so RuleSummary can+ // render customer names instead of prefixed IDs. Stripped at payload time.+ const [customers, setCustomers] = useState<Customer[]>(draft.customers ?? [])++ function handleSave() {+ onSave({+ ...draft,+ preferences: { ...draft.preferences, user_ids: customerIds },+ customers,+ })+ onClose()+ }++ return (+ <EditorShell onSave={handleSave} onCancel={onClose} pending={false}>+ <FieldGroup>+ <Field>+ <FieldLabel>{t('admin.fields.price_rule.customers.label')}</FieldLabel>+ <ResourceMultiAutocomplete+ {...customerAutocompleteProps('price-rule-customers')}+ value={customerIds}+ onChange={setCustomerIds}+ onResolvedOptionsChange={setCustomers}+ />+ <p className="text-xs text-muted-foreground">+ {t('admin.fields.price_rule.customers.help')}+ </p>+ </Field>+ </FieldGroup>+ </EditorShell>+ )+}diff --git a/packages/admin/src/components/spree/price-list-editors/status-badge.tsx b/packages/admin/src/components/spree/price-list-editors/status-badge.tsxnew file mode 100644index 0000000000..908dc85529--- /dev/null+++ b/packages/admin/src/components/spree/price-list-editors/status-badge.tsx@@ -0,0 +1,33 @@+import type { PriceList } from '@spree/admin-sdk'+import { useTranslation } from 'react-i18next'+import { Badge } from '@/components/ui/badge'++// `scheduled` collapses into the active treatment whenever the date+// range puts it live now — mirrors the legacy admin's+// `price_list_status_badge` helper.+const STATUS_STYLES = {+ active: { className: 'bg-emerald-100 text-emerald-900 hover:bg-emerald-100' },+ scheduled: { className: 'bg-sky-100 text-sky-900 hover:bg-sky-100' },+ inactive: { variant: 'secondary' as const },+ draft: { variant: 'outline' as const },+} as const++type PriceListStatus = keyof typeof STATUS_STYLES++function normalizeStatus(value: unknown): PriceListStatus {+ return typeof value === 'string' && value in STATUS_STYLES ? (value as PriceListStatus) : 'draft'+}++export function PriceListStatusBadge({ priceList }: { priceList: PriceList }) {+ const { t } = useTranslation()+ const raw = normalizeStatus(priceList.status)+ // `scheduled` collapses into the active treatment whenever the date+ // range puts it live now. Keep `inactive` distinct even when the API+ // reports a stale `currently_active: true`.+ const status: PriceListStatus = priceList.currently_active && raw !== 'inactive' ? 'active' : raw++ const style = STATUS_STYLES[status]+ const label = t(`admin.fields.price_list.status.${status}`)+ if ('variant' in style) return <Badge variant={style.variant}>{label}</Badge>+ return <Badge className={style.className}>{label}</Badge>+}diff --git a/packages/admin/src/components/spree/price-list-editors/types.ts b/packages/admin/src/components/spree/price-list-editors/types.tsnew file mode 100644index 0000000000..be53f0ab42--- /dev/null+++ b/packages/admin/src/components/spree/price-list-editors/types.ts@@ -0,0 +1,23 @@+import type { PriceRuleFormDraft } from '@/schemas/price-list'++/**+ * Slot context for a price rule editor. Editors mutate the draft+ * locally and call `onSave(next)` to write back to the parent form;+ * the parent persists everything via a single `PATCH /price_lists`+ * when the user hits Save on the page header.+ *+ * Slot key: `price_list.rule_form.<draft.type>` (where `draft.type`+ * is the wire shorthand — e.g. `user_rule`, `customer_group_rule`,+ * `volume_rule`).+ */+export interface PriceRuleEditorContext {+ draft: PriceRuleFormDraft+ onSave: (next: PriceRuleFormDraft) => void+ onClose: () => void+}++const PRICE_RULE_FORM_SLOT_PREFIX = 'price_list.rule_form.'++export function ruleFormSlot(key: string): string {+ return `${PRICE_RULE_FORM_SLOT_PREFIX}${key}`+}diff --git a/packages/admin/src/components/spree/products/inventory-section.tsx b/packages/admin/src/components/spree/products/inventory-section.tsxindex 59cb755f84..5c763cf324 100644--- a/packages/admin/src/components/spree/products/inventory-section.tsx+++ b/packages/admin/src/components/spree/products/inventory-section.tsx@@ -4,7 +4,13 @@ import { ExternalLinkIcon } from 'lucide-react'import { useMemo } from 'react'import { Controller, type UseFormReturn, useWatch } from 'react-hook-form'import { useTranslation } from 'react-i18next'-import { DataGrid, NumberCell, ReadOnlyCell, SwitchCell } from '@/components/spree/data-grid'+import {+ DataGrid,+ editableRowIndex,+ NumberCell,+ ReadOnlyCell,+ SwitchCell,+} from '@/components/spree/data-grid'import type { ProductFormValues } from '@/schemas/product'interface InventoryRow {@@ -174,18 +180,3 @@ export function InventorySection({ form, storeId, hasVariants }: InventorySectio/>)}--// Counts editable (non-header) rows up to and including the given row id so the-// cell at that position has stable grid coords that exclude header rows.-function editableRowIndex<T extends { kind: 'header' | 'item'; id: string }>(- rows: ReadonlyArray<{ id: string; original: T }>,- rowId: string,-): number {- let i = 0- for (const row of rows) {- if (row.original.kind !== 'item') continue- if (row.id === rowId) return i- i++- }- return i-}diff --git a/packages/admin/src/hooks/use-price-lists.ts b/packages/admin/src/hooks/use-price-lists.tsnew file mode 100644index 0000000000..89fcae5a86--- /dev/null+++ b/packages/admin/src/hooks/use-price-lists.ts@@ -0,0 +1,95 @@+import type { PriceList, PriceListCreateParams, PriceListUpdateParams } from '@spree/admin-sdk'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import { adminClient } from '@/client'+import { useResourceMutation } from '@/hooks/use-resource-mutation'++export const priceListsQueryKey = ['price-lists'] as const++export function priceListQueryKey(id: string, expand?: string[]) {+ return expand?.length+ ? (['price-lists', id, { expand }] as const)+ : (['price-lists', id] as const)+}++export function usePriceList(id: string | undefined, expand?: string[]) {+ return useQuery({+ queryKey: id ? priceListQueryKey(id, expand) : ['price-lists', 'noop'],+ queryFn: () => adminClient.priceLists.get(id as string, { expand }),+ enabled: !!id,+ })+}++export function useCreatePriceList() {+ return useResourceMutation<PriceList, Error, PriceListCreateParams>({+ mutationFn: (params) => adminClient.priceLists.create(params),+ invalidate: [priceListsQueryKey],+ successMessage: 'Price list created',+ errorMessage: 'Failed to create price list',+ })+}++export function useUpdatePriceList(id: string) {+ return useResourceMutation<PriceList, Error, PriceListUpdateParams>({+ mutationFn: (params) => adminClient.priceLists.update(id, params),+ invalidate: [priceListsQueryKey, priceListQueryKey(id)],+ successMessage: 'Price list updated',+ errorMessage: 'Failed to update price list',+ })+}++export function useDeletePriceList() {+ const queryClient = useQueryClient()++ return useResourceMutation<void, Error, string>({+ mutationFn: (id) => adminClient.priceLists.delete(id),+ invalidate: [priceListsQueryKey],+ successMessage: 'Price list deleted',+ errorMessage: 'Failed to delete price list',+ onSuccess: (_data, id) => {+ queryClient.removeQueries({ queryKey: priceListQueryKey(id) })+ },+ })+}++export function useActivatePriceList(id: string) {+ return useResourceMutation<PriceList, Error, void>({+ mutationFn: () => adminClient.priceLists.activate(id),+ invalidate: [priceListsQueryKey, priceListQueryKey(id)],+ successMessage: 'Price list activated',+ errorMessage: 'Failed to activate price list',+ })+}++export function useDeactivatePriceList(id: string) {+ return useResourceMutation<PriceList, Error, void>({+ mutationFn: () => adminClient.priceLists.deactivate(id),+ invalidate: [priceListsQueryKey, priceListQueryKey(id)],+ successMessage: 'Price list deactivated',+ errorMessage: 'Failed to deactivate price list',+ })+}++// Prices ride along on `useUpdatePriceList` — there's no separate+// mutation hook for the spreadsheet anymore.++// ---------------------------------------------------------------------------+// Price Rule type discovery+// ---------------------------------------------------------------------------+//+// Rules themselves aren't a separate REST resource — the SPA ships them+// inline on the price list `update` payload via `rules: [...]`. The+// `ruleTypes` lookup below is the one piece of separately-fetched data+// the rule editor needs: the registry of available subclasses (and their+// `preference_schema`) so the "Add rule" picker + generic preferences+// form know what to render.++const priceRuleTypesQueryKey = ['price-rule-types'] as const++export function usePriceRuleTypes() {+ return useQuery({+ queryKey: priceRuleTypesQueryKey,+ queryFn: () => adminClient.priceLists.ruleTypes(),+ // Registry is static; cache for the session.+ staleTime: Infinity,+ })+}diff --git a/packages/admin/src/hooks/use-prices.ts b/packages/admin/src/hooks/use-prices.tsnew file mode 100644index 0000000000..a287d2f90e--- /dev/null+++ b/packages/admin/src/hooks/use-prices.ts@@ -0,0 +1,21 @@+import type { PriceBulkUpsertRow } from '@spree/admin-sdk'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { adminClient } from '@/client'++/**+ * Mutation hook for the bulk-upsert endpoint behind the price spreadsheet.+ * Invalidates every `prices` query so cards that show price counts (price+ * list "N prices configured" hints, base-price grids on other surfaces)+ * refetch automatically. Toasts and form-error mapping live in the caller+ * so the spreadsheet can render its own dirty-state UI on failure.+ */+export function useBulkUpsertPrices() {+ const queryClient = useQueryClient()++ return useMutation({+ mutationFn: (params: { prices: PriceBulkUpsertRow[] }) => adminClient.prices.bulkUpsert(params),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['prices'] })+ },+ })+}diff --git a/packages/admin/src/lib/permissions.ts b/packages/admin/src/lib/permissions.tsindex 30a527e993..9207fe98d1 100644--- a/packages/admin/src/lib/permissions.ts+++ b/packages/admin/src/lib/permissions.ts@@ -25,6 +25,8 @@ export const Subject = {StockLocation: 'Spree::StockLocation',StockItem: 'Spree::StockItem',StockTransfer: 'Spree::StockTransfer',+ PriceList: 'Spree::PriceList',+ PriceRule: 'Spree::PriceRule',Promotion: 'Spree::Promotion',PromotionAction: 'Spree::PromotionAction',PromotionRule: 'Spree::PromotionRule',diff --git a/packages/admin/src/locales/en.json b/packages/admin/src/locales/en.jsonindex 471d31e004..0bc5fe6afe 100644--- a/packages/admin/src/locales/en.json+++ b/packages/admin/src/locales/en.json@@ -12,6 +12,8 @@"creating": "Creating…","delete": "Delete","deleting": "Deleting…",+ "discard": "Discard",+ "discard_changes": "Discard changes","edit": "Edit","generate": "Generate","remove": "Remove",@@ -92,7 +94,8 @@"are_you_sure": "Are you sure?","remove_question": "Remove?","deleted": "Deleted",- "unsaved_changes": "You have unsaved changes."+ "unsaved_changes": "You have unsaved changes.",+ "prices": "Prices"},"color_picker": {"no_color": "No color"@@ -226,7 +229,10 @@"state_abbr": { "label": "State / Province" },"state_name": { "label": "State / Province" },"starts_at": { "label": "Starts" },+ "ends_at": { "label": "Ends" },"expires_at": { "label": "Expires" },+ "products_count": { "label": "Products" },+ "prices_count": { "label": "Prices" },"active": { "label": "Active" },"kind": { "label": "Kind" },"amount": { "label": "Amount" },@@ -278,6 +284,7 @@},"field_type": {"label": "Type",+ "read_only_help": "The type can't be changed once values exist — switching it would leave stored values misinterpreted.","options": {"short_text": "Short text","long_text": "Long text",@@ -324,6 +331,48 @@"name": { "placeholder": "e.g. VIP customers" },"description": { "placeholder": "Optional internal description" }},+ "price_list": {+ "name": {+ "label": "Name",+ "placeholder": "e.g. EU wholesale",+ "help": "Internal label — never shown to customers."+ },+ "description": {+ "label": "Description",+ "placeholder": "Optional internal description"+ },+ "starts_at": {+ "label": "Starts",+ "placeholder": "Immediately",+ "help": "When this list becomes active. Leave blank to start immediately on activation."+ },+ "ends_at": {+ "label": "Ends",+ "placeholder": "Never",+ "help": "Leave blank for no end date."+ },+ "match_policy": {+ "label": "Match policy",+ "all": "All rules must match",+ "any": "Any rule may match"+ },+ "status": {+ "active": "Active",+ "scheduled": "Scheduled",+ "inactive": "Inactive",+ "draft": "Draft"+ }+ },+ "price_rule": {+ "customers": {+ "label": "Customers",+ "help": "Leave empty to apply this rule to every signed-in customer."+ },+ "customer_groups": {+ "label": "Customer groups",+ "help": "Leave empty to apply this rule to every customer regardless of group."+ }+ },"stock_location": {"name": { "placeholder": "Brooklyn warehouse" },"admin_name": {@@ -716,6 +765,11 @@}},"products": {+ "edit": {+ "bulk_prices": {+ "dialog_title": "Edit prices — {{name}}"+ }+ },"section_basics": "Basics","section_media": "Media","section_pricing": "Pricing",@@ -792,6 +846,105 @@"values_empty": "No values yet.","add_value": "Add option value","table": { "values": "Values" }+ },+ "price_lists": {+ "title": "Price Lists",+ "subtitle": "Targeted pricing for customer groups, regions, or volume tiers.",+ "add_cta": "New price list",+ "sheet_title_create": "Create price list",+ "sheet_title_edit": "Edit price list",+ "delete_confirm": {+ "title": "Delete price list?",+ "message": "Removing \"{{name}}\" deletes its prices. This cannot be undone."+ },+ "activate": "Activate",+ "deactivate": "Deactivate",+ "schedule": "Schedule",+ "unschedule": "Unschedule",+ "edit_prices_cta": "Edit prices",+ "add_products_cta": "Add products",+ "remove_selected": "Remove selected",+ "basics_section": "Basics",+ "schedule_section": "Schedule",+ "products_section": "Products",+ "rules_section": "Rules",+ "add_rule": "Add rule",+ "rule_click_to_configure": "Click to configure",+ "rule_no_options": "This rule has no configurable options — its presence alone applies the constraint.",+ "rule_name_overflow": "{{names}} +{{count}} more",+ "remove_rule_confirm": {+ "title": "Remove rule?",+ "message": "The rule is removed when you save the price list."+ },+ "rules_help": "Conditions that decide when this list applies. Use \"all\" to require every rule, \"any\" to take the first match.",+ "rules_empty": "No rules — this list applies to every shopper.",+ "add_rule_help": "Pick a rule type to configure.",+ "rule_types_empty": "No rule types registered.",+ "rule_default_description": "Tune the rule's parameters.",+ "products_help": "Pick the products this list applies to. Placeholder prices are created on save — fill them in below.",+ "products_search_placeholder": "Search products by name…",+ "products_empty_search": "No products match",+ "products_selected_one": "{{count}} product selected.",+ "products_selected_other": "{{count}} products selected.",+ "prices_help_one": "{{count}} price configured. Open the bulk editor to update it.",+ "prices_help_other": "{{count}} prices configured. Open the bulk editor to update them.",+ "prices_help_zero": "Pick products above to seed placeholder prices, then open the bulk editor.",+ "activate_confirm": {+ "title": "Activate price list?",+ "message": "\"{{name}}\" will apply to qualifying customers immediately and stay active until manually deactivated.",+ "message_with_end": "\"{{name}}\" will apply to qualifying customers immediately and stay active until manually deactivated or its end date ({{ends_at}})."+ },+ "schedule_confirm": {+ "title": "Schedule price list?",+ "message": "\"{{name}}\" will go live on {{starts_at}} and stay active until its end date."+ },+ "deactivate_confirm": {+ "title": "Deactivate price list?",+ "message": "\"{{name}}\" will stop applying to customers immediately. Existing orders are unaffected."+ },+ "unschedule_confirm": {+ "title": "Unschedule price list?",+ "message": "\"{{name}}\" will no longer activate on its scheduled date. You can re-schedule or activate it manually later."+ },+ "edit_prices": {+ "title": "Edit prices — {{name}}",+ "currency_label": "Currency",+ "empty": "No products in this list yet.",+ "add_products_link": "Add products",+ "columns": {+ "product": "Product",+ "variant": "Variant",+ "sku": "SKU",+ "price": "Price",+ "compare_at_price": "Compare-at price"+ },+ "variant_default": "Default",+ "grid_aria": "Variant prices",+ "search_placeholder": "Search by product, SKU, or option…",+ "price_aria": "Price for {{label}}",+ "compare_at_aria": "Compare-at price for {{label}}",+ "save_cta": "Save prices",+ "save_success_one": "Saved {{count}} price",+ "save_success_other": "Saved {{count}} prices",+ "save_failed": "Failed to save prices",+ "count_summary_one": "{{count}} price in {{currency}}",+ "count_summary_other": "{{count}} prices in {{currency}}",+ "no_matches_for_filters": "No prices match the current filters.",+ "no_matches_for_search": "No prices match \"{{search}}\".",+ "empty_pick_products": "Pick products on the price list to start setting prices.",+ "empty_no_base_prices": "No base prices yet.",+ "dirty_summary_one": "{{count}} unsaved change",+ "dirty_summary_other": "{{count}} unsaved changes",+ "discard_confirm": {+ "title": "Discard unsaved prices?",+ "message_close_one": "You have {{count}} unsaved price. Closing will discard it.",+ "message_close_other": "You have {{count}} unsaved prices. Closing will discard them.",+ "message_currency": "Switching currency will discard your unsaved prices.",+ "confirm": "Discard changes"+ }+ },+ "products_empty": "No products yet — add one to start editing prices.",+ "no_changes": "No changes to save."}},"settings": {diff --git a/packages/admin/src/nav/default.ts b/packages/admin/src/nav/default.tsindex b13c959e87..8eca26f541 100644--- a/packages/admin/src/nav/default.ts+++ b/packages/admin/src/nav/default.ts@@ -49,7 +49,7 @@ nav.add({key: 'products.price-lists',label: i18n.t('admin.nav.price_lists'),path: '/products/price-lists',- subject: Subject.Product,+ subject: Subject.PriceList,position: 100,},{diff --git a/packages/admin/src/routeTree.gen.ts b/packages/admin/src/routeTree.gen.tsindex e1076edf54..52119fc081 100644--- a/packages/admin/src/routeTree.gen.ts+++ b/packages/admin/src/routeTree.gen.ts@@ -39,6 +39,9 @@ import { Route as AuthenticatedStoreIdOrdersDraftsRouteImport } from './routes/_import { Route as AuthenticatedStoreIdOrdersOrderIdRouteImport } from './routes/_authenticated/$storeId/orders/$orderId'import { Route as AuthenticatedStoreIdCustomersGroupsRouteImport } from './routes/_authenticated/$storeId/customers/groups'import { Route as AuthenticatedStoreIdCustomersCustomerIdRouteImport } from './routes/_authenticated/$storeId/customers/$customerId'+import { Route as AuthenticatedStoreIdProductsPriceListsIndexRouteImport } from './routes/_authenticated/$storeId/products/price-lists/index'+import { Route as AuthenticatedStoreIdProductsPriceListsNewRouteImport } from './routes/_authenticated/$storeId/products/price-lists/new'+import { Route as AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRouteImport } from './routes/_authenticated/$storeId/products/price-lists/$priceListId/index'const LoginRoute = LoginRouteImport.update({id: '/login',@@ -215,6 +218,24 @@ const AuthenticatedStoreIdCustomersCustomerIdRoute =path: '/customers/$customerId',getParentRoute: () => AuthenticatedStoreIdRoute,} as any)+const AuthenticatedStoreIdProductsPriceListsIndexRoute =+ AuthenticatedStoreIdProductsPriceListsIndexRouteImport.update({+ id: '/products/price-lists/',+ path: '/products/price-lists/',+ getParentRoute: () => AuthenticatedStoreIdRoute,+ } as any)+const AuthenticatedStoreIdProductsPriceListsNewRoute =+ AuthenticatedStoreIdProductsPriceListsNewRouteImport.update({+ id: '/products/price-lists/new',+ path: '/products/price-lists/new',+ getParentRoute: () => AuthenticatedStoreIdRoute,+ } as any)+const AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute =+ AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRouteImport.update({+ id: '/products/price-lists/$priceListId/',+ path: '/products/price-lists/$priceListId/',+ getParentRoute: () => AuthenticatedStoreIdRoute,+ } as any)export interface FileRoutesByFullPath {'/': typeof AuthenticatedIndexRoute@@ -246,6 +267,9 @@ export interface FileRoutesByFullPath {'/$storeId/products/': typeof AuthenticatedStoreIdProductsIndexRoute'/$storeId/promotions/': typeof AuthenticatedStoreIdPromotionsIndexRoute'/$storeId/settings/': typeof AuthenticatedStoreIdSettingsIndexRoute+ '/$storeId/products/price-lists/new': typeof AuthenticatedStoreIdProductsPriceListsNewRoute+ '/$storeId/products/price-lists/': typeof AuthenticatedStoreIdProductsPriceListsIndexRoute+ '/$storeId/products/price-lists/$priceListId/': typeof AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute}export interface FileRoutesByTo {'/login': typeof LoginRoute@@ -275,6 +299,9 @@ export interface FileRoutesByTo {'/$storeId/products': typeof AuthenticatedStoreIdProductsIndexRoute'/$storeId/promotions': typeof AuthenticatedStoreIdPromotionsIndexRoute'/$storeId/settings': typeof AuthenticatedStoreIdSettingsIndexRoute+ '/$storeId/products/price-lists/new': typeof AuthenticatedStoreIdProductsPriceListsNewRoute+ '/$storeId/products/price-lists': typeof AuthenticatedStoreIdProductsPriceListsIndexRoute+ '/$storeId/products/price-lists/$priceListId': typeof AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute}export interface FileRoutesById {__root__: typeof rootRouteImport@@ -308,6 +335,9 @@ export interface FileRoutesById {'/_authenticated/$storeId/products/': typeof AuthenticatedStoreIdProductsIndexRoute'/_authenticated/$storeId/promotions/': typeof AuthenticatedStoreIdPromotionsIndexRoute'/_authenticated/$storeId/settings/': typeof AuthenticatedStoreIdSettingsIndexRoute+ '/_authenticated/$storeId/products/price-lists/new': typeof AuthenticatedStoreIdProductsPriceListsNewRoute+ '/_authenticated/$storeId/products/price-lists/': typeof AuthenticatedStoreIdProductsPriceListsIndexRoute+ '/_authenticated/$storeId/products/price-lists/$priceListId/': typeof AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute}export interface FileRouteTypes {fileRoutesByFullPath: FileRoutesByFullPath@@ -341,6 +371,9 @@ export interface FileRouteTypes {| '/$storeId/products/'| '/$storeId/promotions/'| '/$storeId/settings/'+ | '/$storeId/products/price-lists/new'+ | '/$storeId/products/price-lists/'+ | '/$storeId/products/price-lists/$priceListId/'fileRoutesByTo: FileRoutesByToto:| '/login'@@ -370,6 +403,9 @@ export interface FileRouteTypes {| '/$storeId/products'| '/$storeId/promotions'| '/$storeId/settings'+ | '/$storeId/products/price-lists/new'+ | '/$storeId/products/price-lists'+ | '/$storeId/products/price-lists/$priceListId'id:| '__root__'| '/_authenticated'@@ -402,6 +438,9 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/products/'| '/_authenticated/$storeId/promotions/'| '/_authenticated/$storeId/settings/'+ | '/_authenticated/$storeId/products/price-lists/new'+ | '/_authenticated/$storeId/products/price-lists/'+ | '/_authenticated/$storeId/products/price-lists/$priceListId/'fileRoutesById: FileRoutesById}export interface RootRouteChildren {@@ -622,6 +661,27 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthenticatedStoreIdCustomersCustomerIdRouteImportparentRoute: typeof AuthenticatedStoreIdRoute}+ '/_authenticated/$storeId/products/price-lists/': {+ id: '/_authenticated/$storeId/products/price-lists/'+ path: '/products/price-lists'+ fullPath: '/$storeId/products/price-lists/'+ preLoaderRoute: typeof AuthenticatedStoreIdProductsPriceListsIndexRouteImport+ parentRoute: typeof AuthenticatedStoreIdRoute+ }+ '/_authenticated/$storeId/products/price-lists/new': {+ id: '/_authenticated/$storeId/products/price-lists/new'+ path: '/products/price-lists/new'+ fullPath: '/$storeId/products/price-lists/new'+ preLoaderRoute: typeof AuthenticatedStoreIdProductsPriceListsNewRouteImport+ parentRoute: typeof AuthenticatedStoreIdRoute+ }+ '/_authenticated/$storeId/products/price-lists/$priceListId/': {+ id: '/_authenticated/$storeId/products/price-lists/$priceListId/'+ path: '/products/price-lists/$priceListId'+ fullPath: '/$storeId/products/price-lists/$priceListId/'+ preLoaderRoute: typeof AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRouteImport+ parentRoute: typeof AuthenticatedStoreIdRoute+ }}}@@ -679,6 +739,9 @@ interface AuthenticatedStoreIdRouteChildren {AuthenticatedStoreIdOrdersIndexRoute: typeof AuthenticatedStoreIdOrdersIndexRouteAuthenticatedStoreIdProductsIndexRoute: typeof AuthenticatedStoreIdProductsIndexRouteAuthenticatedStoreIdPromotionsIndexRoute: typeof AuthenticatedStoreIdPromotionsIndexRoute+ AuthenticatedStoreIdProductsPriceListsNewRoute: typeof AuthenticatedStoreIdProductsPriceListsNewRoute+ AuthenticatedStoreIdProductsPriceListsIndexRoute: typeof AuthenticatedStoreIdProductsPriceListsIndexRoute+ AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute: typeof AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute}const AuthenticatedStoreIdRouteChildren: AuthenticatedStoreIdRouteChildren = {@@ -712,6 +775,12 @@ const AuthenticatedStoreIdRouteChildren: AuthenticatedStoreIdRouteChildren = {AuthenticatedStoreIdProductsIndexRoute,AuthenticatedStoreIdPromotionsIndexRoute:AuthenticatedStoreIdPromotionsIndexRoute,+ AuthenticatedStoreIdProductsPriceListsNewRoute:+ AuthenticatedStoreIdProductsPriceListsNewRoute,+ AuthenticatedStoreIdProductsPriceListsIndexRoute:+ AuthenticatedStoreIdProductsPriceListsIndexRoute,+ AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute:+ AuthenticatedStoreIdProductsPriceListsPriceListIdIndexRoute,}const AuthenticatedStoreIdRouteWithChildren =diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/price-lists/$priceListId/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/price-lists/$priceListId/index.tsxnew file mode 100644index 0000000000..49c80af468--- /dev/null+++ b/packages/admin/src/routes/_authenticated/$storeId/products/price-lists/$priceListId/index.tsx@@ -0,0 +1,58 @@+import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { useConfirm } from '@/components/spree/confirm-dialog'+import { PriceListForm } from '@/components/spree/price-list-editors/price-list-form'+import { useDeletePriceList, usePriceList, useUpdatePriceList } from '@/hooks/use-price-lists'++export const Route = createFileRoute('/_authenticated/$storeId/products/price-lists/$priceListId/')(+ {+ component: EditPriceListPage,+ },+)++function EditPriceListPage() {+ const { t } = useTranslation()+ const { storeId, priceListId } = Route.useParams()+ const navigate = useNavigate()+ // Pull rules inline via expand — there's no separate /price_rules+ // endpoint anymore; rules ship as a nested array on the price list.+ const { data: priceList } = usePriceList(priceListId, ['price_rules'])+ const updateMutation = useUpdatePriceList(priceListId)+ const deleteMutation = useDeletePriceList()+ const confirm = useConfirm()++ async function onDelete() {+ const ok = await confirm({+ title: t('admin.pages.products.price_lists.delete_confirm.title'),+ message: t('admin.pages.products.price_lists.delete_confirm.message', {+ name: priceList?.name ?? '',+ }),+ variant: 'destructive',+ confirmLabel: t('admin.actions.delete'),+ })+ if (!ok) return+ try {+ await deleteMutation.mutateAsync(priceListId)+ } catch (err) {+ // Surface failure as a toast and stay on the page — navigating away+ // would tell the user the row vanished when it didn't.+ toast.error(err instanceof Error ? err.message : t('admin.errors.failed_to_delete'))+ return+ }+ navigate({ to: '/$storeId/products/price-lists', params: { storeId } })+ }++ return (+ <PriceListForm+ mode="edit"+ priceList={priceList}+ initialRules={priceList?.price_rules}+ onSubmit={async (payload) => {+ await updateMutation.mutateAsync(payload)+ }}+ onDelete={onDelete}+ deletePending={deleteMutation.isPending}+ />+ )+}diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/price-lists/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/price-lists/index.tsxnew file mode 100644index 0000000000..c8573a8b6c--- /dev/null+++ b/packages/admin/src/routes/_authenticated/$storeId/products/price-lists/index.tsx@@ -0,0 +1,95 @@+import type { PriceList } from '@spree/admin-sdk'+import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { PlusIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { adminClient } from '@/client'+import { Can } from '@/components/spree/can'+import { useConfirm } from '@/components/spree/confirm-dialog'+import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource-table'+import { RowActions } from '@/components/spree/row-actions'+import { useRowClickBridge } from '@/components/spree/row-click-bridge'+import { Button } from '@/components/ui/button'+import { useDeletePriceList } from '@/hooks/use-price-lists'+import { Subject } from '@/lib/permissions'+import { usePermissions } from '@/providers/permission-provider'+import '@/tables/price-lists'++export const Route = createFileRoute('/_authenticated/$storeId/products/price-lists/')({+ validateSearch: resourceSearchSchema,+ component: PriceListsPage,+})++function PriceListsPage() {+ const { t } = useTranslation()+ const { storeId } = Route.useParams()+ const search = Route.useSearch()+ const navigate = useNavigate()+ const confirm = useConfirm()+ const deleteMutation = useDeletePriceList()+ const { permissions } = usePermissions()++ function openEdit(id: string) {+ navigate({+ to: '/$storeId/products/price-lists/$priceListId',+ params: { storeId, priceListId: id },+ })+ }++ function openCreate() {+ navigate({ to: '/$storeId/products/price-lists/new', params: { storeId } })+ }++ useRowClickBridge('data-price-list-id', openEdit)++ async function handleDelete(list: PriceList) {+ const ok = await confirm({+ title: t('admin.pages.products.price_lists.delete_confirm.title'),+ message: t('admin.pages.products.price_lists.delete_confirm.message', { name: list.name }),+ variant: 'destructive',+ confirmLabel: t('admin.actions.delete'),+ })+ if (!ok) return+ try {+ await deleteMutation.mutateAsync(list.id)+ } catch (err) {+ toast.error(err instanceof Error ? err.message : t('admin.errors.failed_to_delete'))+ }+ }++ return (+ <ResourceTable<PriceList>+ tableKey="price-lists"+ queryKey="price-lists"+ queryFn={(params) => adminClient.priceLists.list(params)}+ searchParams={search}+ rowActions={(list) => (+ <RowActions+ actions={[+ { key: 'edit', onSelect: () => openEdit(list.id) },+ {+ key: 'delete',+ destructive: true,+ visible: permissions.can('destroy', Subject.PriceList),+ disabled: deleteMutation.isPending,+ onSelect: () => handleDelete(list),+ },+ ]}+ />+ )}+ actions={+ <Can I="create" a={Subject.PriceList}>+ <Button size="sm" className="h-[2.125rem]" onClick={openCreate}>+ <PlusIcon className="size-4" />+ {t('admin.pages.products.price_lists.add_cta')}+ </Button>+ </Can>+ }+ reorder={{+ onReorder: async (id, position) => {+ await adminClient.priceLists.update(id, { position })+ },+ }}+ />+ )+}diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/price-lists/new.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/price-lists/new.tsxnew file mode 100644index 0000000000..9d301fc50d--- /dev/null+++ b/packages/admin/src/routes/_authenticated/$storeId/products/price-lists/new.tsx@@ -0,0 +1,26 @@+import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { PriceListForm } from '@/components/spree/price-list-editors/price-list-form'+import { useCreatePriceList } from '@/hooks/use-price-lists'++export const Route = createFileRoute('/_authenticated/$storeId/products/price-lists/new')({+ component: NewPriceListPage,+})++function NewPriceListPage() {+ const { storeId } = Route.useParams()+ const navigate = useNavigate()+ const create = useCreatePriceList()++ return (+ <PriceListForm+ mode="create"+ onSubmit={async (payload) => {+ const list = await create.mutateAsync(payload)+ navigate({+ to: '/$storeId/products/price-lists/$priceListId',+ params: { storeId, priceListId: list.id },+ })+ }}+ />+ )+}diff --git a/packages/admin/src/schemas/price-list.ts b/packages/admin/src/schemas/price-list.tsnew file mode 100644index 0000000000..6db384315e--- /dev/null+++ b/packages/admin/src/schemas/price-list.ts@@ -0,0 +1,151 @@+import type {+ Customer,+ CustomerGroup,+ PreferenceField,+ PriceListCreateParams,+ PriceListUpdateParams,+ PriceRule,+} from '@spree/admin-sdk'+import { z } from 'zod/v4'+import { defaultPreferences } from '@/components/spree/preferences-form'+import { blankToNull } from '@/lib/form-mappers'+import { requiredMessage } from '@/lib/validation-messages'++export const MATCH_POLICIES = ['all', 'any'] as const+export type MatchPolicy = (typeof MATCH_POLICIES)[number]++/**+ * Form-state row for a price rule. Carries the editor's display fields+ * (`label`, `description`, `preference_schema`) alongside the payload+ * fields the API consumes (`type`, `preferences`, optional `id`). Closely+ * mirrors `PromotionRuleFormDraft` so the editor patterns are 1:1.+ */+export interface PriceRuleFormDraft {+ /** Stable client-side id used as a React key while the row has no server id. */+ _localId: string+ /** Present once the row has been persisted. */+ id?: string+ /** Wire shorthand — `volume_rule`, `market_rule`, etc. */+ type: string+ label: string+ description?: string | null+ preference_schema: PreferenceField[]+ preferences: Record<string, unknown>+ /**+ * Display-only embeds the per-rule editors set when the user picks+ * records via autocomplete. Used by `RuleSummary` so the row preview+ * reads "Customer groups: VIPs, Wholesale" instead of "cg_…". Never+ * sent to the API — `priceListValuesToParams` strips them.+ */+ customers?: Customer[]+ customer_groups?: CustomerGroup[]+}++const priceRuleDraftSchema: z.ZodType<PriceRuleFormDraft> = z.object({+ _localId: z.string(),+ id: z.string().optional(),+ type: z.string().min(1),+ label: z.string(),+ description: z.string().nullable().optional(),+ preference_schema: z.array(z.any()).default([]),+ preferences: z.record(z.string(), z.unknown()).default({}),+ customers: z.array(z.any()).optional(),+ customer_groups: z.array(z.any()).optional(),+}) as unknown as z.ZodType<PriceRuleFormDraft>++export const priceListFormSchema = z+ .object({+ name: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('price_list.name') }),+ description: z.string().trim().optional(),+ starts_at: z.string().optional().nullable(),+ ends_at: z.string().optional().nullable(),+ match_policy: z.enum(MATCH_POLICIES).default('all'),+ rules: z.array(priceRuleDraftSchema).default([]),+ /**+ * Prefixed product ids in the list. The server reconciles this set+ * on every PATCH — adds placeholder prices for new ids, drops prices+ * for removed ones — so the form ships the full desired set.+ */+ product_ids: z.array(z.string()).default([]),+ })+ .refine(+ (v) => {+ if (!v.starts_at || !v.ends_at) return true+ return new Date(v.starts_at) < new Date(v.ends_at)+ },+ { path: ['ends_at'], error: 'Must be after start date.' },+ )++export type PriceListFormValues = z.infer<typeof priceListFormSchema>++export const PRICE_LIST_DEFAULTS: PriceListFormValues = {+ name: '',+ description: '',+ starts_at: null,+ ends_at: null,+ match_policy: 'all',+ rules: [],+ product_ids: [],+}++export function priceListValuesToParams(+ v: PriceListFormValues,+): PriceListCreateParams & PriceListUpdateParams {+ return {+ name: v.name,+ description: blankToNull(v.description),+ starts_at: v.starts_at || null,+ ends_at: v.ends_at || null,+ match_policy: v.match_policy,+ rules: v.rules.map(ruleDraftToPayload),+ product_ids: v.product_ids,+ }+}++let nextLocalId = 0+function newLocalId(): string {+ nextLocalId += 1+ return `pl-rule-${nextLocalId}`+}++/** Materializes a draft from an existing server-side rule. */+export function ruleDraftFromRule(rule: PriceRule): PriceRuleFormDraft {+ return {+ _localId: rule.id,+ id: rule.id,+ type: rule.type,+ label: rule.label,+ description: rule.description,+ preference_schema: rule.preference_schema,+ preferences: rule.preferences,+ }+}++/** Materializes a fresh draft from a registry type definition. */+export function ruleDraftFromType(type: {+ type: string+ label: string+ description?: string | null+ preference_schema: PreferenceField[]+}): PriceRuleFormDraft {+ return {+ _localId: newLocalId(),+ type: type.type,+ label: type.label,+ description: type.description ?? null,+ preference_schema: type.preference_schema,+ preferences: defaultPreferences(type.preference_schema),+ }+}++/** Strips display-only fields before sending to the API. */+export function ruleDraftToPayload(draft: PriceRuleFormDraft) {+ return {+ id: draft.id,+ type: draft.type,+ preferences: draft.preferences,+ }+}diff --git a/packages/admin/src/tables/price-lists.tsx b/packages/admin/src/tables/price-lists.tsxnew file mode 100644index 0000000000..3d072db13a--- /dev/null+++ b/packages/admin/src/tables/price-lists.tsx@@ -0,0 +1,77 @@+import type { PriceList } from '@spree/admin-sdk'+import i18n from 'i18next'+import { TagsIcon } from 'lucide-react'+import { PriceListStatusBadge } from '@/components/spree/price-list-editors/status-badge'+import { ResourceNameCell } from '@/components/spree/resource-name-cell'+import { defineTable } from '@/lib/table-registry'++defineTable<PriceList>('price-lists', {+ title: i18n.t('admin.nav.price_lists'),+ searchParam: 'name_cont',+ searchPlaceholder: i18n.t('admin.common.search_placeholder'),+ defaultSort: { field: 'position', direction: 'asc' },+ emptyIcon: <TagsIcon className="size-8 text-muted-foreground" />,+ emptyMessage: i18n.t('admin.common.no_results'),+ columns: [+ {+ key: 'name',+ label: i18n.t('admin.fields.name.label'),+ sortable: true,+ filterable: true,+ default: true,+ render: (list) => (+ <ResourceNameCell+ id={list.id}+ dataAttr="data-price-list-id"+ name={list.name}+ secondary={list.description ?? undefined}+ />+ ),+ },+ {+ key: 'status',+ label: i18n.t('admin.fields.status.label'),+ sortable: true,+ filterable: true,+ filterType: 'enum',+ filterOptions: [+ { value: 'draft', label: i18n.t('admin.fields.price_list.status.draft') },+ { value: 'active', label: i18n.t('admin.fields.price_list.status.active') },+ { value: 'scheduled', label: i18n.t('admin.fields.price_list.status.scheduled') },+ { value: 'inactive', label: i18n.t('admin.fields.price_list.status.inactive') },+ ],+ default: true,+ render: (list) => <PriceListStatusBadge priceList={list} />,+ },+ {+ key: 'products_count',+ label: i18n.t('admin.fields.products_count.label'),+ default: true,+ render: (list) => list.products_count,+ },+ {+ key: 'prices_count',+ label: i18n.t('admin.fields.prices_count.label'),+ default: true,+ render: (list) => list.prices_count,+ },+ {+ key: 'starts_at',+ label: i18n.t('admin.fields.starts_at.label'),+ sortable: true,+ filterable: true,+ filterType: 'date',+ default: false,+ render: (list) => (list.starts_at ? new Date(list.starts_at).toLocaleDateString() : '—'),+ },+ {+ key: 'ends_at',+ label: i18n.t('admin.fields.ends_at.label'),+ sortable: true,+ filterable: true,+ filterType: 'date',+ default: false,+ render: (list) => (list.ends_at ? new Date(list.ends_at).toLocaleDateString() : '—'),+ },+ ],+})