Skip to content

armgit / spree

Public Imported from GitHub
0

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

Let a catalog's price list discount by quantity (#14534)

Damian Legawiec403c25165023
diff --git a/docs/plans/6.0-price-list-automatic-pricing.md b/docs/plans/6.0-price-list-automatic-pricing.md
index 947f408250..bdd6ea6e5f 100644
--- a/docs/plans/6.0-price-list-automatic-pricing.md
+++ b/docs/plans/6.0-price-list-automatic-pricing.md
@@ -1,10 +1,12 @@
# Price List Automatic Pricing (Percentage Adjustments)
-**Status:** Draft — design finalized 2026-08-30, nothing built
+**Status:** Implemented — schema, model, resolver, admin API and the
+catalog Pricing card shipped 2026-08-30; contextual rules on owned
+lists shipped 2026-08-31
**Target:** Spree 6.0
**Depends on:** B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md — catalog-bound lists), one-question-per-entity doctrine (decisions.md 2026-08-30)
**Author:** Damian + Claude
-**Last updated:** 2026-08-30
+**Last updated:** 2026-08-31
## Summary
@@ -66,6 +68,21 @@ maintain and no drift when base prices move.
letting the list's own products scope it with "none = everything" — that
is the catalog-rework leak reintroduced as a default. See decisions.md.
+- **An owned list honours its contextual rules, and only those**
+ (2026-08-31). Reached through its catalog, an owned list has already been
+ matched on audience — the assignment is what selected it — so re-asking a
+ `CustomerGroupRule` or `ChannelRule` there would answer a question the
+ agreement already owns. Quantity is different in kind: no assignment can
+ express "when they buy ten", because that is a property of the purchase
+ and not of the buyer. So the resolver consults an owned list's
+ **contextual** rules (`PriceRule.contextual?` — a class predicate beside
+ `geographic?` and `superseded?`, deliberately not a constant, since
+ extensions register rule kinds of their own) and ignores its audience
+ rules. `VolumeRule` is the only contextual core kind. This is what makes
+ the headline case — a `VolumeRule` at `min_quantity: 10` plus −5% —
+ resolve at all: before it, the two halves could not live on one list. See
+ decisions.md.
+
## Design Details
### Schema + model
@@ -109,9 +126,22 @@ way.)
Nothing else in the walk changes: adjustment lists are ordinary lists —
rule-matched by position, or catalog-bound with catalog precedence, dates
-and status honored. The resolution cache key must incorporate the base
-price's version for adjustment lists (a computed price changes when the
-base row changes, not when the list does).
+and status honored, plus the contextual rules an owned list carries.
+
+Derived prices are read from the base row on every call: the internal
+provider is deliberately uncached (`Pricing::PriceResolution` caches only
+providers declaring a `cache_ttl`, which Internal does not), so a computed
+price cannot go stale behind a changed base price. Any future cache over
+the internal path would have to key on the base price's version.
+
+Quantity tiers are not expressible on one list. A price rule is unique per
+`(type, price_list)`, so a list holds at most one volume rule, and a
+catalog owns at most one list — "−10% from ten, −20% from fifty" therefore
+means two catalogs on the same company, where the lower-positioned one wins
+even for a buyer who qualifies for the deeper tier. Real tiering wants a
+rule that carries bands, or resolution that prefers the best-priced
+matching list rather than the first; both are additive and neither is 6.0
+scope.
### API + dashboard
@@ -143,6 +173,19 @@ exactly as today.
## Constraints on Current Work
+- **Pricing does not re-check the assortment; visibility is what scopes a
+ percentage.** The resolver derives a price for whatever variant it is
+ asked about, so an owned list's percentage is scoped only because
+ `Products::ForContext` never shows the buyer a product outside the
+ catalog's assortment (verified 2026-08-31: a member sees 20 of 38 sample
+ products, and the other 18 are unreachable). This is deliberate — an
+ empty assortment is a legitimate pricing-only overlay that prices the
+ whole channel range, so the resolver cannot simply require membership.
+ The consequence for new code: anything that prices a variant a buyer
+ cannot see (an admin tool, a feed, a report resolving with a `company:`)
+ gets the adjusted amount, and must scope by assortment itself rather than
+ assume the resolver did.
+
- **Never materialize derived rows** — no job, rake task, or import path
may write price rows computed from an adjustment; the override path is a
merchant typing an explicit amount.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 0cba49e6d4..d3010f4902 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -4538,3 +4538,50 @@ sale — as a default rather than an accident.
Plans amended: `6.0-price-list-automatic-pricing.md` (Key Decisions, API +
dashboard), `6.0-catalog-agreement-rework.md` (unchanged in substance — the
catalog page was always the card's home).
+
+## 2026-08-31 — An owned price list honours its contextual rules, and only those
+
+Settles the open consequence recorded in the catalog-owned-only decision
+earlier today, which left automatic volume pricing — the automatic-pricing
+plan's headline case — with no working home.
+
+**The finding.** The resolver reaches a catalog-owned list through the
+catalog and selects it on status and dates alone; `applicable?` is never
+called, so an owned list's rules are inert. Meanwhile a percentage may only
+live on an owned list. The two halves of "a `VolumeRule` at `min_quantity:
+10` plus −5%" were therefore in different rooms: the resolver specs prove
+it, testing volume pricing only on standalone lists with hand-entered rows
+and percentages only on rule-less owned lists.
+
+**Decision.** Owned lists consult their **contextual** rules and ignore
+their **audience** rules. The split is a class-level predicate on the rule,
+`PriceRule.contextual?`, beside the existing `geographic?` and
+`superseded?` — not a constant listing type names, since extensions
+register rule kinds of their own and a frozen list would silently exclude
+them. `VolumeRule` is contextual; every other core kind is not.
+
+The reasoning is that an owned list has already been matched on audience by
+the time the resolver holds it — the catalog assignment is what selected it,
+nearest node first. Re-asking a `CustomerGroupRule` there could only narrow
+an audience the agreement already decided, which is the second answer to a
+question the doctrine says one entity owns. Quantity is different in kind:
+no catalog assignment can express "when they buy ten", because it is a
+property of the purchase and not of the buyer. Dates and status already
+gate owned lists and are unchanged.
+
+**Consequences.** `Catalogs::SetPriceList` accepts `rules` on the inline
+payload, and the catalog editor offers the contextual kinds only — the
+picker filters on `contextual?` for an owned list exactly as it filters on
+`superseded?` elsewhere. An owned list carrying no rules behaves exactly as
+before, so nothing merchants have already set up moves.
+
+Rejected: consulting every rule on an owned list. That re-litigates the
+audience inside the agreement and would let a stale `CustomerGroupRule`
+silently switch a negotiated price off. Also rejected: a separate
+quantity-tier table on the list — price rules already express the
+predicate, and a second vocabulary for the same question is what the
+one-question-per-entity doctrine exists to prevent.
+
+Plans amended: `6.0-price-list-automatic-pricing.md` (Key Decisions,
+Resolution), `6.0-catalog-agreement-rework.md` (Constraints — owned lists
+are no longer rule-free).
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 23f50b1d09..0f330afcc4 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -2601,10 +2601,11 @@ export interface CatalogParams {
/**
* The price list this catalog prices through, written inline: an object
* creates the owned list or updates the one already there. An explicit
- * `null` **deletes** that list — a list a catalog owns carries no rules of
- * its own, so releasing it into general matching would price every
- * shopper; it is a soft delete, so the prices stay recoverable. Omit the
- * key, or send `{}`, to leave the pricing alone.
+ * `null` **deletes** that list — an owned list is matched by its catalog
+ * rather than by an audience of its own, so releasing it into general
+ * matching would price every shopper; it is a soft delete, so the prices
+ * stay recoverable. Omit the key, or send `{}`, to leave the pricing
+ * alone.
*
* Do not send this together with `price_list_id`: a catalog may only own
* its own list, and the pair is refused rather than letting one catalog
@@ -2625,6 +2626,21 @@ export interface CatalogPriceListParams {
/** Signed: negative discounts off base prices, positive marks up. */
price_adjustment_percentage?: string | null
adjust_compare_at?: boolean
+ /**
+ * Contextual rules for the owned list — in practice a `volume_rule`, which
+ * is what turns a percentage into an automatic volume discount.
+ *
+ * This payload speaks only for those: the catalog's assignments already
+ * decide who the agreement is for, so audience rules on the list are left
+ * exactly as they are, and an empty array clears the contextual rules
+ * without touching them.
+ */
+ rules?: Array<PriceListRuleDraft>
+ /**
+ * Explicit per-variant amounts. An empty array clears them, which is what
+ * switching from hand-entered prices to a percentage sends.
+ */
+ prices?: Array<PriceListPriceOverrideParams>
}
export interface CatalogAssignParams {
diff --git a/packages/dashboard/e2e/catalogs.spec.ts b/packages/dashboard/e2e/catalogs.spec.ts
index 10f9574fc1..cf132a7e35 100644
--- a/packages/dashboard/e2e/catalogs.spec.ts
+++ b/packages/dashboard/e2e/catalogs.spec.ts
@@ -160,6 +160,69 @@ test.describe('catalogs', () => {
await expect(emptyGrid.getByLabel(/^price for/i)).toHaveCount(0, { timeout: 15_000 })
})
+ // An automatic agreement is a percentage plus the quantity it starts at.
+ // Both have to survive a reload, and a second Save must not fail on the
+ // rule the first one wrote
+ // (docs/plans/6.0-price-list-automatic-pricing.md).
+ test('keeps the percentage and its quantity threshold across saves', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, CATALOGS_PATH(creds.store_id), CTA)
+
+ const name = `E2E Catalog Volume ${Date.now()}`
+ await createCatalog(page, name)
+
+ await page.locator('#catalog-pricing-mode').click()
+ await page.getByRole('option', { name: /percentage off/i }).click()
+ await page.locator('#catalog-adjustment-magnitude').fill('10')
+ await page.locator('#catalog-minimum-quantity').fill('10')
+ await saveCatalog(page)
+
+ await page.reload()
+ await expect(page.locator('#catalog-adjustment-magnitude')).toHaveValue('10', {
+ timeout: 15_000,
+ })
+ await expect(page.locator('#catalog-minimum-quantity')).toHaveValue('10')
+
+ // Saving again re-sends the same rule; it must update the row rather
+ // than try to add a second of its kind.
+ await page.locator('#catalog-adjustment-magnitude').fill('20')
+ await saveCatalog(page)
+ await page.reload()
+ await expect(page.locator('#catalog-adjustment-magnitude')).toHaveValue('20', {
+ timeout: 15_000,
+ })
+ await expect(page.locator('#catalog-minimum-quantity')).toHaveValue('10')
+ })
+
+ // The threshold survives a switch away from automatic pricing, where its
+ // field is no longer rendered. Judging it then would block Save over
+ // something the merchant cannot see or correct. The input refuses letters
+ // on its own, so the value that gets here is a number the rule still
+ // rejects — zero gates nothing.
+ test('does not judge the quantity once the agreement prices by hand', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, CATALOGS_PATH(creds.store_id), CTA)
+
+ const name = `E2E Catalog Switch ${Date.now()}`
+ await createCatalog(page, name)
+
+ await page.locator('#catalog-pricing-mode').click()
+ await page.getByRole('option', { name: /percentage off/i }).click()
+ await page.locator('#catalog-adjustment-magnitude').fill('10')
+ await page.locator('#catalog-minimum-quantity').fill('0')
+
+ await page.locator('#catalog-pricing-mode').click()
+ await page.getByRole('option', { name: /prices i enter for this catalog/i }).click()
+ await expect(page.locator('#catalog-minimum-quantity')).toHaveCount(0)
+
+ await saveCatalog(page)
+
+ // Saved: the list exists, so the price spreadsheet is reachable.
+ await expect(page.getByRole('button', { name: /^enter prices$/i })).toBeVisible({
+ timeout: 15_000,
+ })
+ })
+
test('renames a catalog from the header Save', async ({ page }) => {
const creds = await login(page)
await gotoIndex(page, CATALOGS_PATH(creds.store_id), CTA)
diff --git a/packages/dashboard/src/components/spree/catalog-pricing-fields.tsx b/packages/dashboard/src/components/spree/catalog-pricing-fields.tsx
index 68c03a2293..2fe260d0be 100644
--- a/packages/dashboard/src/components/spree/catalog-pricing-fields.tsx
+++ b/packages/dashboard/src/components/spree/catalog-pricing-fields.tsx
@@ -6,6 +6,10 @@ import {
FieldError,
FieldLabel,
Input,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ InputGroupText,
Select,
SelectContent,
SelectItem,
@@ -118,18 +122,25 @@ export function CatalogPricingFields({
{mode === 'automatic' && (
<>
<div className="flex items-end gap-2">
- <Field className="w-32">
+ <Field className="w-36">
<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')}
- />
+ <InputGroup>
+ <InputGroupInput
+ id="catalog-adjustment-magnitude"
+ type="number"
+ step="0.001"
+ min="0"
+ placeholder="15"
+ disabled={!canEdit}
+ aria-invalid={!!errors.adjustment_magnitude || undefined}
+ {...form.register('adjustment_magnitude')}
+ />
+ <InputGroupAddon align="inline-end">
+ <InputGroupText>%</InputGroupText>
+ </InputGroupAddon>
+ </InputGroup>
</Field>
<Field className="flex-1">
<FieldLabel htmlFor="catalog-adjustment-direction" className="sr-only">
@@ -184,6 +195,35 @@ export function CatalogPricingFields({
</p>
</div>
</Field>
+
+ {/* The threshold rides as the list's volume rule. Left blank the
+ agreement prices every quantity; filled in, it is an automatic
+ volume discount with no rows to maintain
+ (docs/plans/6.0-price-list-automatic-pricing.md). */}
+ {/* A quantity needs a few characters, so the field is narrow — but
+ `Field` stretches its children, so the help text has to sit
+ outside it or it wraps inside that narrow column. */}
+ <div className="flex flex-col gap-2">
+ <Field className="w-36">
+ <FieldLabel htmlFor="catalog-minimum-quantity">
+ {t('admin.fields.price_list.minimum_quantity.label')}
+ </FieldLabel>
+ <Input
+ id="catalog-minimum-quantity"
+ type="number"
+ step="1"
+ min="1"
+ placeholder={t('admin.fields.price_list.minimum_quantity.placeholder')}
+ disabled={!canEdit}
+ aria-invalid={!!errors.minimum_quantity || undefined}
+ {...form.register('minimum_quantity')}
+ />
+ </Field>
+ <FieldDescription>
+ {t('admin.fields.price_list.minimum_quantity.help')}
+ </FieldDescription>
+ <FieldError errors={[errors.minimum_quantity]} />
+ </div>
</>
)}
diff --git a/packages/dashboard/src/hooks/use-catalogs.ts b/packages/dashboard/src/hooks/use-catalogs.ts
index 450b553dee..fcab170d73 100644
--- a/packages/dashboard/src/hooks/use-catalogs.ts
+++ b/packages/dashboard/src/hooks/use-catalogs.ts
@@ -17,7 +17,9 @@ export function useCatalog(id: string | undefined) {
return useQuery({
queryKey: useResourceKey('catalogs', id ?? 'noop'),
queryFn: () =>
- adminClient.catalogs.get(id as string, { expand: ['assignments', 'price_list'] }),
+ adminClient.catalogs.get(id as string, {
+ expand: ['assignments', 'price_list', 'price_list.price_rules'],
+ }),
enabled: !!id,
})
}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 3619887233..7f2df500a4 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -1484,6 +1484,11 @@
"any": "قد تطابق أي قاعدة",
"label": "سياسة المطابقة"
},
+ "minimum_quantity": {
+ "help": "لا تطبّق الخصم إلا عند بلوغ هذا العدد من الوحدات في السطر. اتركه فارغًا لتسعير كل الكميات.",
+ "label": "الحد الأدنى للكمية",
+ "placeholder": "10"
+ },
"name": {
"help": "تسمية داخلية — لا تُعرض للعملاء أبدًا.",
"label": "الاسم",
@@ -3829,7 +3834,8 @@
"validation": {
"adjustment_required": "أدخل نسبة مئوية.",
"adjustment_too_deep": "يجب أن تكون أقل من 100%.",
- "ends_after_starts": "يجب أن يكون بعد تاريخ البدء."
+ "ends_after_starts": "يجب أن يكون بعد تاريخ البدء.",
+ "minimum_quantity_invalid": "أدخل عددًا صحيحًا."
}
},
"product_type_adds_options_one": "يضيف هذا النوع {{options}} إلى المنتجات الجديدة.",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 8293d11017..c016e3c9d2 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -1470,6 +1470,11 @@
"any": "Eine beliebige Regel darf zutreffen",
"label": "Übereinstimmungsregel"
},
+ "minimum_quantity": {
+ "help": "Rabatt erst ab dieser Stückzahl je Position. Leer lassen, um jede Menge zu bepreisen.",
+ "label": "Mindestmenge",
+ "placeholder": "10"
+ },
"name": {
"help": "Interne Bezeichnung — wird Kunden nie angezeigt.",
"label": "Name",
@@ -3811,7 +3816,8 @@
"validation": {
"adjustment_required": "Bitte einen Prozentsatz eingeben.",
"adjustment_too_deep": "Muss kleiner als 100 % sein.",
- "ends_after_starts": "Muss nach dem Startdatum liegen."
+ "ends_after_starts": "Muss nach dem Startdatum liegen.",
+ "minimum_quantity_invalid": "Geben Sie eine ganze Zahl ein."
}
},
"product_type_adds_options_one": "Dieser Typ fügt neuen Produkten {{options}} hinzu.",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index f9947967e6..c24a6aa5ac 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -1470,6 +1470,11 @@
"any": "Any rule may match",
"label": "Match policy"
},
+ "minimum_quantity": {
+ "help": "Only discount a line once it reaches this many units. Leave blank to price every quantity.",
+ "label": "Minimum quantity",
+ "placeholder": "10"
+ },
"name": {
"help": "Internal label — never shown to customers.",
"label": "Name",
@@ -3811,7 +3816,8 @@
"validation": {
"adjustment_required": "Enter a percentage.",
"adjustment_too_deep": "Must be less than 100%.",
- "ends_after_starts": "Must be after start date."
+ "ends_after_starts": "Must be after start date.",
+ "minimum_quantity_invalid": "Enter a whole number."
}
},
"product_type_adds_options_one": "This type adds {{options}} to new products.",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index a2a0632436..b3742b4dfc 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -1470,6 +1470,11 @@
"any": "N'importe quelle règle peut correspondre",
"label": "Règle de correspondance"
},
+ "minimum_quantity": {
+ "help": "N'appliquer la remise qu'à partir de ce nombre d'unités par ligne. Laissez vide pour tarifer toutes les quantités.",
+ "label": "Quantité minimale",
+ "placeholder": "10"
+ },
"name": {
"help": "Libellé interne — jamais affiché aux clients.",
"label": "Nom",
@@ -3811,7 +3816,8 @@
"validation": {
"adjustment_required": "Saisissez un pourcentage.",
"adjustment_too_deep": "Doit être inférieur à 100 %.",
- "ends_after_starts": "Doit être postérieur à la date de début."
+ "ends_after_starts": "Doit être postérieur à la date de début.",
+ "minimum_quantity_invalid": "Saisissez un nombre entier."
}
},
"product_type_adds_options_one": "Ce type ajoute {{options}} aux nouveaux produits.",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index af2106c62c..f6910c7883 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -1482,6 +1482,11 @@
"any": "Dowolna reguła może być spełniona",
"label": "Reguła dopasowania"
},
+ "minimum_quantity": {
+ "help": "Rabat dopiero od tej liczby sztuk w pozycji. Pozostaw puste, aby wyceniać każdą ilość.",
+ "label": "Minimalna ilość",
+ "placeholder": "10"
+ },
"name": {
"help": "Etykieta wewnętrzna — nigdy nie pokazywana klientom.",
"label": "Nazwa",
@@ -3859,7 +3864,8 @@
"validation": {
"adjustment_required": "Podaj wartość procentową.",
"adjustment_too_deep": "Musi być mniejsza niż 100%.",
- "ends_after_starts": "Musi być po dacie rozpoczęcia."
+ "ends_after_starts": "Musi być po dacie rozpoczęcia.",
+ "minimum_quantity_invalid": "Podaj liczbę całkowitą."
}
},
"product_type_adds_options_few": "Ten typ dodaje {{options}} do nowych produktów.",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 406974a820..0e7255bfc1 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -1466,6 +1466,11 @@
"any": "满足任一规则即可",
"label": "匹配策略"
},
+ "minimum_quantity": {
+ "help": "订单行达到此数量后才享受折扣。留空则对所有数量定价。",
+ "label": "最低数量",
+ "placeholder": "10"
+ },
"name": {
"help": "内部标签 — 不会向客户展示。",
"label": "名称",
@@ -3803,7 +3808,8 @@
"validation": {
"adjustment_required": "请输入百分比。",
"adjustment_too_deep": "必须小于 100%。",
- "ends_after_starts": "必须晚于开始日期。"
+ "ends_after_starts": "必须晚于开始日期。",
+ "minimum_quantity_invalid": "请输入整数。"
}
},
"product_type_adds_options_one": "此类型会为新商品添加{{options}}。",
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 594c7ad09b..986ffb6da2 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
@@ -170,7 +170,9 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
jsonPreview={{
title: `Catalog ${catalog.name}`,
fetch: () =>
- adminClient.catalogs.get(catalog.id, { expand: ['assignments', 'price_list'] }),
+ adminClient.catalogs.get(catalog.id, {
+ expand: ['assignments', 'price_list', 'price_list.price_rules'],
+ }),
endpoint: `/api/v3/admin/catalogs/${catalog.id}`,
resolveLink: spreeJsonLinkResolver(storeId),
}}
diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.ts
index ca3b576a36..54974d20d7 100644
--- a/packages/dashboard/src/schemas/catalog.ts
+++ b/packages/dashboard/src/schemas/catalog.ts
@@ -1,4 +1,4 @@
-import type { CatalogParams } from '@spree/admin-sdk'
+import type { CatalogParams, PriceList } from '@spree/admin-sdk'
import { blankToNull } from '@spree/dashboard-core'
import { requiredMessage } from '@spree/dashboard-ui'
import i18n from 'i18next'
@@ -8,6 +8,7 @@ import {
ADJUSTMENT_DIRECTIONS,
adjustmentFormValues,
PRICING_MODES,
+ parseMinimumQuantity,
parsePercentage,
} from './price-list'
@@ -43,7 +44,27 @@ export const catalogFormSchema = z
adjustment_direction: z.enum(ADJUSTMENT_DIRECTIONS).default('decrease'),
adjustment_magnitude: z.string().trim().optional(),
adjust_compare_at: z.boolean().default(false),
+ /**
+ * The quantity an order line must reach before the adjustment applies,
+ * carried as the owned list's volume rule. Blank means the agreement
+ * prices every quantity — which is what most agreements do
+ * (docs/plans/6.0-price-list-automatic-pricing.md).
+ */
+ minimum_quantity: z.string().trim().optional(),
})
+ // Only while the field is on screen. The value survives a switch away from
+ // automatic pricing, and judging it then would block Save over a field the
+ // merchant can no longer see or correct.
+ .refine(
+ (v) =>
+ v.pricing_mode !== 'automatic' ||
+ !v.minimum_quantity?.trim() ||
+ parseMinimumQuantity(v.minimum_quantity) !== null,
+ {
+ path: ['minimum_quantity'],
+ error: () => i18n.t('admin.products.price_lists.validation.minimum_quantity_invalid'),
+ },
+ )
.refine(
(v) => v.pricing_mode !== 'automatic' || parsePercentage(v.adjustment_magnitude) !== null,
{
@@ -75,6 +96,7 @@ export const CATALOG_DEFAULTS: CatalogFormValues = {
adjustment_direction: 'decrease',
adjustment_magnitude: '',
adjust_compare_at: false,
+ minimum_quantity: '',
staged_products: { adds: [], removes: [] },
}
@@ -103,8 +125,11 @@ function priceListPayload(values: CatalogFormValues, previousMode?: CatalogPrici
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 }
+ // makes it fixed. The quantity threshold goes with the percentage — left
+ // behind it would gate the hand-entered prices, and the card stops
+ // showing it, so nothing would explain the gap. `rules: []` clears only
+ // the contextual ones; the server keeps the rest.
+ return { price_adjustment_percentage: null, adjust_compare_at: false, rules: [] }
}
const magnitude = parsePercentage(values.adjustment_magnitude)
@@ -118,10 +143,24 @@ function priceListPayload(values: CatalogFormValues, previousMode?: CatalogPrici
adjust_compare_at: values.adjust_compare_at,
}
+ // A minimum quantity rides as the list's volume rule; dropping it from the
+ // list of rules is what clears it, so removing the threshold is a real
+ // edit rather than a silent no-op.
+ const withRule = { ...base, rules: volumeRulePayload(values.minimum_quantity) }
+
// Switching away from hand-entered prices clears them. An explicit amount
// beats the adjustment by design, so leaving the old rows behind would
// keep charging them while the card claims a percentage is in effect.
- return previousMode === 'fixed' ? { ...base, prices: [] } : base
+ return previousMode === 'fixed' ? { ...withRule, prices: [] } : withRule
+}
+
+function volumeRulePayload(minimumQuantity: string | undefined) {
+ const quantity = parseMinimumQuantity(minimumQuantity)
+ // A threshold of 1 gates nothing, which is exactly what blank means, so
+ // both send no rule at all rather than one that always matches.
+ if (quantity === null || quantity === 1) return []
+
+ return [{ type: 'volume_rule', preferences: { min_quantity: quantity } }]
}
/**
@@ -130,10 +169,7 @@ function priceListPayload(values: CatalogFormValues, previousMode?: CatalogPrici
*/
export function catalogPricingValues(
priceList:
- | {
- price_adjustment_percentage?: string | null
- adjust_compare_at?: boolean
- }
+ | Pick<PriceList, 'price_adjustment_percentage' | 'adjust_compare_at' | 'price_rules'>
| null
| undefined,
): {
@@ -141,6 +177,7 @@ export function catalogPricingValues(
adjustment_direction: CatalogFormValues['adjustment_direction']
adjustment_magnitude: string
adjust_compare_at: boolean
+ minimum_quantity: string
} {
if (!priceList) {
return {
@@ -148,6 +185,7 @@ export function catalogPricingValues(
adjustment_direction: 'decrease',
adjustment_magnitude: '',
adjust_compare_at: false,
+ minimum_quantity: '',
}
}
@@ -160,5 +198,21 @@ export function catalogPricingValues(
adjustment_direction,
adjustment_magnitude,
adjust_compare_at: priceList.adjust_compare_at ?? false,
+ minimum_quantity: minimumQuantityOf(priceList.price_rules),
}
}
+
+/**
+ * The volume rule's threshold, as the string the input edits. Shows whatever
+ * the rule holds — including a 1 set through the API or the standalone rules
+ * editor — because a value the field hides is a value the next Save destroys
+ * without the merchant ever seeing it.
+ */
+function minimumQuantityOf(rules: PriceList['price_rules']): string {
+ const rule = rules?.find((entry) => entry.type === 'volume_rule')
+ const quantity = parseMinimumQuantity(
+ rule?.preferences?.min_quantity as string | number | undefined,
+ )
+
+ return quantity === null ? '' : String(quantity)
+}
diff --git a/packages/dashboard/src/schemas/price-list.ts b/packages/dashboard/src/schemas/price-list.ts
index 7a0dad2c3d..f93c0b5abb 100644
--- a/packages/dashboard/src/schemas/price-list.ts
+++ b/packages/dashboard/src/schemas/price-list.ts
@@ -134,6 +134,19 @@ export function parsePercentage(value: string | undefined): number | null {
return Number.isFinite(parsed) && parsed > 0 ? parsed : null
}
+/**
+ * A whole-number quantity threshold, or null when absent or unusable. One
+ * parse for the validation, the write and the read, so the field cannot
+ * accept a value it then silently discards.
+ */
+export function parseMinimumQuantity(value: string | number | undefined | null): number | null {
+ const text = typeof value === 'string' ? value.trim() : value
+ if (text === '' || text === null || text === undefined) return null
+
+ const parsed = Number(text)
+ return Number.isInteger(parsed) && parsed >= 1 ? parsed : null
+}
+
export type PriceListFormValues = z.infer<typeof priceListFormSchema>
export const PRICE_LIST_DEFAULTS: PriceListFormValues = {
diff --git a/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb
index 4f51f56d7c..7ed1c4babc 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
@@ -82,6 +82,13 @@ module Spree
:name, :description, :status, :match_policy,
:starts_at, :ends_at,
:price_adjustment_percentage, :adjust_compare_at,
+ # Contextual rules only in practice — a
+ # VolumeRule is what turns a percentage
+ # into automatic volume pricing. Audience
+ # rules on an owned list are inert, since
+ # the catalog assignment already decided
+ # the audience.
+ { rules: [:id, :type, { preferences: {} }] },
# An empty array clears the hand-entered
# amounts — what switching to a
# percentage sends.
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.rb
index cdb38e0ee6..208c6615bf 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
@@ -40,6 +40,53 @@ RSpec.describe Spree::Api::V3::Admin::CatalogsController, type: :controller do
expect(list).to be_active
end
+ # A percentage plus a volume rule is an automatic volume discount, and
+ # both halves have to be settable in the one request that stands the
+ # agreement up (docs/plans/6.0-price-list-automatic-pricing.md).
+ it 'accepts the contextual rules that make automatic volume pricing work' do
+ post :create,
+ params: {
+ name: 'Bulk tier',
+ price_list: {
+ price_adjustment_percentage: '-10',
+ rules: [{ type: 'volume_rule', preferences: { min_quantity: 10 } }]
+ }
+ },
+ as: :json
+
+ expect(response).to have_http_status(:created)
+
+ list = store.catalogs.find_by(name: 'Bulk tier').price_list
+ rule = list.price_rules.sole
+ expect(rule).to be_a(Spree::PriceRules::VolumeRule)
+ expect(rule.preferred_min_quantity).to eq(10)
+ end
+
+ # Switching to hand-entered prices has to take the threshold with it.
+ # A rule left behind would gate the merchant's own amounts, and the card
+ # stops showing the field, so nothing would explain the missing discount.
+ it 'clears the volume rule when the agreement moves to fixed prices' do
+ post :create,
+ params: {
+ name: 'Switcher',
+ price_list: {
+ price_adjustment_percentage: '-10',
+ rules: [{ type: 'volume_rule', preferences: { min_quantity: 10 } }]
+ }
+ },
+ as: :json
+ created = store.catalogs.find_by(name: 'Switcher')
+ expect(created.price_list.price_rules.count).to eq(1)
+
+ patch :update,
+ params: { id: created.prefixed_id,
+ price_list: { price_adjustment_percentage: nil, rules: [] } },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(created.price_list.reload.price_rules).to be_empty
+ 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')
diff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rb
index 7b751fc735..05a0c4bab3 100644
--- a/spree/core/app/models/spree/catalog.rb
+++ b/spree/core/app/models/spree/catalog.rb
@@ -135,9 +135,14 @@ module Spree
catalogs = store.catalogs.for_customer_groups(groups)
end
catalogs = [channel&.default_catalog].compact.select(&:active?) if catalogs.empty?
- # Pricing reads each catalog's price list; without this the walk is one
- # query per catalog again.
- ActiveRecord::Associations::Preloader.new(records: catalogs, associations: :price_list).call if catalogs.any?
+ # Pricing reads each catalog's price list, and the list's contextual
+ # rules decide whether it applies to the quantity being bought; without
+ # this the walk is one query per catalog again, plus one per list.
+ if catalogs.any?
+ ActiveRecord::Associations::Preloader.new(
+ records: catalogs, associations: { price_list: :price_rules }
+ ).call
+ end
catalogs
end
diff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rb
index bd162b6d8e..db0e16d9f1 100644
--- a/spree/core/app/models/spree/price_list.rb
+++ b/spree/core/app/models/spree/price_list.rb
@@ -129,20 +129,38 @@ module Spree
# Returns true if the price list rules are applicable to the context
# @param context [Spree::Pricing::Context]
+ # @param rules [Enumerable<Spree::PriceRule>] the rules to judge; the
+ # list's own by default, a subset when only some of them still have a
+ # question to answer (see #contextual_rules_applicable?)
# @return [Boolean]
- def rules_applicable?(context)
- return true if price_rules.none?
+ def rules_applicable?(context, rules = price_rules)
+ return true if rules.none?
case match_policy
- when 'all'
- price_rules.all? { |rule| rule.applicable?(context) }
- when 'any'
- price_rules.any? { |rule| rule.applicable?(context) }
- else
- false
+ when 'all' then rules.all? { |rule| rule.applicable?(context) }
+ when 'any' then rules.any? { |rule| rule.applicable?(context) }
+ else false
end
end
+ # Whether an owned list still applies once its catalog has selected it.
+ #
+ # Only the contextual rules are asked. An owned list is reached through
+ # its catalog, which already answered the audience question — re-asking a
+ # customer-group or channel rule here would let a stale audience rule
+ # switch off a price the agreement grants. Quantity is the case a catalog
+ # cannot express, and it is what makes automatic volume pricing work
+ # (docs/plans/6.0-price-list-automatic-pricing.md).
+ #
+ # An owned list with no contextual rules applies, which is every list
+ # merchants have set up so far.
+ #
+ # @param context [Spree::Pricing::Context]
+ # @return [Boolean]
+ def contextual_rules_applicable?(context)
+ rules_applicable?(context, price_rules.select(&:contextual?))
+ end
+
# Whether this list derives prices from base prices rather than pricing
# only what it holds explicit rows for.
# @return [Boolean]
diff --git a/spree/core/app/models/spree/price_rule.rb b/spree/core/app/models/spree/price_rule.rb
index d71d742134..45e046bfd7 100644
--- a/spree/core/app/models/spree/price_rule.rb
+++ b/spree/core/app/models/spree/price_rule.rb
@@ -28,6 +28,33 @@ module Spree
false
end
+ # Whether this rule narrows by something about the purchase rather than
+ # about the buyer. A catalog-owned price list has already been matched on
+ # audience by the time the resolver holds it — the catalog assignment is
+ # what selected it — so only contextual rules still have a question left
+ # to answer there. Quantity is the case that matters: no assignment can
+ # express "when they buy ten", because that is a property of the order
+ # line and not of the customer.
+ #
+ # A predicate rather than a list of type names, so a rule kind an
+ # extension registers can declare itself contextual too
+ # (docs/plans/6.0-price-list-automatic-pricing.md).
+ #
+ # @return [Boolean]
+ def self.contextual?
+ false
+ end
+
+ # Instance-side reader, so rules are classified the same way
+ # `geographic?` classifies them (`rules.any?(&:geographic?)`). A kind
+ # whose answer depends on how it is configured overrides this, exactly
+ # as MarketRule does for `geographic?`.
+ #
+ # @return [Boolean]
+ def contextual?
+ self.class.contextual?
+ end
+
# Whether a better mechanism has replaced this rule kind. Superseded
# kinds are grandfathered — existing rules keep matching indefinitely —
# but they are flagged in types discovery so pickers stop offering them
diff --git a/spree/core/app/models/spree/price_rules/volume_rule.rb b/spree/core/app/models/spree/price_rules/volume_rule.rb
index ef821aece3..2deeb23e30 100644
--- a/spree/core/app/models/spree/price_rules/volume_rule.rb
+++ b/spree/core/app/models/spree/price_rules/volume_rule.rb
@@ -16,6 +16,12 @@ module Spree
def self.description
'Apply pricing based on quantity purchased'
end
+
+ # Quantity is a fact about the purchase, not the buyer, so this rule
+ # still narrows a list its catalog has already matched on audience.
+ def self.contextual?
+ true
+ end
end
end
end
diff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rb
index 184b88ed8e..bd869d4a9b 100644
--- a/spree/core/app/models/spree/pricing_provider/internal.rb
+++ b/spree/core/app/models/spree/pricing_provider/internal.rb
@@ -56,12 +56,21 @@ module Spree
# Price lists reached through the buyer's effective catalogs, in
# catalog resolution order — company subtree first, then customer
# groups, then the channel's default catalog (the same fallback
- # chain visibility uses). A catalog-attached list applies because
- # the catalog applies — its own rules are not consulted, only its
- # status and dates.
+ # chain visibility uses).
+ #
+ # A catalog-attached list applies because the catalog applies: its
+ # audience rules are not consulted, since the assignment already
+ # answered that question. Its *contextual* rules still are — a
+ # VolumeRule asks about the quantity being bought, which no catalog
+ # assignment can express, and that combination is what automatic
+ # volume pricing is (docs/plans/6.0-price-list-automatic-pricing.md).
+ # Status and dates gate the list as before.
+ #
# @return [Array<Spree::PriceList>]
def catalog_price_lists
- @catalog_price_lists ||= catalogs_for_context.filter_map(&:price_list).uniq.select(&:currently_active?)
+ @catalog_price_lists ||= catalogs_for_context.filter_map(&:price_list).uniq.select do |price_list|
+ price_list.currently_active? && price_list.contextual_rules_applicable?(context)
+ end
end
# Returns the price lists that are applicable to the context by their
diff --git a/spree/core/app/workflows/spree/catalogs/set_price_list.rb b/spree/core/app/workflows/spree/catalogs/set_price_list.rb
index f4afe8a9f3..7b615ce125 100644
--- a/spree/core/app/workflows/spree/catalogs/set_price_list.rb
+++ b/spree/core/app/workflows/spree/catalogs/set_price_list.rb
@@ -81,8 +81,50 @@ module Spree
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[:rules] = merged_rules(attrs[:rules]) if attrs.key?(:rules)
attrs
end
+
+ # This payload speaks only for the list's contextual rules — a catalog
+ # states the terms of the purchase, while who the agreement is for is
+ # settled by its assignments. Rules are reconciled by replacement, so
+ # the audience rules the caller never mentioned are merged back in;
+ # without this, editing a catalog's name through the inline payload
+ # would destroy a market rule and silently change how its prices are
+ # restated for VAT.
+ def merged_rules(rows)
+ existing = catalog.price_list&.price_rules&.to_a || []
+ untouched = existing.reject(&:contextual?)
+
+ contextual = Array(rows).filter_map do |row|
+ attrs = row.to_h.with_indifferent_access
+ klass = Spree::PriceRule.find_by_api_type(attrs[:type])
+ next unless klass&.contextual?
+
+ # A rule is unique per kind on a list, and this payload names kinds
+ # rather than rows, so the row already holding that kind is the one
+ # meant — whatever id the caller sent, or none at all. Taking the
+ # caller's id at face value would build a second rule of the same
+ # type (an id from another list finds nothing here) and be refused
+ # by the uniqueness validation, turning an ordinary save into a
+ # 500.
+ attrs[:id] = existing.find { |rule| rule.class == klass }&.id
+ attrs
+ end
+
+ # The payload names kinds, so two rows of one kind are one intent
+ # stated twice; the last wins. Left as-is they would both resolve to
+ # the same row and the second would be refused as a duplicate type.
+ contextual = contextual.reverse.uniq { |attrs| attrs[:type] }.reverse
+
+ # Named by id and type only, deliberately without their preferences:
+ # reconciliation runs a row's preference setters, and those re-check
+ # every record an audience rule points at. Re-sending the stored
+ # values would re-validate data this payload never spoke about, so a
+ # customer group deleted long after the rule was written would turn
+ # an ordinary catalog save into a 404.
+ contextual + untouched.map { |rule| { id: rule.id, type: rule.class.api_type } }
+ end
end
end
end
diff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rb
index 9373b33d76..c3937eb85a 100644
--- a/spree/core/spec/models/spree/price_list_spec.rb
+++ b/spree/core/spec/models/spree/price_list_spec.rb
@@ -65,6 +65,60 @@ describe Spree::PriceList, type: :model do
end
end
+ # An owned list is selected by its catalog, which already answered the
+ # audience question — so only rules about the purchase itself still have
+ # anything to say (docs/plans/6.0-price-list-automatic-pricing.md).
+ describe '#contextual_rules_applicable?' do
+ let(:catalog) { create(:catalog, store: @default_store) }
+ let(:price_list) { create(:price_list, :active, store: @default_store, catalog: catalog) }
+
+ def context_with(quantity:)
+ Spree::Pricing::Context.new(currency: 'USD', store: @default_store, quantity: quantity)
+ end
+
+ it 'applies when the list carries no rules at all' do
+ expect(price_list.contextual_rules_applicable?(context_with(quantity: 1))).to be true
+ end
+
+ it 'asks a volume rule about the quantity being bought' do
+ create(:volume_price_rule, price_list: price_list, min_quantity: 10)
+ price_list.reload
+
+ expect(price_list.contextual_rules_applicable?(context_with(quantity: 10))).to be true
+ expect(price_list.contextual_rules_applicable?(context_with(quantity: 9))).to be false
+ end
+
+ # Re-asking the audience inside the agreement would let a stale rule
+ # switch off a price the catalog assignment already granted.
+ it 'ignores audience rules entirely' do
+ create(:customer_group_price_rule, price_list: price_list,
+ customer_group_ids: [create(:customer_group, store: @default_store).id])
+ price_list.reload
+
+ expect(price_list.contextual_rules_applicable?(context_with(quantity: 1))).to be true
+ end
+
+ it 'honours the match policy across contextual rules only' do
+ create(:volume_price_rule, price_list: price_list, min_quantity: 10)
+ create(:customer_group_price_rule, price_list: price_list,
+ customer_group_ids: [create(:customer_group, store: @default_store).id])
+ price_list.update!(match_policy: 'all')
+ price_list.reload
+
+ # The unsatisfied audience rule does not drag the 'all' policy down.
+ expect(price_list.contextual_rules_applicable?(context_with(quantity: 10))).to be true
+ end
+ end
+
+ describe '.contextual?' do
+ it 'is true for the volume rule and false for the audience kinds' do
+ expect(Spree::PriceRules::VolumeRule).to be_contextual
+ expect(Spree::PriceRules::CustomerGroupRule).not_to be_contextual
+ expect(Spree::PriceRules::ChannelRule).not_to be_contextual
+ expect(Spree::PriceRules::MarketRule).not_to be_contextual
+ end
+ end
+
# The catalog binding: nil = standalone (rule-matched), set = owned by
# exactly one catalog and reached only through it
# (docs/plans/6.0-catalog-agreement-rework.md).
diff --git a/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb b/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb
index 7900c6d11e..3cbbbacaa0 100644
--- a/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb
+++ b/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb
@@ -293,6 +293,74 @@ describe Spree::PricingProvider::Internal::Resolution do
end
end
+ # The headline case: a percentage plus a VolumeRule is an automatic
+ # volume discount, with no rows to maintain
+ # (docs/plans/6.0-price-list-automatic-pricing.md).
+ context 'with an automatic price list carrying a contextual rule' do
+ let(:company) { create(:company, store: store) }
+ let(:catalog) do
+ create(:catalog, store: store).tap do |owner|
+ create(:catalog_assignment, catalog: owner, assignable: company)
+ end
+ end
+ let!(:price_list) do
+ create(:price_list, :active, store: store, catalog: catalog, price_adjustment_percentage: -10)
+ end
+
+ before do
+ variant.prices.base_prices.with_currency(currency).update_all(amount: 20.00)
+ create(:volume_price_rule, price_list: price_list, min_quantity: 10)
+ end
+
+ def price_at(quantity)
+ described_class.new(
+ Spree::Pricing::Context.new(
+ variant: variant, currency: currency, store: store,
+ company: company, quantity: quantity
+ )
+ ).resolve
+ end
+
+ it 'derives the adjusted price once the quantity threshold is met' do
+ price = price_at(10)
+
+ expect(price.amount).to eq(18.00)
+ expect(price.price_list_id).to eq(price_list.id)
+ end
+
+ it 'leaves the base price alone below the threshold' do
+ price = price_at(5)
+
+ expect(price.amount).to eq(20.00)
+ expect(price.price_list_id).to be_nil
+ end
+
+ # Rules need a quantity to judge; a catalogue listing has none, and
+ # must not be priced as though it were a bulk order.
+ it 'leaves the base price alone when the context carries no quantity' do
+ expect(price_at(nil).amount).to eq(20.00)
+ end
+
+ # An audience rule on an owned list is inert: the catalog assignment
+ # already answered that question, and re-asking it here would let a
+ # stale rule switch off a price the agreement grants.
+ it 'ignores an audience rule the buyer does not satisfy' do
+ create(:customer_group_price_rule, price_list: price_list,
+ customer_group_ids: [create(:customer_group, store: store).id])
+
+ expect(price_at(10).amount).to eq(18.00)
+ end
+
+ # An explicit row is a deliberate override and beats the derived
+ # amount, but only once the rule lets the list apply at all.
+ it 'still prefers an explicit row over the derived amount' do
+ create(:price, variant: variant, currency: currency, amount: 15.00, price_list: price_list)
+
+ expect(price_at(10).amount).to eq(15.00)
+ expect(price_at(5).amount).to eq(20.00)
+ end
+ end
+
context 'with price list from different store' do
let(:other_store) { create(:store) }
let!(:other_store_list) { create(:price_list, :active, store: other_store) }
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.rb
index f838149d33..df40f557a6 100644
--- a/spree/core/spec/workflows/spree/catalogs/set_price_list_spec.rb
+++ b/spree/core/spec/workflows/spree/catalogs/set_price_list_spec.rb
@@ -133,4 +133,114 @@ describe Spree::Catalogs::SetPriceList do
expect(result).not_to be_success
expect(catalog.reload.price_list).to be_nil
end
+ # The inline payload is the catalog's voice, and a catalog states the terms
+ # of the purchase, not who it is for. So it speaks only for the contextual
+ # rules; the audience rules on the list belong to the standalone editor and
+ # must survive an edit made here.
+ describe 'rule reconciliation' do
+ let(:catalog) { create(:catalog, store: store) }
+ let!(:price_list) { create(:price_list, :active, store: store, catalog: catalog) }
+ let!(:market_rule) { create(:market_price_rule, price_list: price_list) }
+
+ it 'keeps the audience rules the payload never mentions' do
+ described_class.call(
+ catalog: catalog,
+ attributes: { rules: [{ 'type' => 'volume_rule', 'preferences' => { 'min_quantity' => 10 } }] }
+ )
+
+ types = price_list.reload.price_rules.map { |rule| rule.class.api_type }
+ expect(types).to contain_exactly('volume_rule', 'market_rule')
+ # Kept, not replaced: reconciliation matches on id, so the row survives.
+ expect(price_list.price_rules.find_by(type: market_rule.type).id).to eq(market_rule.id)
+ end
+
+ # The payload names kinds, not rows. A second save that repeats the kind
+ # has to update the row it already has — building another would be
+ # refused, and the merchant would see a 500 on an ordinary Save.
+ it 'updates the rule in place when the same kind is sent again' do
+ volume_payload = ->(quantity) do
+ { rules: [{ 'type' => 'volume_rule', 'preferences' => { 'min_quantity' => quantity } }] }
+ end
+
+ described_class.call(catalog: catalog, attributes: volume_payload.call(10))
+ original = price_list.reload.price_rules.find_by(type: 'Spree::PriceRules::VolumeRule')
+
+ result = described_class.call(catalog: catalog, attributes: volume_payload.call(25))
+
+ expect(result).to be_success
+ rules = price_list.reload.price_rules.select { |rule| rule.is_a?(Spree::PriceRules::VolumeRule) }
+ expect(rules.size).to eq(1)
+ expect(rules.first.id).to eq(original.id)
+ expect(rules.first.preferred_min_quantity).to eq(25)
+ end
+
+ # The payload names kinds, so the row holding that kind is the one meant.
+ # Taking a caller's id at face value would try to build a second rule of
+ # the same type and turn an ordinary save into a 500.
+ it 'ignores a rule id belonging to another catalog' do
+ other = create(:catalog, store: store)
+ other_list = create(:price_list, :active, store: store, catalog: other)
+ stranger = create(:volume_price_rule, price_list: other_list, min_quantity: 4)
+ mine = create(:volume_price_rule, price_list: price_list, min_quantity: 10)
+
+ result = described_class.call(
+ catalog: catalog,
+ attributes: { rules: [{ 'id' => stranger.id, 'type' => 'volume_rule',
+ 'preferences' => { 'min_quantity' => 99 } }] }
+ )
+
+ expect(result).to be_success
+ expect(mine.reload.preferred_min_quantity).to eq(99)
+ # The other catalog's rule is untouched, and still its own.
+ expect(stranger.reload.preferred_min_quantity).to eq(4)
+ expect(stranger.price_list_id).to eq(other_list.id)
+ end
+
+ # Merging a rule back in must not re-run its setters: those re-check
+ # every record the rule points at, so a group deleted long after the rule
+ # was written would fail a save that never mentioned it.
+ it 'survives an audience rule whose referenced record is gone' do
+ group = create(:customer_group, store: store)
+ create(:customer_group_price_rule, price_list: price_list, customer_group_ids: [group.id])
+ # Really gone, not soft-deleted: a paranoid destroy still resolves, so
+ # it would not exercise the validator at all.
+ group.really_destroy!
+
+ # The pricing card sends `rules` on every save, so an edit that only
+ # changes the percentage still carries the audience rule through here.
+ result = described_class.call(
+ catalog: catalog,
+ attributes: { price_adjustment_percentage: '-20',
+ rules: [{ 'type' => 'volume_rule', 'preferences' => { 'min_quantity' => 10 } }] }
+ )
+
+ expect(result).to be_success
+ expect(price_list.reload.price_adjustment_percentage).to eq(-20)
+ expect(price_list.price_rules.map { |rule| rule.class.api_type }).to include('customer_group_rule')
+ end
+
+ # The payload names kinds, so one kind stated twice is one intent.
+ it 'takes the last of two rows naming the same kind' do
+ result = described_class.call(
+ catalog: catalog,
+ attributes: { rules: [
+ { 'type' => 'volume_rule', 'preferences' => { 'min_quantity' => 5 } },
+ { 'type' => 'volume_rule', 'preferences' => { 'min_quantity' => 20 } }
+ ] }
+ )
+
+ expect(result).to be_success
+ volume = price_list.reload.price_rules.select { |rule| rule.is_a?(Spree::PriceRules::VolumeRule) }
+ expect(volume.map(&:preferred_min_quantity)).to eq([20])
+ end
+
+ it 'clears the contextual rules on an empty array without touching the rest' do
+ create(:volume_price_rule, price_list: price_list, min_quantity: 10)
+
+ described_class.call(catalog: catalog, attributes: { rules: [] })
+
+ expect(price_list.reload.price_rules.map { |rule| rule.class.api_type }).to eq(['market_rule'])
+ end
+ end
+
end