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
Stand up a catalog and the price list it prices through in one request
Damian Legawiec14538649f9fd
diff --git a/docs/plans/6.0-catalog-agreement-rework.md b/docs/plans/6.0-catalog-agreement-rework.mdindex 2ca73a1477..1260983159 100644--- a/docs/plans/6.0-catalog-agreement-rework.md+++ b/docs/plans/6.0-catalog-agreement-rework.md@@ -117,9 +117,19 @@ catalog page this rework establishes.match). Deliberately no warnings, no bridge and no data task — see therevised Key Decision above.4. **API + dashboard** — inline `price_list` payload, agreement editor,- products-with-prices view, wizard, detach warning. (The pricing card's- ±% controls and the Terms card arrive with their own plans on this- surface.)+ products-with-prices view, wizard, detach warning. **Partly done+ 2026-08-30**: the inline payload (`Spree::Catalogs::Create`/`Update`+ delegating to `SetPriceList` — create, update in place, or detach on an+ explicit null; a list a catalog owns is named after the catalog and born+ active, since the catalog's own `active` flag already gates the+ agreement) and the agreement editor's Pricing card (normal prices / ±% /+ fixed, with the detach warning stating that a released list starts+ matching by its own rules). The ±% controls landed with+ `6.0-price-list-automatic-pricing.md`. **Still open:** the+ products-with-prices view, and the pricing choice on the New-catalog+ sheet — it still asks only for a name, so "one go" is not yet true at+ creation time. The Terms card arrives with+ `6.0-b2b-quantity-rules.md`.## Constraints on Current Workdiff --git a/packages/admin-sdk/src/types/generated/Catalog.ts b/packages/admin-sdk/src/types/generated/Catalog.tsindex cf6c83983e..7561a4427f 100644--- a/packages/admin-sdk/src/types/generated/Catalog.ts+++ b/packages/admin-sdk/src/types/generated/Catalog.ts@@ -1,7 +1,7 @@-// Typelizer digest 704a53e6dc0f43cbe2d8f426c518dbaa+// Typelizer digest 0d9c3211b399c7bf1c501f3296c63ee2//// DO NOT MODIFY: This file was automatically generated by Typelizer.-import type {CatalogAssignment} from '@/types'+import type {PriceList, CatalogAssignment} from '@/types'interface Catalog {id: string;@@ -13,6 +13,7 @@ interface Catalog {updated_at: string;price_list_id: string | null;products_count: number;+ price_list?: PriceList;assignments?: Array<CatalogAssignment>;}diff --git a/packages/dashboard/src/components/spree/catalog-pricing-fields.tsx b/packages/dashboard/src/components/spree/catalog-pricing-fields.tsxnew file mode 100644index 0000000000..f365bd9d1a--- /dev/null+++ b/packages/dashboard/src/components/spree/catalog-pricing-fields.tsx@@ -0,0 +1,179 @@+import {+ Button,+ Field,+ FieldDescription,+ FieldError,+ FieldLabel,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Switch,+} from '@spree/dashboard-ui'+import { Controller, type UseFormReturn } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import { CATALOG_PRICING_MODES, type CatalogFormValues } from '../../schemas/catalog'+import { ADJUSTMENT_DIRECTIONS } from '../../schemas/price-list'++/**+ * How the agreement prices, edited on the catalog itself: the catalog and the+ * list it prices through are saved in one request, so standing up "wholesale+ * at −15%" never means visiting the price-lists page+ * (docs/plans/6.0-catalog-agreement-rework.md).+ *+ * Shared by the create sheet and the agreement editor so both offer the same+ * choice; the detach warning only appears where a list already exists.+ */+export function CatalogPricingFields({+ form,+ canEdit,+ hasOwnedList = false,+ onImport,+ importing = false,+}: {+ form: UseFormReturn<CatalogFormValues>+ canEdit: boolean+ /** Drives the detach warning and the import shortcut, both edit-only. */+ hasOwnedList?: boolean+ onImport?: () => void+ importing?: boolean+}) {+ const { t } = useTranslation()+ const { errors } = form.formState+ const mode = form.watch('pricing_mode')++ const modeItems = CATALOG_PRICING_MODES.map((value) => ({+ value,+ label: t(`admin.fields.catalog.pricing_mode.${value}`),+ }))+ const directionItems = ADJUSTMENT_DIRECTIONS.map((value) => ({+ value,+ label: t(`admin.fields.price_list.adjustment_direction.${value}`),+ }))++ return (+ <>+ <Field>+ <FieldLabel htmlFor="catalog-pricing-mode">+ {t('admin.fields.catalog.pricing_mode.label')}+ </FieldLabel>+ <Controller+ control={form.control}+ name="pricing_mode"+ render={({ field }) => (+ <Select+ items={modeItems as never}+ value={field.value}+ onValueChange={field.onChange}+ disabled={!canEdit}+ >+ <SelectTrigger id="catalog-pricing-mode">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {modeItems.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ <FieldDescription>{t('admin.fields.catalog.pricing_mode.help')}</FieldDescription>+ </Field>++ {mode === 'automatic' && (+ <>+ <div className="flex items-end gap-2">+ <Field className="w-32">+ <FieldLabel htmlFor="catalog-adjustment-magnitude">+ {t('admin.fields.price_list.adjustment_magnitude.label')}+ </FieldLabel>+ <Input+ id="catalog-adjustment-magnitude"+ inputMode="decimal"+ placeholder="15"+ disabled={!canEdit}+ aria-invalid={!!errors.adjustment_magnitude || undefined}+ {...form.register('adjustment_magnitude')}+ />+ </Field>+ <Field className="flex-1">+ <FieldLabel htmlFor="catalog-adjustment-direction" className="sr-only">+ {t('admin.fields.price_list.adjustment_direction.label')}+ </FieldLabel>+ <Controller+ control={form.control}+ name="adjustment_direction"+ render={({ field }) => (+ <Select+ items={directionItems as never}+ value={field.value}+ onValueChange={field.onChange}+ disabled={!canEdit}+ >+ <SelectTrigger id="catalog-adjustment-direction">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {directionItems.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ </Field>+ </div>+ <FieldError errors={[errors.adjustment_magnitude]} />++ <Field orientation="horizontal">+ <Controller+ control={form.control}+ name="adjust_compare_at"+ render={({ field }) => (+ <Switch+ id="catalog-adjust-compare-at"+ checked={field.value}+ onCheckedChange={field.onChange}+ disabled={!canEdit}+ />+ )}+ />+ <div>+ <FieldLabel htmlFor="catalog-adjust-compare-at">+ {t('admin.fields.price_list.adjust_compare_at.label')}+ </FieldLabel>+ <p className="text-xs text-muted-foreground">+ {t('admin.fields.price_list.adjust_compare_at.help')}+ </p>+ </div>+ </Field>+ </>+ )}++ {/* Detaching releases the list back to matching by its own rules, and a+ rule-less one matches every shopper — so the consequence is stated+ before Save, not after. */}+ {hasOwnedList && mode === 'base' && (+ <p className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive" role="alert">+ {t('admin.catalogs.detach_warning')}+ </p>+ )}++ {canEdit && hasOwnedList && mode === 'fixed' && onImport && (+ <div>+ <Button type="button" size="sm" variant="outline" disabled={importing} onClick={onImport}>+ {importing ? t('admin.actions.saving') : t('admin.catalogs.import_from_price_list')}+ </Button>+ <FieldDescription>{t('admin.catalogs.import_from_price_list_help')}</FieldDescription>+ </div>+ )}+ </>+ )+}diff --git a/packages/dashboard/src/hooks/use-catalogs.ts b/packages/dashboard/src/hooks/use-catalogs.tsindex 7dec862772..450b553dee 100644--- a/packages/dashboard/src/hooks/use-catalogs.ts+++ b/packages/dashboard/src/hooks/use-catalogs.ts@@ -16,7 +16,8 @@ import i18n from 'i18next'export function useCatalog(id: string | undefined) {return useQuery({queryKey: useResourceKey('catalogs', id ?? 'noop'),- queryFn: () => adminClient.catalogs.get(id as string, { expand: ['assignments'] }),+ queryFn: () =>+ adminClient.catalogs.get(id as string, { expand: ['assignments', 'price_list'] }),enabled: !!id,})}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 5491d10fd5..137017a9ec 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -116,6 +116,7 @@"message": "سيؤدي هذا إلى حذف {{name}} وتعييناته. لن تتأثر المنتجات وقوائم الأسعار.","title": "حذف الكتالوج؟"},+ "detach_warning": "سيؤدي الحفظ إلى تحرير قائمة أسعار هذا الكتالوج. ستعود للمطابقة وفق قواعدها الخاصة، والقائمة بلا قواعد تنطبق على كل المتسوقين.","detail": {"delete_label": "حذف الكتالوج","load_error": "تعذر تحميل هذا الكتالوج",@@ -123,6 +124,7 @@},"empty": "لا توجد كتالوجات بعد","import_from_price_list": "استيراد المنتجات من قائمة الأسعار",+ "import_from_price_list_help": "ينسخ المنتجات التي يسعّرها هذا الكتالوج إلى تشكيلته.","messages": {"assigned": "تم تعيين الكتالوج","created": "تم إنشاء الكتالوج",@@ -925,6 +927,13 @@"help": "اختياري. بدون قائمة أسعار، يحدد الكتالوج التشكيلة فقط وتُطبق الأسعار الأساسية. مع تشكيلة فارغة، يقوم الكتالوج بالتسعير فقط — لا يُخفى شيء؛ استورد أو أضف منتجات لتقييد ما يراه هذا الجمهور.","label": "قائمة الأسعار","placeholder": "الأسعار الأساسية"+ },+ "pricing_mode": {+ "automatic": "نسبة مئوية من الأسعار الأساسية",+ "base": "الأسعار العادية",+ "fixed": "الأسعار التي أُدخلها لهذا الكتالوج",+ "help": "ما يدفعه هذا الجمهور. التغيير هنا يحدّث الكتالوج وأسعاره معًا.",+ "label": "التسعير"}},"certificate_document": {diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex ad9a3cee52..0bc36f190f 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -116,6 +116,7 @@"message": "Dies löscht {{name}} und seine Zuweisungen. Produkte und Preislisten bleiben unberührt.","title": "Katalog löschen?"},+ "detach_warning": "Beim Speichern wird die Preisliste dieses Katalogs freigegeben. Sie greift dann wieder nach ihren eigenen Regeln, und eine Liste ohne Regeln gilt für alle Kundinnen und Kunden.","detail": {"delete_label": "Katalog löschen","load_error": "Katalog konnte nicht geladen werden",@@ -123,6 +124,7 @@},"empty": "Noch keine Kataloge","import_from_price_list": "Produkte aus Preisliste importieren",+ "import_from_price_list_help": "Kopiert die Produkte, die dieser Katalog bepreist, in sein Sortiment.","messages": {"assigned": "Katalog zugewiesen","created": "Katalog erstellt",@@ -911,6 +913,13 @@"help": "Optional. Ohne Preisliste schränkt der Katalog nur das Sortiment ein; es gelten die Basispreise. Bei leerem Sortiment bepreist der Katalog nur — nichts wird ausgeblendet; importieren oder fügen Sie Produkte hinzu, um die Sichtbarkeit einzuschränken.","label": "Preisliste","placeholder": "Basispreise"+ },+ "pricing_mode": {+ "automatic": "Ein Prozentsatz auf die Grundpreise",+ "base": "Normale Preise",+ "fixed": "Preise, die ich für diesen Katalog eingebe",+ "help": "Was diese Zielgruppe zahlt. Änderungen hier aktualisieren den Katalog und seine Preise gemeinsam.",+ "label": "Preisgestaltung"}},"certificate_document": {diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 0e59d7d071..22c22235c9 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -116,6 +116,7 @@"message": "This deletes {{name}} and its assignments. Products and price lists are not affected.","title": "Delete catalog?"},+ "detach_warning": "Saving will release this catalog’s price list. It will start matching by its own rules again, and a list with no rules applies to every shopper.","detail": {"delete_label": "Delete catalog","load_error": "Could not load this catalog",@@ -123,6 +124,7 @@},"empty": "No catalogs yet","import_from_price_list": "Import products from price list",+ "import_from_price_list_help": "Copies the products this catalog prices into its assortment.","messages": {"assigned": "Catalog assigned","created": "Catalog created",@@ -911,6 +913,13 @@"help": "Optional. Without one, the catalog only narrows the assortment and base prices apply. With an empty assortment, the catalog only prices — nothing is hidden; import or add products to restrict what this audience sees.","label": "Price list","placeholder": "Base prices"+ },+ "pricing_mode": {+ "automatic": "A percentage off base prices",+ "base": "Normal prices",+ "fixed": "Prices I enter for this catalog",+ "help": "What this audience pays. Changing it here updates the catalog and its prices together.",+ "label": "Pricing"}},"certificate_document": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 5e84a96e54..e14f9ab02b 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -116,6 +116,7 @@"message": "Cela supprime {{name}} et ses affectations. Les produits et listes de prix ne sont pas affectés.","title": "Supprimer le catalogue ?"},+ "detach_warning": "L’enregistrement libérera la liste de prix de ce catalogue. Elle s’appliquera de nouveau selon ses propres règles, et une liste sans règle vaut pour tous les clients.","detail": {"delete_label": "Supprimer le catalogue","load_error": "Impossible de charger ce catalogue",@@ -123,6 +124,7 @@},"empty": "Aucun catalogue pour le moment","import_from_price_list": "Importer les produits de la liste de prix",+ "import_from_price_list_help": "Copie dans l’assortiment les produits que ce catalogue tarifie.","messages": {"assigned": "Catalogue affecté","created": "Catalogue créé",@@ -911,6 +913,13 @@"help": "Optionnel. Sans liste, le catalogue ne restreint que l’assortiment et les prix de base s’appliquent. Avec un assortiment vide, le catalogue ne fait que tarifer — rien n’est masqué ; importez ou ajoutez des produits pour restreindre ce que voit cette audience.","label": "Liste de prix","placeholder": "Prix de base"+ },+ "pricing_mode": {+ "automatic": "Un pourcentage sur les prix de base",+ "base": "Prix normaux",+ "fixed": "Les prix que je saisis pour ce catalogue",+ "help": "Ce que paie cette audience. La modification met à jour le catalogue et ses prix ensemble.",+ "label": "Tarification"}},"certificate_document": {diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex a1d25167f7..fdea5b574b 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -118,6 +118,7 @@"message": "To usunie {{name}} wraz z przypisaniami. Produkty i cenniki pozostaną nietknięte.","title": "Usunąć katalog?"},+ "detach_warning": "Zapis zwolni cennik tego katalogu. Zacznie on ponownie działać według własnych reguł, a cennik bez reguł obejmuje wszystkich klientów.","detail": {"delete_label": "Usuń katalog","load_error": "Nie udało się wczytać tego katalogu",@@ -125,6 +126,7 @@},"empty": "Brak katalogów","import_from_price_list": "Importuj produkty z cennika",+ "import_from_price_list_help": "Kopiuje do asortymentu produkty, które ten katalog wycenia.","messages": {"assigned": "Katalog przypisany","created": "Katalog utworzony",@@ -923,6 +925,13 @@"help": "Opcjonalny. Bez cennika katalog zawęża tylko asortyment i obowiązują ceny podstawowe. Przy pustym asortymencie katalog tylko wycenia — nic nie jest ukrywane; zaimportuj lub dodaj produkty, aby ograniczyć widoczność dla tego odbiorcy.","label": "Cennik","placeholder": "Ceny podstawowe"+ },+ "pricing_mode": {+ "automatic": "Procent od cen bazowych",+ "base": "Zwykłe ceny",+ "fixed": "Ceny, które wpiszę dla tego katalogu",+ "help": "Ile płaci ta grupa odbiorców. Zmiana aktualizuje katalog i jego ceny jednocześnie.",+ "label": "Ceny"}},"certificate_document": {diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex a7e92cbb1e..ed281485a5 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -116,6 +116,7 @@"message": "这将删除 {{name}} 及其分配。产品和价格表不受影响。","title": "删除目录?"},+ "detach_warning": "保存后将释放此目录的价目表。它将重新按自身规则匹配,而没有规则的价目表会对所有顾客生效。","detail": {"delete_label": "删除目录","load_error": "无法加载该目录",@@ -123,6 +124,7 @@},"empty": "暂无目录","import_from_price_list": "从价格表导入产品",+ "import_from_price_list_help": "将此目录定价的商品复制到其商品组合中。","messages": {"assigned": "目录已分配","created": "目录已创建",@@ -907,6 +909,13 @@"help": "可选。不设置价格表时,目录仅限定商品范围,按基础价格计价。商品范围为空时,目录只定价——不隐藏任何商品;导入或添加产品可限制该受众所见范围。","label": "价格表","placeholder": "基础价格"+ },+ "pricing_mode": {+ "automatic": "在基准价格上按百分比调整",+ "base": "正常价格",+ "fixed": "我为此目录输入的价格",+ "help": "此受众支付的价格。在此修改会同时更新目录及其价格。",+ "label": "定价"}},"certificate_document": {diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsxindex c65f672209..4ead27001b 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, CatalogAssignment, PriceList } from '@spree/admin-sdk'+import type { Catalog, CatalogAssignment } from '@spree/admin-sdk'import {adminClient,mapSpreeErrorsToForm,@@ -44,6 +44,7 @@ import { PlusIcon, TrashIcon } from 'lucide-react'import { useEffect, useState } from 'react'import { Controller, type UseFormReturn, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'+import { CatalogPricingFields } from '../../../../../components/spree/catalog-pricing-fields'import { DeferredProductMembershipCard } from '../../../../../components/spree/deferred-product-membership-card'import { ProductMembershipStagingProvider } from '../../../../../components/spree/product-membership-staging'import { ResourceDetailSkeleton } from '../../../../../components/spree/route-pending'@@ -61,6 +62,7 @@ import {CATALOG_DEFAULTS,type CatalogFormValues,catalogFormSchema,+ catalogPricingValues,catalogValuesToParams,} from '../../../../../schemas/catalog'@@ -119,7 +121,7 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {form.reset({name: catalog.name,active: catalog.active,- price_list_id: catalog.price_list_id ?? '',+ ...catalogPricingValues(catalog.price_list),staged_products: { adds: [], removes: [] },})}, [catalog, form])@@ -158,7 +160,8 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {resource={{ id: catalog.id }}jsonPreview={{title: `Catalog ${catalog.name}`,- fetch: () => adminClient.catalogs.get(catalog.id, { expand: ['assignments'] }),+ fetch: () =>+ adminClient.catalogs.get(catalog.id, { expand: ['assignments', 'price_list'] }),endpoint: `/api/v3/admin/catalogs/${catalog.id}`,resolveLink: spreeJsonLinkResolver(storeId),}}@@ -241,52 +244,13 @@ function CatalogSettingsCard({<FieldError errors={[errors.name]} /></Field>- <Field>- <FieldLabel>{t('admin.fields.catalog.price_list.label')}</FieldLabel>- <Controller- control={form.control}- name="price_list_id"- render={({ field }) => (- <ResourceCombobox<PriceList>- queryKey="catalog-price-lists"- // Only lists that are actually available: unowned ones,- // plus the one this catalog already holds. A list another- // catalog owns is refused server-side, so offering it- // would only produce a confusing error.- search={(q) =>- adminClient.priceLists.list({- name_cont: q,- catalog_id_null: true,- limit: 10,- })- }- hydrate={(ids) => adminClient.priceLists.list({ id_in: ids, limit: ids.length })}- getOptionLabel={(list) => list.name}- placeholder={t('admin.fields.catalog.price_list.placeholder')}- emptyText={t('admin.fields.catalog.price_list.empty')}- disabled={!canEdit}- value={field.value || undefined}- onChange={(id) => field.onChange(id ?? '')}- />- )}- />- <FieldDescription>{t('admin.fields.catalog.price_list.help')}</FieldDescription>- {canEdit && catalog.price_list_id && (- <div>- <Button- type="button"- size="sm"- variant="outline"- disabled={importMutation.isPending}- onClick={() => importMutation.mutate()}- >- {importMutation.isPending- ? t('admin.actions.saving')- : t('admin.catalogs.import_from_price_list')}- </Button>- </div>- )}- </Field>+ <CatalogPricingFields+ form={form}+ canEdit={canEdit}+ hasOwnedList={!!catalog.price_list_id}+ onImport={() => importMutation.mutate()}+ importing={importMutation.isPending}+ /><Controllercontrol={form.control}diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.tsindex 24ddc47985..4958a16ce3 100644--- a/packages/dashboard/src/schemas/catalog.ts+++ b/packages/dashboard/src/schemas/catalog.ts@@ -1,24 +1,65 @@import type { CatalogParams } from '@spree/admin-sdk'-import { blankToNull } from '@spree/dashboard-core'import { requiredMessage } from '@spree/dashboard-ui'+import i18n from 'i18next'import { z } from 'zod/v4'import type { ProductMembershipStagingValue } from '../components/spree/product-membership-staging'+import {+ ADJUSTMENT_DIRECTIONS,+ adjustmentFormValues,+ PRICING_MODES,+ parsePercentage,+} from './price-list'-/** Validation for the catalog create sheet and settings card. */-export const catalogFormSchema = z.object({- name: z.string().min(1, { error: requiredMessage('name') }),- /**- * Staged product membership, applied on Save through the nested products- * endpoints. Opaque by design — it holds SDK `Product` records so a staged- * addition can render before it exists server-side, and RHF's `Path<T>`- * must not walk that object graph. Never sent to the API;- * `catalogValuesToParams` drops it.- */- staged_products: z.custom<ProductMembershipStagingValue>(() => true),- active: z.boolean(),- // Empty string = assortment-only (base prices).- price_list_id: z.string().optional(),-})+/**+ * How a catalog prices. `base` is no list at all — the buyer pays the normal+ * price and the catalog only decides what they see. The other two stand up a+ * list the catalog owns: `automatic` derives from base prices by a+ * percentage, `fixed` holds the prices a merchant enters+ * (docs/plans/6.0-catalog-agreement-rework.md).+ */+export const CATALOG_PRICING_MODES = ['base', ...PRICING_MODES] as const+export type CatalogPricingMode = (typeof CATALOG_PRICING_MODES)[number]++/** Validation for the catalog create sheet and the agreement editor. */+export const catalogFormSchema = z+ .object({+ name: z.string().min(1, { error: requiredMessage('name') }),+ /**+ * Staged product membership, applied on Save through the nested products+ * endpoints. Opaque by design — it holds SDK `Product` records so a staged+ * addition can render before it exists server-side, and RHF's `Path<T>`+ * must not walk that object graph. Never sent to the API;+ * `catalogValuesToParams` drops it.+ */+ staged_products: z.custom<ProductMembershipStagingValue>(() => true),+ active: z.boolean(),+ /**+ * Split for editing, recombined into the inline `price_list` payload by+ * `catalogValuesToParams`.+ */+ pricing_mode: z.enum(CATALOG_PRICING_MODES).default('base'),+ adjustment_direction: z.enum(ADJUSTMENT_DIRECTIONS).default('decrease'),+ adjustment_magnitude: z.string().trim().optional(),+ adjust_compare_at: z.boolean().default(false),+ })+ .refine(+ (v) => v.pricing_mode !== 'automatic' || parsePercentage(v.adjustment_magnitude) !== null,+ {+ path: ['adjustment_magnitude'],+ error: () => i18n.t('admin.products.price_lists.validation.adjustment_required'),+ },+ )+ .refine(+ (v) => {+ if (v.pricing_mode !== 'automatic' || v.adjustment_direction !== 'decrease') return true+ const magnitude = parsePercentage(v.adjustment_magnitude)+ return magnitude === null || magnitude < 100+ },+ {+ path: ['adjustment_magnitude'],+ error: () => i18n.t('admin.products.price_lists.validation.adjustment_too_deep'),+ },+ )/** Values the catalog form holds. */export type CatalogFormValues = z.infer<typeof catalogFormSchema>@@ -27,18 +68,82 @@ export type CatalogFormValues = z.infer<typeof catalogFormSchema>export const CATALOG_DEFAULTS: CatalogFormValues = {name: '',active: true,- price_list_id: '',+ pricing_mode: 'base',+ adjustment_direction: 'decrease',+ adjustment_magnitude: '',+ adjust_compare_at: false,staged_products: { adds: [], removes: [] },}/**- * Maps form values to the Admin API payload; a blank price list means- * "no list", which leaves the catalog pricing through base prices.+ * Maps form values to the Admin API payload. The catalog and the list it+ * prices through are written in one request, so `price_list` rides inline:+ * an object stands the list up or updates it, and an explicit null detaches+ * — which is a deliberate act, since a released list starts matching by its+ * own rules again.*/export function catalogValuesToParams(values: CatalogFormValues): CatalogParams {return {name: values.name,active: values.active,- price_list_id: blankToNull(values.price_list_id),+ price_list: priceListPayload(values),+ }+}++function priceListPayload(values: CatalogFormValues) {+ if (values.pricing_mode === 'base') return null++ if (values.pricing_mode === 'fixed') {+ // A fixed list holds explicit rows; clearing any adjustment is what+ // makes it fixed.+ return { price_adjustment_percentage: null, adjust_compare_at: false }+ }++ const magnitude = parsePercentage(values.adjustment_magnitude)+ if (magnitude === null) return { adjust_compare_at: values.adjust_compare_at }++ const signed = values.adjustment_direction === 'decrease' ? -magnitude : magnitude+ return {+ price_adjustment_percentage: String(signed),+ adjust_compare_at: values.adjust_compare_at,+ }+}++/**+ * Splits a catalog's owned list back into the edited fields. No list means+ * the catalog prices at base.+ */+export function catalogPricingValues(+ priceList:+ | {+ price_adjustment_percentage?: string | null+ adjust_compare_at?: boolean+ }+ | null+ | undefined,+): {+ pricing_mode: CatalogPricingMode+ adjustment_direction: CatalogFormValues['adjustment_direction']+ adjustment_magnitude: string+ adjust_compare_at: boolean+} {+ if (!priceList) {+ return {+ pricing_mode: 'base',+ adjustment_direction: 'decrease',+ adjustment_magnitude: '',+ adjust_compare_at: false,+ }+ }++ const { pricing_mode, adjustment_direction, adjustment_magnitude } = adjustmentFormValues(+ priceList.price_adjustment_percentage,+ )++ return {+ pricing_mode,+ adjustment_direction,+ adjustment_magnitude,+ adjust_compare_at: priceList.adjust_compare_at ?? false,}}diff --git a/packages/dashboard/src/schemas/price-list.ts b/packages/dashboard/src/schemas/price-list.tsindex eaa1226e84..6854aa248c 100644--- a/packages/dashboard/src/schemas/price-list.ts+++ b/packages/dashboard/src/schemas/price-list.ts@@ -151,7 +151,7 @@ export const priceListFormSchema = z)/** A positive percentage, or null when absent or unparseable. */-function parsePercentage(value: string | undefined): number | null {+export function parsePercentage(value: string | undefined): number | null {if (!value?.trim()) return nullconst parsed = Number(value)return Number.isFinite(parsed) && parsed > 0 ? parsed : nulldiff --git a/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rbindex 92177431e6..e0d4d16890 100644--- a/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb@@ -61,9 +61,28 @@ module Spree[:catalog_products, :price_list]end+ def create_workflow+ Spree.catalog_create_workflow+ end++ def update_workflow+ Spree.catalog_update_workflow+ end++ # `price_list` is an inline payload rather than a reference: a+ # catalog and the list it prices through are stood up in one+ # request (docs/plans/6.0-catalog-agreement-rework.md). Sending it+ # as `null` detaches the list the catalog owns; omitting the key+ # leaves it alone.def permitted_paramspermitted = params.permit(*model_additional_permitted_attributes,- :name, :active, :position, :price_list_id, metadata: {})+ :name, :active, :position, :price_list_id,+ metadata: {},+ price_list: [+ :name, :description, :status, :match_policy,+ :starts_at, :ends_at,+ :price_adjustment_percentage, :adjust_compare_at+ ])if permitted.key?(:price_list_id)permitted[:price_list_id] =if permitted[:price_list_id].present?@@ -72,6 +91,9 @@ module Spreenilendend+ # `permit` drops an explicit null, but detaching has to be+ # distinguishable from saying nothing.+ permitted[:price_list] = nil if params.key?(:price_list) && params[:price_list].nil?permittedenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rbindex e0eda60760..65d04b8ed5 100644--- a/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rb@@ -21,6 +21,13 @@ module Spreecatalog.catalog_products.sizeend+ # The owned list rides along so the agreement editor can render its+ # pricing without a second request — the catalog page is where an+ # owned list is edited (docs/plans/6.0-catalog-agreement-rework.md).+ one :price_list,+ resource: proc { Spree.api.admin_price_list_serializer },+ if: proc { expand?('price_list') }+many :catalog_assignments, key: :assignments,resource: proc { Spree.api.admin_catalog_assignment_serializer },if: proc { expand?('assignments') }diff --git a/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rbindex 55c7cb8ac7..99f75b0c5b 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rb@@ -9,6 +9,85 @@ RSpec.describe Spree::Api::V3::Admin::CatalogsController, type: :controller dobefore { request.headers.merge!(headers) }+ # Standing up an agreement is one request — the catalog and the list it+ # prices through (docs/plans/6.0-catalog-agreement-rework.md).+ describe 'the inline price_list payload' do+ it 'creates the catalog and its owned list together' do+ post :create,+ params: {+ name: 'Wholesale tier',+ price_list: { price_adjustment_percentage: '-15.0' }+ },+ as: :json++ expect(response).to have_http_status(:created)++ created = store.catalogs.find_by(name: 'Wholesale tier')+ list = created.price_list+ expect(list).to be_present+ expect(list.price_adjustment_percentage).to eq(-15)+ # Named after the catalog, since a merchant never sees it separately.+ expect(list.name).to eq('Wholesale tier')+ # Born active: the catalog's own flag already gates the agreement.+ expect(list).to be_active+ end++ it 'updates the owned list in place' do+ post :create, params: { name: 'Tier', price_list: { price_adjustment_percentage: '-10' } }, as: :json+ created = store.catalogs.find_by(name: 'Tier')+ list_id = created.price_list.id++ patch :update,+ params: { id: created.prefixed_id, price_list: { price_adjustment_percentage: '-20' } },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(created.reload.price_list.id).to eq(list_id)+ expect(created.price_list.price_adjustment_percentage).to eq(-20)+ end++ it 'detaches on an explicit null, keeping the list itself' do+ post :create, params: { name: 'Tier', price_list: { price_adjustment_percentage: '-10' } }, as: :json+ created = store.catalogs.find_by(name: 'Tier')+ list_id = created.price_list.id++ patch :update, params: { id: created.prefixed_id, price_list: nil }, as: :json++ expect(response).to have_http_status(:ok)+ expect(created.reload.price_list).to be_nil+ expect(Spree::PriceList.find(list_id).catalog_id).to be_nil+ end++ it 'leaves the list alone when the key is omitted' do+ post :create, params: { name: 'Tier', price_list: { price_adjustment_percentage: '-10' } }, as: :json+ created = store.catalogs.find_by(name: 'Tier')++ patch :update, params: { id: created.prefixed_id, name: 'Renamed' }, as: :json++ expect(created.reload.name).to eq('Renamed')+ expect(created.price_list).to be_present+ end++ it 'refuses an invalid adjustment without creating the catalog' do+ expect {+ post :create,+ params: { name: 'Bad tier', price_list: { price_adjustment_percentage: '-100' } },+ as: :json+ }.not_to change { store.catalogs.count }++ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'expands the owned list on read' do+ post :create, params: { name: 'Tier', price_list: { price_adjustment_percentage: '-10' } }, as: :json+ created = store.catalogs.find_by(name: 'Tier')++ get :show, params: { id: created.prefixed_id, expand: 'price_list' }, as: :json++ expect(json_response['price_list']['price_adjustment_percentage']).to eq('-10.0')+ end+ end+describe 'GET #index' doit 'lists the store catalogs with product counts' docreate(:catalog_product, catalog: catalog)diff --git a/spree/core/app/workflows/spree/catalogs/create.rb b/spree/core/app/workflows/spree/catalogs/create.rbnew file mode 100644index 0000000000..1f601b7555--- /dev/null+++ b/spree/core/app/workflows/spree/catalogs/create.rb@@ -0,0 +1,57 @@+module Spree+ module Catalogs+ # Creates a catalog, and the price list it prices through when one rides+ # along in the payload. Standing up an agreement is one request: a+ # merchant naming an audience and a discount never has to visit the+ # price-lists page to finish (docs/plans/6.0-catalog-agreement-rework.md).+ class Create < Spree::Workflow+ hooks :validate, :after_create++ attr_reader :catalog++ # @param store [Spree::Store]+ # @param attributes [Hash] may carry `price_list`+ # @return [Spree::ServiceModule::Result] value is the catalog+ def perform(store:, attributes: {})+ super++ step :build_catalog+ run_hooks :validate++ ApplicationRecord.transaction do+ step :save_catalog+ step :apply_price_list+ run_hooks :after_create+ end++ success(catalog)+ end++ private++ # The list payload is held back rather than assigned: the catalog needs+ # an id before a list can point at it.+ def build_catalog+ attrs = attributes.to_h.with_indifferent_access++ @price_list_attributes = attrs.key?(:price_list) ? attrs[:price_list] : nil+ @catalog = store.catalogs.new(attrs.except(:price_list))+ end++ def save_catalog+ failure(catalog) unless catalog.save+ end++ def apply_price_list+ return if @price_list_attributes.blank?++ result = Spree.catalog_price_list_workflow.call(+ catalog: catalog, attributes: @price_list_attributes+ )+ # Pass the inner ResultError through rather than wrapping it, so the+ # ActiveModel::Errors a 422 is built from survive.+ failure(catalog, result.error.value) unless result.success?+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/catalogs/set_price_list.rb b/spree/core/app/workflows/spree/catalogs/set_price_list.rbnew file mode 100644index 0000000000..ced0b2cbbc--- /dev/null+++ b/spree/core/app/workflows/spree/catalogs/set_price_list.rb@@ -0,0 +1,77 @@+module Spree+ module Catalogs+ # Writes the price list a catalog prices through, from an inline payload:+ # creates the owned list, updates the one already owned, or detaches with+ # nil (docs/plans/6.0-catalog-agreement-rework.md).+ #+ # Detaching is an explicit act with a consequence — a released list starts+ # matching by its own rules again, and a rule-less one matches everyone —+ # so it happens only when the caller sends `price_list: null`, never as a+ # side effect of omitting the key.+ class SetPriceList < Spree::Workflow+ attr_reader :catalog++ # @param catalog [Spree::Catalog]+ # @param attributes [Hash, nil] list attributes, or nil to detach+ # @return [Spree::ServiceModule::Result] value is the catalog+ def perform(catalog:, attributes: nil)+ super++ step :write_price_list++ success(catalog)+ end++ private++ def write_price_list+ return detach if attributes.blank?++ existing = catalog.price_list+ return update_existing(existing) if existing++ create_owned+ end++ # Releases the list back to standalone matching. The list itself is+ # kept: it holds prices someone entered, and deleting it because an+ # agreement moved on would lose them.+ def detach+ return if catalog.price_list.nil?++ failure(catalog) unless catalog.update(price_list: nil)+ end++ def update_existing(price_list)+ result = Spree.price_list_update_workflow.call(+ price_list: price_list, attributes: list_attributes+ )+ failure(catalog, result.error.value) unless result.success?+ end++ def create_owned+ result = Spree.price_list_create_workflow.call(+ store: catalog.store, attributes: list_attributes(for_create: true)+ )+ return failure(catalog, result.error.value) unless result.success?++ failure(catalog) unless catalog.update(price_list: result.value)+ end++ # A list a catalog owns is reached only through that catalog, so it+ # needs no name of its own to be found by — but the column is required,+ # and a merchant who never sees the list should not have to name it.+ #+ # It is also born active rather than draft: the catalog's own `active`+ # flag already decides whether the agreement applies, and a second+ # dormant switch inside it would only be a way to configure pricing+ # that silently does nothing.+ def list_attributes(for_create: false)+ attrs = attributes.to_h.with_indifferent_access+ attrs[:name] = catalog.name if attrs[:name].blank?+ attrs[:status] = 'active' if for_create && attrs[:status].blank?+ attrs+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/catalogs/update.rb b/spree/core/app/workflows/spree/catalogs/update.rbnew file mode 100644index 0000000000..b7d776c165--- /dev/null+++ b/spree/core/app/workflows/spree/catalogs/update.rb@@ -0,0 +1,55 @@+module Spree+ module Catalogs+ # Updates a catalog, and the price list it prices through when one rides+ # along in the payload (docs/plans/6.0-catalog-agreement-rework.md).+ class Update < Spree::Workflow+ hooks :validate, :after_update++ # @param catalog [Spree::Catalog]+ # @param attributes [Hash] may carry `price_list`+ # @return [Spree::ServiceModule::Result] value is the catalog+ def perform(catalog:, attributes: {})+ super++ step :assign_attributes+ run_hooks :validate++ ApplicationRecord.transaction do+ step :save_catalog+ step :apply_price_list+ run_hooks :after_update+ end++ success(catalog)+ end++ private++ def assign_attributes+ attrs = attributes.to_h.with_indifferent_access++ @price_list_attributes = attrs.key?(:price_list) ? attrs[:price_list] : nil+ catalog.assign_attributes(attrs.except(:price_list))+ end++ def save_catalog+ failure(catalog) unless catalog.save+ end++ def apply_price_list+ return unless @price_list_attributes || price_list_key_present?++ result = Spree.catalog_price_list_workflow.call(+ catalog: catalog, attributes: @price_list_attributes+ )+ failure(catalog, result.error.value) unless result.success?+ end++ # `price_list: null` is a detach, which is a different thing from+ # sending no `price_list` key at all.+ def price_list_key_present?+ attributes.to_h.with_indifferent_access.key?(:price_list)+ end+ end+ end+enddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex d384b626f4..bb08121513 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -153,6 +153,12 @@ module Spreeproduct_approve_workflow: 'Spree::Products::Approve',product_reject_workflow: 'Spree::Products::Reject',+ # catalogs — the agreement, written together with the price list it+ # prices through (docs/plans/6.0-catalog-agreement-rework.md)+ catalog_create_workflow: 'Spree::Catalogs::Create',+ catalog_update_workflow: 'Spree::Catalogs::Update',+ catalog_price_list_workflow: 'Spree::Catalogs::SetPriceList',+# price listsprice_list_create_workflow: 'Spree::PriceLists::Create',price_list_update_workflow: 'Spree::PriceLists::Update',diff --git a/spree/core/spec/workflows/spree/catalogs/set_price_list_spec.rb b/spree/core/spec/workflows/spree/catalogs/set_price_list_spec.rbnew file mode 100644index 0000000000..da05aa759e--- /dev/null+++ b/spree/core/spec/workflows/spree/catalogs/set_price_list_spec.rb@@ -0,0 +1,74 @@+require 'spec_helper'++# The inline price-list payload: a catalog and the list it prices through are+# written together (docs/plans/6.0-catalog-agreement-rework.md).+describe Spree::Catalogs::SetPriceList do+ let(:store) { @default_store }+ let(:catalog) { create(:catalog, store: store, name: 'Wholesale') }++ def call(attributes)+ described_class.call(catalog: catalog, attributes: attributes)+ end++ it 'creates the owned list, naming it after the catalog' do+ expect(call(price_adjustment_percentage: '-15')).to be_success++ list = catalog.reload.price_list+ expect(list.name).to eq('Wholesale')+ expect(list.price_adjustment_percentage).to eq(-15)+ end++ # The catalog's own `active` flag already gates the agreement; a second+ # dormant switch inside it would only configure pricing that does nothing.+ it 'gives the new list an active status rather than draft' do+ call(price_adjustment_percentage: '-15')++ expect(catalog.reload.price_list).to be_active+ end++ it 'honours an explicit name and status' do+ call(name: 'Negotiated', status: 'draft', price_adjustment_percentage: '-5')++ list = catalog.reload.price_list+ expect(list.name).to eq('Negotiated')+ expect(list).to be_draft+ end++ it 'updates the list already owned rather than making a second one' do+ call(price_adjustment_percentage: '-15')+ original_id = catalog.reload.price_list.id++ expect { call(price_adjustment_percentage: '-20') }.not_to change { store.price_lists.count }++ expect(catalog.reload.price_list.id).to eq(original_id)+ expect(catalog.price_list.price_adjustment_percentage).to eq(-20)+ end++ # Detaching releases the list to standalone matching, so it is only ever an+ # explicit act — and the list itself survives, since it holds prices someone+ # entered.+ it 'detaches on a blank payload, keeping the list' do+ call(price_adjustment_percentage: '-15')+ list = catalog.reload.price_list++ expect(described_class.call(catalog: catalog, attributes: nil)).to be_success++ expect(catalog.reload.price_list).to be_nil+ expect(list.reload.catalog_id).to be_nil+ expect(list).to be_persisted+ end++ it 'is a no-op when detaching a catalog that owns nothing' do+ expect(described_class.call(catalog: catalog, attributes: nil)).to be_success+ expect(catalog.reload.price_list).to be_nil+ end++ it 'fails without creating a list when the adjustment is invalid' do+ result = nil+ expect { result = call(price_adjustment_percentage: '-100') }.+ not_to change { store.price_lists.count }++ expect(result).not_to be_success+ expect(catalog.reload.price_list).to be_nil+ end+end