Skip to content

armgit / spree

Public Imported from GitHub
0

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

Show each variant's price and ladder on the price list page

Damian Legawiec1dce3e3671f2
diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
index 3ce21206f4..8ce39c3b91 100644
--- a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
+++ b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
@@ -140,7 +140,7 @@ export function BulkPriceEditor({
// 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 { mutateAsync: bulkUpsertAsync, isPending: isSaving } = useBulkUpsertPrices(priceListId)
const localeForCurrency = useCurrencyLocale()
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
diff --git a/packages/dashboard/src/components/spree/catalog-price-columns.tsx b/packages/dashboard/src/components/spree/catalog-price-columns.tsx
index 81341331f8..ab104c10dc 100644
--- a/packages/dashboard/src/components/spree/catalog-price-columns.tsx
+++ b/packages/dashboard/src/components/spree/catalog-price-columns.tsx
@@ -1,4 +1,4 @@
-import type { CatalogPrice, CatalogProduct } from '@spree/admin-sdk'
+import type { CatalogPrice } from '@spree/admin-sdk'
import type { ProductMembershipRow, SubRowLayout } from '@spree/dashboard-ui'
import {
Badge,
@@ -12,6 +12,19 @@ import i18n from 'i18next'
const AGREEMENT_SOURCES = ['explicit', 'automatic'] as const
+/** Where the copy comes from: the catalog's strings, or a page's own. */
+const CATALOG_NAMESPACE = 'admin.catalogs.prices'
+
+/**
+ * A string for these columns. A page that reads them on another record — a
+ * price list's own page — supplies a namespace whose keys say "this list"
+ * where the catalog's say "this catalog", and everything it does not
+ * override falls back to the catalog's copy.
+ */
+function text(namespace: string, key: string, options?: Record<string, unknown>) {
+ return i18n.t([`${namespace}.${key}`, `${CATALOG_NAMESPACE}.${key}`], options ?? {})
+}
+
/**
* What the agreement charges, as columns on the assortment rows.
*
@@ -31,11 +44,14 @@ const CATALOG_PRICE_COLUMN_COUNT = 2
export function catalogPriceColumns({
headers,
+ namespace = CATALOG_NAMESPACE,
}: {
headers: {
price: string
source: string
}
+ /** Copy namespace; see `text`. */
+ namespace?: string
}) {
return {
columnCount: CATALOG_PRICE_COLUMN_COUNT,
@@ -52,7 +68,7 @@ export function catalogPriceColumns({
renderCells: (row: ProductMembershipRow) => (
<>
<TableCell className="text-right text-muted-foreground text-xs">
- {row.pending === 'added' ? i18n.t('admin.catalogs.prices.after_save') : null}
+ {row.pending === 'added' ? text(namespace, 'after_save') : null}
</TableCell>
<TableCell />
</>
@@ -65,9 +81,9 @@ export function catalogPriceColumns({
* through to the shop price is called out, because a merchant looking at a
* catalog has every reason to assume it prices what it lists.
*/
-function PriceSourceBadge({ source }: { source: string }) {
+function PriceSourceBadge({ source, namespace }: { source: string; namespace: string }) {
const fromAgreement = (AGREEMENT_SOURCES as readonly string[]).includes(source)
- const help = i18n.t(`admin.catalogs.prices.source_help.${source}`)
+ const help = text(namespace, `source_help.${source}`)
return (
<Tooltip>
@@ -76,7 +92,7 @@ function PriceSourceBadge({ source }: { source: string }) {
hover — the same reason the terms columns wrap theirs. */}
<button type="button" className="cursor-help rounded-sm" aria-label={help}>
<Badge variant={fromAgreement ? 'secondary' : 'outline'}>
- {i18n.t(`admin.catalogs.prices.source.${source}`)}
+ {text(namespace, `source.${source}`)}
</Badge>
</button>
</TooltipTrigger>
@@ -92,8 +108,8 @@ function PriceSourceBadge({ source }: { source: string }) {
* figures, which is a click to answer a question the row could just answer
* (docs/plans/6.0-volume-pricing.md).
*/
-function TierBadge({ price }: { price: CatalogPrice }) {
- const label = i18n.t('admin.catalogs.prices.tier_count', { count: price.break_count })
+function TierBadge({ price, namespace }: { price: CatalogPrice; namespace: string }) {
+ const label = text(namespace, 'tier_count', { count: price.break_count })
// Nothing to preview — either the resolver could not price the rungs, or
// the response predates the field (a client holding a cached page across
@@ -121,9 +137,7 @@ function TierBadge({ price }: { price: CatalogPrice }) {
heading beside a table and wraps both. A ladder is a block: stack it
and let it size to its figures. */}
<TooltipContent className="max-w-none flex-col items-stretch gap-0 px-2.5 py-2 text-left">
- <p className="mb-1.5 whitespace-nowrap font-medium">
- {i18n.t('admin.catalogs.prices.tier_preview')}
- </p>
+ <p className="mb-1.5 whitespace-nowrap font-medium">{text(namespace, 'tier_preview')}</p>
<table className="text-xs tabular-nums">
<tbody>
{/* The variant's own price is the ladder's first rung, so the
@@ -131,14 +145,14 @@ function TierBadge({ price }: { price: CatalogPrice }) {
break — otherwise the cheapest figure reads as the price. */}
<tr>
<td className="whitespace-nowrap pr-4 text-muted-foreground">
- {i18n.t('admin.catalogs.prices.tier_from', { count: 1 })}
+ {text(namespace, 'tier_from', { count: 1 })}
</td>
<td className="whitespace-nowrap text-right">{price.display_amount}</td>
</tr>
{tiers.map((tier) => (
<tr key={tier.min_quantity}>
<td className="whitespace-nowrap pr-4 text-muted-foreground">
- {i18n.t('admin.catalogs.prices.tier_from', { count: tier.min_quantity })}
+ {text(namespace, 'tier_from', { count: tier.min_quantity })}
</td>
<td className="whitespace-nowrap text-right">{tier.display_amount}</td>
</tr>
@@ -150,7 +164,7 @@ function TierBadge({ price }: { price: CatalogPrice }) {
merchant who set both would otherwise expect to see it
(docs/plans/6.0-volume-pricing.md). */}
<p className="mt-1.5 max-w-56 text-muted-foreground text-xs">
- {i18n.t('admin.catalogs.prices.tier_fixed_note')}
+ {text(namespace, 'tier_fixed_note')}
</p>
</TooltipContent>
</Tooltip>
@@ -168,8 +182,18 @@ function TierBadge({ price }: { price: CatalogPrice }) {
* @param products the server rows for this page, which carry the resolved
* per-variant prices
*/
-export function catalogVariantRows({ products }: { products: CatalogProduct[] }) {
- const byId = new Map(products.map((product) => [product.id, product.catalog_variants ?? []]))
+export function catalogVariantRows<Row extends { id: string }>({
+ products,
+ variantsOf,
+ namespace = CATALOG_NAMESPACE,
+}: {
+ products: Row[]
+ /** The resolved per-variant prices a server row carries. */
+ variantsOf: (product: Row) => CatalogPrice[] | undefined
+ /** Copy namespace; see `text`. */
+ namespace?: string
+}) {
+ const byId = new Map(products.map((product) => [product.id, variantsOf(product) ?? []]))
return (
row: ProductMembershipRow,
@@ -194,7 +218,7 @@ export function catalogVariantRows({ products }: { products: CatalogProduct[] })
<TableCell className="max-w-0 text-muted-foreground">
<span className="flex min-w-0 items-center gap-2 pl-11">
<span className="shrink-[1] truncate">
- {price.label ?? i18n.t('admin.catalogs.prices.variant_default')}
+ {price.label ?? text(namespace, 'variant_default')}
</span>
{price.sku && (
<span className="min-w-0 shrink-[4] truncate font-mono text-xs opacity-70">
@@ -206,11 +230,11 @@ export function catalogVariantRows({ products }: { products: CatalogProduct[] })
<TableCell className="text-right tabular-nums">
<span className="inline-flex items-center justify-end gap-1.5">
{price.display_amount}
- {price.break_count > 0 && <TierBadge price={price} />}
+ {price.break_count > 0 && <TierBadge price={price} namespace={namespace} />}
</span>
</TableCell>
<TableCell>
- <PriceSourceBadge source={price.source} />
+ <PriceSourceBadge source={price.source} namespace={namespace} />
</TableCell>
{/* The quantity-term columns and the row-action column, spanned
rather than filled: terms are stated per product, so a variant row
diff --git a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
index c4b5ff1020..2e2cc1e7ea 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
@@ -1,5 +1,10 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import type { PriceList, PriceRule, ResourceTypeDefinition } from '@spree/admin-sdk'
+import type {
+ PriceList,
+ PriceListProduct,
+ PriceRule,
+ ResourceTypeDefinition,
+} from '@spree/admin-sdk'
import {
adminClient,
Can,
@@ -28,6 +33,7 @@ import { Controller, type UseFormReturn, useFieldArray, useForm } from 'react-ho
import { useTranslation } from 'react-i18next'
import { spreeJsonLinkResolver } from '../../../lib/json-link-resolver'
import { BulkPriceEditorDialog } from '../bulk-price-editor/bulk-price-editor-dialog'
+import { catalogPriceColumns, catalogVariantRows } from '../catalog-price-columns'
import { DeferredProductMembershipCard } from '../deferred-product-membership-card'
import { PriceListCsvButtons } from '../price-list-csv-buttons'
import {
@@ -98,6 +104,9 @@ import { type PriceRuleEditorContext, ruleFormSlot } from './types'
// Public API
// =============================================================================
+/** The price columns' copy for this page: "this list" where the catalog says "this catalog". */
+const PRICE_LIST_PRICES_NAMESPACE = 'admin.pages.products.price_lists.prices'
+
interface PriceListFormProps {
mode: 'create' | 'edit'
/** Existing record (edit mode only). */
@@ -297,6 +306,25 @@ export function PriceListForm({
})
: t('admin.pages.products.price_lists.products_help')
}
+ // Each variant priced on its own row with its ladder — the
+ // catalog's reading, on the page where the ladder is edited
+ // (docs/plans/6.0-volume-pricing.md).
+ renderSubRows={(products) =>
+ catalogVariantRows<PriceListProduct>({
+ products,
+ variantsOf: (product) => product.price_list_variants,
+ namespace: PRICE_LIST_PRICES_NAMESPACE,
+ })
+ }
+ extraColumns={() =>
+ catalogPriceColumns({
+ headers: {
+ price: t(`${PRICE_LIST_PRICES_NAMESPACE}.column_price`),
+ source: t(`${PRICE_LIST_PRICES_NAMESPACE}.column_source`),
+ },
+ namespace: PRICE_LIST_PRICES_NAMESPACE,
+ })
+ }
/>
)}
</>
diff --git a/packages/dashboard/src/hooks/use-price-lists.ts b/packages/dashboard/src/hooks/use-price-lists.ts
index 72bfe61791..76fd1d28ba 100644
--- a/packages/dashboard/src/hooks/use-price-lists.ts
+++ b/packages/dashboard/src/hooks/use-price-lists.ts
@@ -78,10 +78,20 @@ export function useDeactivatePriceList(id: string) {
// flushed on Save (deferred card).
// ---------------------------------------------------------------------------
+/**
+ * The list's products, each row carrying what the list charges per variant
+ * — the same reading the catalog's assortment gets, so a ladder is visible
+ * where it is edited (docs/plans/6.0-volume-pricing.md).
+ */
export function usePriceListProducts(priceListId: string | undefined, page = 1) {
return useQuery({
queryKey: useResourceKey('price-lists', priceListId ?? 'noop', 'products', `${page}`),
- queryFn: () => listPriceListProductsPage(priceListId as string, page),
+ queryFn: () =>
+ adminClient.priceLists.products.list(priceListId as string, {
+ page,
+ limit: 25,
+ expand: ['price_list_price'],
+ }),
enabled: !!priceListId,
placeholderData: (previous) => previous,
})
diff --git a/packages/dashboard/src/hooks/use-prices.ts b/packages/dashboard/src/hooks/use-prices.ts
index 189c42999b..a0f00e9d75 100644
--- a/packages/dashboard/src/hooks/use-prices.ts
+++ b/packages/dashboard/src/hooks/use-prices.ts
@@ -15,11 +15,20 @@ import { adminClient, useResourceMutation } from '@spree/dashboard-core'
* Amounts arrive already normalized to canonical `"1234.56"` form — the editor
* converts the merchant's localized input client-side (see
* docs/plans/5.5-client-side-money-normalization.md), so no request locale.
+ *
+ * @param priceListId the list being edited, when there is one: its products
+ * card reads the rows this save writes, so that nested key is refreshed
+ * — and only that one, since refetching the list record itself would
+ * reset the page's form under a merchant's unsaved edits.
*/
-export function useBulkUpsertPrices() {
+export function useBulkUpsertPrices(priceListId?: string | null) {
return useResourceMutation<{ price_count: number }, Error, { prices: PriceBulkUpsertRow[] }>({
mutationFn: (params) => adminClient.prices.bulkUpsert(params),
- invalidate: [['prices'], ['catalogs']],
+ invalidate: [
+ ['prices'],
+ ['catalogs'],
+ ...(priceListId ? [['price-lists', priceListId, 'products']] : []),
+ ],
successMessage: false,
errorMessage: false,
})
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index e1776fa6af..6db0611368 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -3404,6 +3404,17 @@
"select_row": "تحديد المنتج",
"title": "المنتجات"
},
+ "prices": {
+ "column_price": "السعر",
+ "column_source": "المصدر",
+ "source_help": {
+ "explicit": "مبلغ مُدخل في قائمة الأسعار هذه.",
+ "automatic": "سعر المتجر مع تطبيق نسبة قائمة الأسعار هذه.",
+ "base": "سعر المتجر العادي. هذه القائمة لا تسعّر هذا المنتج."
+ },
+ "tier_fixed_note": "لا تنطبق نسبة تعديل هنا. هذه المستويات تحدد السعر.",
+ "tier_preview": "ما تفرضه هذه القائمة"
+ },
"products_help": "اختر المنتجات التي تنطبق عليها هذه القائمة. تُنشأ أسعار مؤقتة عند الحفظ — املأها عبر «تعديل الأسعار».",
"products_help_with_prices_one": "اختر المنتجات التي تنطبق عليها هذه القائمة. تم ضبط سعر واحد ({{count}}) — استخدم «تعديل الأسعار» لتحديثه.",
"products_help_with_prices_other": "اختر المنتجات التي تنطبق عليها هذه القائمة. تم ضبط {{count}} سعر — استخدم «تعديل الأسعار» لتحديثها.",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 951fa9ef73..84db8d7c4c 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -3387,6 +3387,17 @@
"select_row": "Produkt auswählen",
"title": "Produkte"
},
+ "prices": {
+ "column_price": "Preis",
+ "column_source": "Quelle",
+ "source_help": {
+ "explicit": "Ein auf dieser Preisliste eingetragener Betrag.",
+ "automatic": "Der Shop-Preis mit dem Prozentsatz dieser Preisliste.",
+ "base": "Der normale Shop-Preis. Diese Liste bepreist dieses Produkt nicht."
+ },
+ "tier_fixed_note": "Eine prozentuale Anpassung gilt hier nicht. Diese Staffeln legen den Preis fest.",
+ "tier_preview": "Was diese Liste berechnet"
+ },
"products_help": "Wählen Sie die Produkte, für die diese Liste gilt. Platzhalterpreise werden beim Speichern angelegt — über „Preise bearbeiten\" ausfüllen.",
"products_help_with_prices_one": "Wählen Sie die Produkte, für die diese Liste gilt. {{count}} Preis ist hinterlegt — über „Preise bearbeiten\" anpassen.",
"products_help_with_prices_other": "Wählen Sie die Produkte, für die diese Liste gilt. {{count}} Preise sind hinterlegt — über „Preise bearbeiten\" anpassen.",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 7aeb927a65..ef6e5e9ad4 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -3387,6 +3387,17 @@
"select_row": "Select product",
"title": "Products"
},
+ "prices": {
+ "column_price": "Price",
+ "column_source": "From",
+ "source_help": {
+ "explicit": "An amount entered on this price list.",
+ "automatic": "The shop price with this list's percentage applied.",
+ "base": "The normal shop price. This list does not price this product."
+ },
+ "tier_fixed_note": "A percentage adjustment does not apply here. These tiers fix the price.",
+ "tier_preview": "What this list charges"
+ },
"products_help": "Pick the products this list applies to. Placeholder prices are created on save — fill them in with Edit prices.",
"products_help_with_prices_one": "Pick the products this list applies to. {{count}} price is configured — use Edit prices to update it.",
"products_help_with_prices_other": "Pick the products this list applies to. {{count}} prices are configured — use Edit prices to update them.",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 0025200cca..fc78bd8214 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -3387,6 +3387,17 @@
"select_row": "Sélectionner le produit",
"title": "Produits"
},
+ "prices": {
+ "column_price": "Prix",
+ "column_source": "Source",
+ "source_help": {
+ "explicit": "Un montant saisi sur cette liste de prix.",
+ "automatic": "Le prix boutique avec le pourcentage de cette liste appliqué.",
+ "base": "Le prix boutique normal. Cette liste ne fixe pas de prix pour ce produit."
+ },
+ "tier_fixed_note": "Un ajustement en pourcentage ne s'applique pas ici. Ces paliers fixent le prix.",
+ "tier_preview": "Ce que cette liste facture"
+ },
"products_help": "Choisissez les produits auxquels cette liste s'applique. Des prix provisoires sont créés à l'enregistrement — renseignez-les via « Modifier les prix ».",
"products_help_with_prices_one": "Choisissez les produits auxquels cette liste s'applique. {{count}} prix est configuré — utilisez « Modifier les prix » pour le mettre à jour.",
"products_help_with_prices_other": "Choisissez les produits auxquels cette liste s'applique. {{count}} prix sont configurés — utilisez « Modifier les prix » pour les mettre à jour.",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 3697147f68..446146b4a7 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -3427,6 +3427,17 @@
"select_row": "Wybierz produkt",
"title": "Produkty"
},
+ "prices": {
+ "column_price": "Cena",
+ "column_source": "Źródło",
+ "source_help": {
+ "explicit": "Kwota wprowadzona na tym cenniku.",
+ "automatic": "Cena sklepowa z zastosowanym procentem tego cennika.",
+ "base": "Zwykła cena sklepowa. Ten cennik nie wycenia tego produktu."
+ },
+ "tier_fixed_note": "Procentowa korekta nie ma tu zastosowania. Te progi ustalają cenę.",
+ "tier_preview": "Ile pobiera ten cennik"
+ },
"products_help": "Wybierz produkty, których dotyczy ten cennik. Ceny zastępcze zostaną utworzone przy zapisie — uzupełnij je przez „Edytuj ceny”.",
"products_help_with_prices_one": "Wybierz produkty, których dotyczy ten cennik. Skonfigurowano {{count}} cenę — użyj „Edytuj ceny”, aby ją zaktualizować.",
"products_help_with_prices_other": "Wybierz produkty, których dotyczy ten cennik. Skonfigurowano {{count}} ceny — użyj „Edytuj ceny”, aby je zaktualizować.",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index dc364f863a..29ffb92009 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -3379,6 +3379,17 @@
"select_row": "选择产品",
"title": "产品"
},
+ "prices": {
+ "column_price": "价格",
+ "column_source": "来源",
+ "source_help": {
+ "explicit": "在此价目表上输入的金额。",
+ "automatic": "应用此价目表百分比后的商店价格。",
+ "base": "正常的商店价格。此价目表未为该产品定价。"
+ },
+ "tier_fixed_note": "百分比调整不适用于此处。这些阶梯固定了价格。",
+ "tier_preview": "此价目表的收费"
+ },
"products_help": "选择此价格表适用的产品。保存时会创建占位价格 — 使用“编辑价格”填写。",
"products_help_with_prices_one": "选择此价格表适用的产品。已配置 {{count}} 个价格 — 使用“编辑价格”进行更新。",
"products_help_with_prices_other": "选择此价格表适用的产品。已配置 {{count}} 个价格 — 使用“编辑价格”进行更新。",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
index d922081e01..f03c04243b 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import type { Catalog } from '@spree/admin-sdk'
+import type { Catalog, CatalogProduct } from '@spree/admin-sdk'
import type { PanelImport } from '@spree/dashboard-core'
import {
adminClient,
@@ -329,7 +329,12 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
// Each variant priced on its own row: a product's variants can
// be priced differently and carry different ladders
// (docs/plans/6.0-volume-pricing.md).
- renderSubRows={(products) => catalogVariantRows({ products })}
+ renderSubRows={(products) =>
+ catalogVariantRows<CatalogProduct>({
+ products,
+ variantsOf: (product) => product.catalog_variants,
+ })
+ }
extraColumns={() =>
mergeExtraColumns(
catalogPriceColumns({