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.

Apply catalog product terms atomically, and refuse what cannot be a rule

Damian Legawiecfd197fc87b42
diff --git a/docs/plans/6.0-b2b-quantity-rules.md b/docs/plans/6.0-b2b-quantity-rules.md
index 08c6eceb2b..758b32aee6 100644
--- a/docs/plans/6.0-b2b-quantity-rules.md
+++ b/docs/plans/6.0-b2b-quantity-rules.md
@@ -23,9 +23,9 @@ This plan adds those rules as a purchasing layer over unchanged inventory:
stock stays in units, `Stock::Quantifier` and availability are untouched, and
the rules are enforced where quantities enter the cart — the `Carts::AddItem`
/ `Carts::UpsertItems` workflows that already own item validation. It builds
-directly on the packing chain the wholesale-shipping plan puts on variants
-(`units_per_carton`, `cartons_per_pallet`), completing SKU → MOQ → Order
-Multiple → Carton → Pallet.
+directly on the packing chain: this plan adds `units_per_carton` (see the
+decision below) and the wholesale-shipping plan adds the rest around it,
+completing SKU → MOQ → Order Multiple → Carton → Pallet.
## Key Decisions (do not deviate without discussion)
@@ -126,8 +126,8 @@ Multiple → Carton → Pallet.
multiple, blank meaning "uses the catalog default", which shows as the
placeholder. Stating a term for a product that is not in the assortment
**adds it**, and removing a product **removes its terms**: a rule has
- nothing to apply to without the product, and a surviving one silently
- reapplies if the product ever returns.
+ nothing to apply to without its product, and one left behind would come
+ back into force unannounced if that product were ever re-added.
- **A product row writes every variant's rule** (2026-08-31): the rows are
per variant in the database but a merchant thinks "minimum 48 of this
product", so a row's cells write the same pair to all of the product's
@@ -308,9 +308,9 @@ behavior (MOQ 1, multiple 1, unit display).
- Merchant feedback, 2026-08 (MOQ + order multiple; carton as the commercial
purchase unit; pallet quantities; per-catalog rule tiers; minimum B2B
order value).
-- `docs/plans/6.0-b2b-wholesale-shipping.md` — packing chain
- (`units_per_carton`, `carton_weight`, `cartons_per_pallet`,
- `PackageType`).
+- `docs/plans/6.0-b2b-wholesale-shipping.md` — the rest of the packing chain
+ (`carton_package_type_id`, `carton_weight`, `cartons_per_pallet`,
+ `PackageType`) around the `units_per_carton` this plan adds.
- `docs/plans/6.0-extendable-validations.md` — `UpsertItems` contract,
partial-success warnings, `ActiveModel::Errors` rejections.
- `docs/plans/6.0-b2b-companies-and-catalogs.md` — catalogs,
diff --git a/docs/plans/6.0-b2b-wholesale-shipping.md b/docs/plans/6.0-b2b-wholesale-shipping.md
index d26de1cf24..dabda0a234 100644
--- a/docs/plans/6.0-b2b-wholesale-shipping.md
+++ b/docs/plans/6.0-b2b-wholesale-shipping.md
@@ -353,8 +353,9 @@ Mechanics, scoped to the minimum that makes deposits real:
1. **Unit groundwork** — `Spree::Measurement`; `Variant#dimensions_unit`
store fallback (mirror of the existing `weight_unit` fallback).
2. **Schema** — `spree_package_types`; `carton_package_type_id` +
- `units_per_carton` + `carton_weight` + `cartons_per_pallet` on
- `spree_variants`; `unpriced` on `spree_delivery_rates`.
+ `carton_weight` + `cartons_per_pallet` on `spree_variants` (around the
+ `units_per_carton` `6.0-b2b-quantity-rules.md` already added);
+ `unpriced` on `spree_delivery_rates`.
3. **PackageType** — model, backfill task (`spree:package_types:backfill`)
creating default rows from the store preferences, `Stock::Package`
reading through the default row, preference deprecation bridges.
diff --git a/packages/dashboard-core/src/components/resource-picker-sheet.tsx b/packages/dashboard-core/src/components/resource-picker-sheet.tsx
index f0f90de519..a209f54ef9 100644
--- a/packages/dashboard-core/src/components/resource-picker-sheet.tsx
+++ b/packages/dashboard-core/src/components/resource-picker-sheet.tsx
@@ -172,7 +172,7 @@ export function ResourcePickerSheet<T extends PickerOption>({
type="button"
disabled={inList}
onClick={() => toggle(option)}
- className="flex w-full items-center gap-3 px-4 py-2.5 text-left hover:bg-muted/50 disabled:cursor-not-allowed disabled:opacity-60"
+ className="flex w-full items-center gap-3 px-4 py-2.5 text-left hover:bg-accent/50 disabled:cursor-not-allowed disabled:opacity-60"
>
<Checkbox
checked={checked}
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index 8ff7979e41..1901367077 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -1562,7 +1562,8 @@
"validation": {
"positive_integer": "أدخل عددًا صحيحًا أكبر من صفر، أو اترك الحقل فارغًا.",
"currency_taken": "هذه العملة لديها حد أدنى بالفعل.",
- "positive_amount": "أدخل مبلغًا أكبر من صفر."
+ "positive_amount": "أدخل مبلغًا أكبر من صفر.",
+ "fix_terms": "صحّح قواعد الكمية المميزة قبل الحفظ."
},
"mixed": "مختلط",
"inherits": "الافتراضي",
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index ab40570f18..4618e355b1 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -1557,7 +1557,8 @@
"validation": {
"positive_integer": "Geben Sie eine ganze Zahl größer als null ein oder lassen Sie das Feld leer.",
"currency_taken": "Für diese Währung gibt es bereits einen Mindestwert.",
- "positive_amount": "Geben Sie einen Betrag größer als null ein."
+ "positive_amount": "Geben Sie einen Betrag größer als null ein.",
+ "fix_terms": "Korrigieren Sie die markierten Mengenregeln, bevor Sie speichern."
},
"mixed": "Gemischt",
"inherits": "Standard",
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index 0566a4b20d..d10946212f 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -1559,7 +1559,8 @@
"validation": {
"positive_integer": "Enter a whole number greater than zero, or leave blank.",
"currency_taken": "This currency already has a minimum.",
- "positive_amount": "Enter an amount greater than zero."
+ "positive_amount": "Enter an amount greater than zero.",
+ "fix_terms": "Fix the highlighted quantity rules before saving."
},
"mixed": "Mixed",
"inherits": "Default",
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index b90fd92e39..ef7dde613f 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -1557,7 +1557,8 @@
"validation": {
"positive_integer": "Saisissez un nombre entier supérieur à zéro, ou laissez vide.",
"currency_taken": "Cette devise a déjà un minimum.",
- "positive_amount": "Saisissez un montant supérieur à zéro."
+ "positive_amount": "Saisissez un montant supérieur à zéro.",
+ "fix_terms": "Corrigez les règles de quantité signalées avant d’enregistrer."
},
"mixed": "Variable",
"inherits": "Par défaut",
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index 6cebe0eb35..763b512e46 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -1583,7 +1583,8 @@
"validation": {
"positive_integer": "Podaj liczbę całkowitą większą od zera lub pozostaw pole puste.",
"currency_taken": "Ta waluta ma już ustawione minimum.",
- "positive_amount": "Podaj kwotę większą od zera."
+ "positive_amount": "Podaj kwotę większą od zera.",
+ "fix_terms": "Popraw zaznaczone reguły ilości przed zapisaniem."
},
"mixed": "Różne",
"inherits": "Domyślne",
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index b738793ff9..e7d8707481 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -1556,7 +1556,8 @@
"validation": {
"positive_integer": "请输入大于零的整数,或留空。",
"currency_taken": "该币种已设置最低金额。",
- "positive_amount": "请输入大于零的金额。"
+ "positive_amount": "请输入大于零的金额。",
+ "fix_terms": "保存前请修正标记的数量规则。"
},
"mixed": "不一致",
"inherits": "默认",
diff --git a/packages/dashboard/src/components/spree/catalog-terms-card.tsx b/packages/dashboard/src/components/spree/catalog-terms-card.tsx
index 7ab3eabff3..49ff001c8b 100644
--- a/packages/dashboard/src/components/spree/catalog-terms-card.tsx
+++ b/packages/dashboard/src/components/spree/catalog-terms-card.tsx
@@ -262,6 +262,8 @@ export function catalogTermColumns({
/** What the term means, shown from the column heading. */
minimumHelp: string
multipleHelp: string
+ /** Shown under a cell holding something that cannot be a rule. */
+ invalid: string
mixed: string
defaultHint: string
}
@@ -310,6 +312,11 @@ export function catalogTermColumns({
// A row on its way out takes its terms with it, so editing them is
// meaningless — and the struck-through row already says so.
const disabled = !canEdit || row.pending === 'removed'
+ // An unusable entry is flagged where it was typed. Without this it
+ // normalizes to null on submit, which the API reads as "clear this
+ // override" — the merchant's rule would vanish with no error anywhere.
+ const minimumInvalid = isUnusable(entry?.minimum_order_quantity)
+ const multipleInvalid = isUnusable(entry?.order_multiple)
return (
<>
@@ -319,12 +326,14 @@ export function catalogTermColumns({
min={1}
step={1}
disabled={disabled}
+ aria-invalid={minimumInvalid}
aria-label={headers.minimumLabel}
placeholder={entry?.mixed ? headers.mixed : catalogMinimum || headers.defaultHint}
value={entry?.minimum_order_quantity ?? ''}
onChange={(event) => set(row.id, 'minimum_order_quantity', event.target.value)}
className="h-8"
/>
+ {minimumInvalid && <p className="mt-1 text-destructive text-xs">{headers.invalid}</p>}
</TableCell>
<TableCell>
<Input
@@ -332,12 +341,14 @@ export function catalogTermColumns({
min={1}
step={1}
disabled={disabled}
+ aria-invalid={multipleInvalid}
aria-label={headers.multipleLabel}
placeholder={entry?.mixed ? headers.mixed : catalogMultiple || headers.defaultHint}
value={entry?.order_multiple ?? ''}
onChange={(event) => set(row.id, 'order_multiple', event.target.value)}
className="h-8"
/>
+ {multipleInvalid && <p className="mt-1 text-destructive text-xs">{headers.invalid}</p>}
</TableCell>
</>
)
@@ -366,6 +377,24 @@ export function termsToFormValues(
)
}
+/**
+ * True when a cell holds something that is neither blank nor a usable rule.
+ * Blank is a valid answer — it means the product uses the catalog default.
+ */
+function isUnusable(value: string | undefined): boolean {
+ return !!value?.trim() && normalizeQuantityRule(value) === null
+}
+
+/**
+ * True when any staged cell holds an unusable entry, so the page refuses to
+ * save rather than send a value the API would read as "clear this rule".
+ */
+export function stagedTermsHaveErrors(terms: StagedProductTerms): boolean {
+ return Object.values(terms).some(
+ (entry) => isUnusable(entry.minimum_order_quantity) || isUnusable(entry.order_multiple),
+ )
+}
+
/** Terms as the API takes them, with blanks meaning "clear this product". */
export function stagedTermsToParams(
terms: Record<string, { minimum_order_quantity: string; order_multiple: string }>,
diff --git a/packages/dashboard/src/components/spree/sellers/seller-onboarding-card.tsx b/packages/dashboard/src/components/spree/sellers/seller-onboarding-card.tsx
index 94ff93b45f..36f69ea91e 100644
--- a/packages/dashboard/src/components/spree/sellers/seller-onboarding-card.tsx
+++ b/packages/dashboard/src/components/spree/sellers/seller-onboarding-card.tsx
@@ -63,7 +63,7 @@ export function SellerOnboardingCard({ seller, canEdit }: { seller: Seller; canE
{/* Open while there is something left to do; a finished checklist
folds away so the page leads with what still needs the operator. */}
<Collapsible defaultOpen={!seller.onboarding_complete}>
- <CollapsibleTrigger className="group flex w-full cursor-pointer items-center gap-3 p-4 text-left hover:bg-muted/50 border-border-subtle">
+ <CollapsibleTrigger className="group flex w-full cursor-pointer items-center gap-3 p-4 text-left hover:bg-accent/50 border-border-subtle">
<CardTitle>{t('admin.sellers.onboarding.title')}</CardTitle>
{seller.onboarding_complete ? (
<SharedStatusBadge status="complete" label={t('admin.sellers.onboarding.all_done')} />
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 22db8c54a0..efb92055c7 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -168,7 +168,8 @@
"validation": {
"positive_integer": "أدخل عددًا صحيحًا أكبر من صفر، أو اترك الحقل فارغًا.",
"currency_taken": "هذه العملة لديها حد أدنى بالفعل.",
- "positive_amount": "أدخل مبلغًا أكبر من صفر."
+ "positive_amount": "أدخل مبلغًا أكبر من صفر.",
+ "fix_terms": "صحّح قواعد الكمية المميزة قبل الحفظ."
},
"mixed": "مختلط",
"inherits": "الافتراضي",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 5863936538..383c1d7efc 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -168,7 +168,8 @@
"validation": {
"positive_integer": "Geben Sie eine ganze Zahl größer als null ein oder lassen Sie das Feld leer.",
"currency_taken": "Für diese Währung gibt es bereits einen Mindestwert.",
- "positive_amount": "Geben Sie einen Betrag größer als null ein."
+ "positive_amount": "Geben Sie einen Betrag größer als null ein.",
+ "fix_terms": "Korrigieren Sie die markierten Mengenregeln, bevor Sie speichern."
},
"mixed": "Gemischt",
"inherits": "Standard",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index d54530301e..cca2caab89 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -168,7 +168,8 @@
"validation": {
"positive_integer": "Enter a whole number greater than zero, or leave blank.",
"currency_taken": "This currency already has a minimum.",
- "positive_amount": "Enter an amount greater than zero."
+ "positive_amount": "Enter an amount greater than zero.",
+ "fix_terms": "Fix the highlighted quantity rules before saving."
},
"mixed": "Mixed",
"inherits": "Default",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 0dfaa4102e..d935758503 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -168,7 +168,8 @@
"validation": {
"positive_integer": "Saisissez un nombre entier supérieur à zéro, ou laissez vide.",
"currency_taken": "Cette devise a déjà un minimum.",
- "positive_amount": "Saisissez un montant supérieur à zéro."
+ "positive_amount": "Saisissez un montant supérieur à zéro.",
+ "fix_terms": "Corrigez les règles de quantité signalées avant d’enregistrer."
},
"mixed": "Variable",
"inherits": "Par défaut",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 7279823de9..6a31b48efc 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -170,7 +170,8 @@
"validation": {
"positive_integer": "Podaj liczbę całkowitą większą od zera lub pozostaw pole puste.",
"currency_taken": "Ta waluta ma już ustawione minimum.",
- "positive_amount": "Podaj kwotę większą od zera."
+ "positive_amount": "Podaj kwotę większą od zera.",
+ "fix_terms": "Popraw zaznaczone reguły ilości przed zapisaniem."
},
"mixed": "Różne",
"inherits": "Domyślne",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 779812bf61..f8e4da1e23 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -168,7 +168,8 @@
"validation": {
"positive_integer": "请输入大于零的整数,或留空。",
"currency_taken": "该币种已设置最低金额。",
- "positive_amount": "请输入大于零的金额。"
+ "positive_amount": "请输入大于零的金额。",
+ "fix_terms": "保存前请修正标记的数量规则。"
},
"mixed": "不一致",
"inherits": "默认",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx
index 2c7785bec2..bb8d612eb7 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx
@@ -392,7 +392,7 @@ function SubUnitsCard({ company, canEdit }: { company: Company; canEdit: boolean
key={child.id}
to={'/$storeId/companies/$companyId' as string}
params={{ storeId, companyId: child.id }}
- className="flex items-center justify-between gap-3 border-b px-6 py-3 no-underline last:border-b-0 hover:bg-muted/50"
+ className="flex items-center justify-between gap-3 border-b px-6 py-3 no-underline last:border-b-0 hover:bg-accent/50"
>
<span className="flex min-w-0 items-center gap-2">
<span className="truncate font-medium text-foreground text-sm">{child.name}</span>
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 51913a23ee..3b36f5d251 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
@@ -49,6 +49,7 @@ import { CatalogPricingFields } from '../../../../../components/spree/catalog-pr
import {
CatalogTermsCard,
catalogTermColumns,
+ stagedTermsHaveErrors,
stagedTermsToParams,
termsToFormValues,
} from '../../../../../components/spree/catalog-terms-card'
@@ -158,6 +159,14 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
}
async function handleSave(values: CatalogFormValues) {
+ // Refused here rather than normalized away: an unusable cell would be
+ // sent as null, which the API reads as "clear this override", so the
+ // merchant's rule would disappear instead of being corrected.
+ if (stagedTermsHaveErrors(values.staged_terms ?? {})) {
+ form.setError('root', { message: t('admin.catalogs.terms.validation.fix_terms') })
+ return
+ }
+
try {
// A product on its way out takes its terms with it, so its cells are
// dropped rather than sent — the save would otherwise re-create rows
@@ -251,6 +260,7 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
multipleLabel: t('admin.fields.order_multiple.label'),
minimumHelp: t('admin.catalogs.terms.help.minimum'),
multipleHelp: t('admin.catalogs.terms.help.multiple'),
+ invalid: t('admin.catalogs.terms.validation.positive_integer'),
mixed: t('admin.catalogs.terms.mixed'),
defaultHint: t('admin.catalogs.terms.inherits'),
},
diff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rb
index e89e32cb7b..996fb63164 100644
--- a/spree/core/app/models/spree/current.rb
+++ b/spree/core/app/models/spree/current.rb
@@ -104,6 +104,12 @@ module Spree
# @return [Array<Spree::Catalog>]
def catalogs_for(company: nil, user: nil, channel: nil)
channel ||= self.channel
+ # Normalized before the key is built, not just before the query: the
+ # key is an id, so an admin and a customer sharing one would otherwise
+ # share an entry and whichever resolved first would decide for both.
+ # Only a customer has customer-group catalogs to resolve.
+ user = nil unless user.is_a?(Spree.customer_class)
+
key = [store&.id, company&.id, user&.id, channel&.id]
applicable_catalogs[key] ||= Spree::Catalog.for_context(
store: store, company: company, user: user, channel: channel
diff --git a/spree/core/app/services/spree/catalogs/set_product_terms.rb b/spree/core/app/services/spree/catalogs/set_product_terms.rb
index 67103e5c30..f1152172d0 100644
--- a/spree/core/app/services/spree/catalogs/set_product_terms.rb
+++ b/spree/core/app/services/spree/catalogs/set_product_terms.rb
@@ -23,17 +23,30 @@ module Spree
foreign = terms.keys.reject { |product| product.store_id == catalog.store_id }
return failure(catalog, Spree.t('catalogs.product_not_in_store')) if foreign.any?
+ invalid = nil
+
ApplicationRecord.transaction do
catalog.add_products(terms.keys.reject { |product| catalog.product_ids.include?(product.id) }.map(&:id))
- terms.each { |product, values| apply(catalog, product, values) }
+ terms.each do |product, values|
+ invalid = apply(catalog, product, values)
+ # A plain service's `failure` returns rather than raising, so one
+ # bad row has to take the transaction down itself — otherwise the
+ # rest of the set commits, the products are added, and the caller
+ # is told the whole thing worked.
+ raise ActiveRecord::Rollback if invalid
+ end
end
+ return failure(invalid) if invalid
+
success(catalog.reload)
end
private
+ # @return [Spree::CatalogQuantityRule, nil] the first row that would not
+ # save, so the caller can roll the whole set back
def apply(catalog, product, values)
minimum = normalize(values[:minimum_order_quantity])
multiple = normalize(values[:order_multiple])
@@ -43,22 +56,27 @@ module Spree
# own default, which is what an empty pair means on the row.
if minimum.nil? && multiple.nil?
catalog.quantity_rules.where(variant_id: variant_ids).destroy_all
- return
+ return nil
end
variant_ids.each do |variant_id|
rule = catalog.quantity_rules.find_or_initialize_by(variant_id: variant_id)
rule.assign_attributes(minimum_order_quantity: minimum, order_multiple: multiple)
- failure(rule) unless rule.save
+ return rule unless rule.save
end
+
+ nil
end
# A blank arrives as nil or an empty string depending on the client;
- # both mean "say nothing", which is not the same as zero.
+ # both mean "say nothing", which is not the same as zero. Anything else
+ # is passed through as given — a negative or fractional entry has to
+ # reach the model's validation and be refused, not be coerced into a
+ # different rule than the merchant typed.
def normalize(value)
return nil if value.nil? || value.to_s.strip.empty?
- value.to_i
+ value
end
end
end
diff --git a/spree/core/spec/models/spree/catalog_for_buyer_spec.rb b/spree/core/spec/models/spree/catalog_for_buyer_spec.rb
index 1e2bc1d0b6..18c1f62f33 100644
--- a/spree/core/spec/models/spree/catalog_for_buyer_spec.rb
+++ b/spree/core/spec/models/spree/catalog_for_buyer_spec.rb
@@ -83,6 +83,26 @@ RSpec.describe Spree::Catalog, '.for_buyer' do
expect(Spree::Current.standing_company_for(customer)).to eq(company)
end
+ # The same collision one level up: the catalog memo is keyed on an id too,
+ # so a non-customer must not reach it in either order.
+ it 'keeps a non-customer out of the catalog memo in either order' do
+ group = create(:customer_group, store: store)
+ grouped = create(:user)
+ grouped.customer_groups << group
+ group_catalog = create(:catalog, store: store)
+ create(:catalog_assignment, catalog: group_catalog, assignable: group)
+ Spree::Current.store = store
+ impostor = Struct.new(:id).new(grouped.id)
+
+ Spree::Current.reset_catalog_memos
+ expect(Spree::Current.catalogs_for(user: grouped)).to eq([group_catalog])
+ expect(Spree::Current.catalogs_for(user: impostor)).to be_empty
+
+ Spree::Current.reset_catalog_memos
+ expect(Spree::Current.catalogs_for(user: impostor)).to be_empty
+ expect(Spree::Current.catalogs_for(user: grouped)).to eq([group_catalog])
+ end
+
it 'is empty without a store' do
expect(described_class.for_buyer(store: nil, customer: customer)).to eq([])
end
diff --git a/spree/core/spec/services/spree/catalogs/set_product_terms_spec.rb b/spree/core/spec/services/spree/catalogs/set_product_terms_spec.rb
index 3f5fab46e3..532e84d640 100644
--- a/spree/core/spec/services/spree/catalogs/set_product_terms_spec.rb
+++ b/spree/core/spec/services/spree/catalogs/set_product_terms_spec.rb
@@ -15,7 +15,7 @@ RSpec.describe Spree::Catalogs::SetProductTerms do
apply(product => { minimum_order_quantity: 48, order_multiple: 24 })
rules = catalog.quantity_rules.reload
- expect(rules.count).to eq(product.variants_including_master.count)
+ expect(rules.count).to eq(product.variants.count)
expect(rules.map(&:minimum_order_quantity).uniq).to eq([48])
end
@@ -67,6 +67,31 @@ RSpec.describe Spree::Catalogs::SetProductTerms do
expect(catalog.quantity_rules.reload).to be_empty
end
+ # The set applies whole or not at all: a partial write would leave the
+ # agreement in a state the merchant never asked for, and the products would
+ # have been added on the way.
+ it 'rolls the whole set back when one product\'s terms are unusable' do
+ other = create(:product, store: store)
+
+ result = apply(
+ product => { minimum_order_quantity: 48 },
+ other => { minimum_order_quantity: -5 }
+ )
+
+ expect(result).to be_failure
+ expect(catalog.quantity_rules.reload).to be_empty
+ expect(catalog.products.reload).to be_empty
+ end
+
+ # Coercing would save a different rule than the one typed — the same silent
+ # adjustment the whole feature exists to prevent.
+ it 'refuses a fractional quantity rather than truncating it' do
+ result = apply(product => { minimum_order_quantity: '2.5' })
+
+ expect(result).to be_failure
+ expect(catalog.quantity_rules.reload).to be_empty
+ end
+
it 'does nothing for an empty payload' do
expect(apply({})).to be_success
end