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
Close the gaps the second review found
Damian Legawiecaa824c0b230c
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.jsonindex 8a4bb6f8d0..981598d792 100644--- a/packages/dashboard-core/src/locales/ar.json+++ b/packages/dashboard-core/src/locales/ar.json@@ -825,7 +825,8 @@},"units_per_carton": {"label": "الوحدات في الكرتونة"- }+ },+ "quantity_rule_invalid": "أدخل عددًا صحيحًا أكبر من صفر، أو اترك الحقل فارغًا."},"minimum_order_quantity": {"label": "الحد الأدنى لكمية الطلب",diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.jsonindex a43b298282..553e901259 100644--- a/packages/dashboard-core/src/locales/de.json+++ b/packages/dashboard-core/src/locales/de.json@@ -825,7 +825,8 @@},"units_per_carton": {"label": "Stück pro Karton"- }+ },+ "quantity_rule_invalid": "Geben Sie eine ganze Zahl größer als null ein oder lassen Sie das Feld leer."},"minimum_order_quantity": {"label": "Mindestbestellmenge",diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.jsonindex 3ae05fa0a2..175d4d7d1f 100644--- a/packages/dashboard-core/src/locales/en.json+++ b/packages/dashboard-core/src/locales/en.json@@ -827,7 +827,8 @@},"units_per_carton": {"label": "Units per carton"- }+ },+ "quantity_rule_invalid": "Enter a whole number greater than zero, or leave blank."},"minimum_order_quantity": {"label": "Minimum order quantity",diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.jsonindex 4576c219a7..60e84ff01d 100644--- a/packages/dashboard-core/src/locales/fr.json+++ b/packages/dashboard-core/src/locales/fr.json@@ -825,7 +825,8 @@},"units_per_carton": {"label": "Unités par carton"- }+ },+ "quantity_rule_invalid": "Saisissez un nombre entier supérieur à zéro, ou laissez vide."},"minimum_order_quantity": {"label": "Quantité minimale de commande",diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.jsonindex ff35e16d18..14f8f93b0d 100644--- a/packages/dashboard-core/src/locales/pl.json+++ b/packages/dashboard-core/src/locales/pl.json@@ -825,7 +825,8 @@},"units_per_carton": {"label": "Sztuk w kartonie"- }+ },+ "quantity_rule_invalid": "Podaj liczbę całkowitą większą od zera lub pozostaw pole puste."},"minimum_order_quantity": {"label": "Minimalna wielkość zamówienia",diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.jsonindex ebbb0a0b89..8d741cfdf3 100644--- a/packages/dashboard-core/src/locales/zh-CN.json+++ b/packages/dashboard-core/src/locales/zh-CN.json@@ -825,7 +825,8 @@},"units_per_carton": {"label": "每箱件数"- }+ },+ "quantity_rule_invalid": "请输入大于零的整数,或留空。"},"minimum_order_quantity": {"label": "最小起订量",diff --git a/packages/dashboard-core/src/products/product-form-mapping.ts b/packages/dashboard-core/src/products/product-form-mapping.tsindex 55cae40971..964cb760ee 100644--- a/packages/dashboard-core/src/products/product-form-mapping.ts+++ b/packages/dashboard-core/src/products/product-form-mapping.ts@@ -1,4 +1,5 @@import { i18n } from '../lib/i18n'+import { normalizeQuantityRule } from './normalize-quantity'import type { MediaType, ProductFormValues, VariantFormValues } from './product-schema'import type { PanelMedia, PanelProduct, PanelVariant } from './product-types'@@ -31,10 +32,10 @@ export function variantToFormValues(variant: PanelVariant, position: number): Vahs_code: variant.hs_code ?? null,country_of_origin: variant.country_of_origin ?? null,customs_description: variant.customs_description ?? null,- minimum_order_quantity: variant.minimum_order_quantity ?? null,- order_multiple: variant.order_multiple ?? null,+ minimum_order_quantity: variant.minimum_order_quantity?.toString() ?? null,+ order_multiple: variant.order_multiple?.toString() ?? null,purchase_unit: variant.purchase_unit ?? null,- units_per_carton: variant.units_per_carton ?? null,+ units_per_carton: variant.units_per_carton?.toString() ?? null,track_inventory: variant.track_inventory,preorderable: variant.preorderable ?? false,preorder_ships_at: variant.preorder_ships_at ?? null,@@ -177,10 +178,10 @@ export function variantToWirePayload(v: VariantFormValues, index: number) {hs_code: v.hs_code ?? null,country_of_origin: v.country_of_origin ?? null,customs_description: v.customs_description ?? null,- minimum_order_quantity: v.minimum_order_quantity ?? null,- order_multiple: v.order_multiple ?? null,+ minimum_order_quantity: normalizeQuantityRule(v.minimum_order_quantity),+ order_multiple: normalizeQuantityRule(v.order_multiple),purchase_unit: v.purchase_unit ?? null,- units_per_carton: v.units_per_carton ?? null,+ units_per_carton: normalizeQuantityRule(v.units_per_carton),}if (v.id) payload.id = v.idif (v.track_inventory != null) payload.track_inventory = v.track_inventorydiff --git a/packages/dashboard-core/src/products/product-schema.ts b/packages/dashboard-core/src/products/product-schema.tsindex 68047c8205..1136c4bb38 100644--- a/packages/dashboard-core/src/products/product-schema.ts+++ b/packages/dashboard-core/src/products/product-schema.ts@@ -1,7 +1,21 @@import { requiredMessage } from '@spree/dashboard-ui'+import i18n from 'i18next'import { z } from 'zod/v4'+import { normalizeQuantityRule } from './normalize-quantity'import { isSupportedVideoUrl } from './video-url'+/**+ * A purchasing rule as typed. Blank means the rule is unset — a valid+ * answer — so only a non-blank entry that normalizes away is an error.+ */+const quantityRuleField = z+ .string()+ .nullable()+ .optional()+ .refine((value) => !value?.trim() || normalizeQuantityRule(value) !== null, {+ error: () => i18n.t('admin.fields.variant.quantity_rule_invalid'),+ })+export const stockLevelFormSchema = z.object({id: z.string().optional(),stock_location_id: z.string(),@@ -49,10 +63,13 @@ export const variantFormSchema = z.object({hs_code: z.string().nullable().optional(),country_of_origin: z.string().nullable().optional(),customs_description: z.string().nullable().optional(),- minimum_order_quantity: z.number().int().positive().nullable().optional(),- order_multiple: z.number().int().positive().nullable().optional(),+ // Held as strings so an unusable entry can be reported rather than+ // silently coerced away: normalizing `0` straight to null would clear the+ // rule while the merchant believes they set one.+ minimum_order_quantity: quantityRuleField,+ order_multiple: quantityRuleField,purchase_unit: z.string().nullable().optional(),- units_per_carton: z.number().int().positive().nullable().optional(),+ units_per_carton: quantityRuleField,track_inventory: z.boolean().optional(),preorderable: z.boolean().optional(),preorder_ships_at: z.string().nullable().optional(),@@ -275,10 +292,10 @@ export function isPlaceholderDefaultVariant(v: VariantFormValues): boolean {!v.hs_code &&!v.country_of_origin &&!v.customs_description &&- v.minimum_order_quantity == null &&- v.order_multiple == null &&+ !v.minimum_order_quantity &&+ !v.order_multiple &&v.purchase_unit == null &&- v.units_per_carton == null &&+ !v.units_per_carton &&v.preorderable !== true &&v.preorder_ships_at == null &&v.backorder_limit == null &&diff --git a/packages/dashboard-core/src/products/variant-edit-sheet.tsx b/packages/dashboard-core/src/products/variant-edit-sheet.tsxindex 217e236e79..3b91bc0db2 100644--- a/packages/dashboard-core/src/products/variant-edit-sheet.tsx+++ b/packages/dashboard-core/src/products/variant-edit-sheet.tsx@@ -22,7 +22,7 @@ import { useEffect, useRef } from 'react'import { Controller, type UseFormReturn } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { normalizeCustomsDescription, normalizeHsCode } from './normalize-customs'-import { normalizeQuantityRule, PURCHASE_UNITS } from './normalize-quantity'+import { PURCHASE_UNITS } from './normalize-quantity'import {useFormOptionTypes as useOptionTypes,useFormTaxCategories as useTaxCategories,@@ -343,9 +343,7 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Promin="1"step="1"placeholder={t('admin.fields.variant.minimum_order_quantity.placeholder')}- {...form.register(`variants.${variantIndex}.minimum_order_quantity`, {- setValueAs: normalizeQuantityRule,- })}+ {...form.register(`variants.${variantIndex}.minimum_order_quantity`)}/><FieldErrorerrors={[form.formState.errors.variants?.[variantIndex]?.minimum_order_quantity]}@@ -361,9 +359,7 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Promin="1"step="1"placeholder={t('admin.fields.variant.order_multiple.placeholder')}- {...form.register(`variants.${variantIndex}.order_multiple`, {- setValueAs: normalizeQuantityRule,- })}+ {...form.register(`variants.${variantIndex}.order_multiple`)}/><FieldErrorerrors={[form.formState.errors.variants?.[variantIndex]?.order_multiple]}@@ -413,9 +409,7 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Protype="number"min="1"step="1"- {...form.register(`variants.${variantIndex}.units_per_carton`, {- setValueAs: normalizeQuantityRule,- })}+ {...form.register(`variants.${variantIndex}.units_per_carton`)}/><FieldErrorerrors={[form.formState.errors.variants?.[variantIndex]?.units_per_carton]}diff --git a/packages/dashboard/src/components/spree/catalog-terms-card.tsx b/packages/dashboard/src/components/spree/catalog-terms-card.tsxindex 9183596c0b..6f50c5fbbd 100644--- a/packages/dashboard/src/components/spree/catalog-terms-card.tsx+++ b/packages/dashboard/src/components/spree/catalog-terms-card.tsx@@ -35,7 +35,7 @@ import {useConfirm,} from '@spree/dashboard-ui'import { PlusIcon, XIcon } from 'lucide-react'-import { useState } from 'react'+import { useEffect, useState } from 'react'import type { UseFormReturn } from 'react-hook-form'import { useTranslation } from 'react-i18next'import {@@ -318,6 +318,13 @@ function QuantityRulesSection({ catalogId, canEdit }: { catalogId: string; canEdconst deleteMutation = useDeleteCatalogQuantityRule(catalogId)const rules = data?.data ?? []+ const lastPage = data?.meta?.pages ?? 1++ // Deleting the last row on the last page would otherwise strand the+ // merchant on an empty page while earlier ones still have rows.+ useEffect(() => {+ if (page > lastPage) setPage(lastPage)+ }, [page, lastPage])async function handleDelete(rule: CatalogQuantityRule) {const confirmed = await confirm({diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex f1ac961f2a..6f2cacf16a 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -2184,7 +2184,8 @@},"units_per_carton": {"label": "الوحدات في الكرتونة"- }+ },+ "quantity_rule_invalid": "أدخل عددًا صحيحًا أكبر من صفر، أو اترك الحقل فارغًا."},"webhook_endpoint": {"active": {diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 110c83663d..a36806f53f 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -2170,7 +2170,8 @@},"units_per_carton": {"label": "Stück pro Karton"- }+ },+ "quantity_rule_invalid": "Geben Sie eine ganze Zahl größer als null ein oder lassen Sie das Feld leer."},"webhook_endpoint": {"active": {diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex a64bf84cf9..ad54ecb7ab 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -2170,7 +2170,8 @@},"units_per_carton": {"label": "Units per carton"- }+ },+ "quantity_rule_invalid": "Enter a whole number greater than zero, or leave blank."},"webhook_endpoint": {"active": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex d92c1939b6..c50fc2605d 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -2170,7 +2170,8 @@},"units_per_carton": {"label": "Unités par carton"- }+ },+ "quantity_rule_invalid": "Saisissez un nombre entier supérieur à zéro, ou laissez vide."},"webhook_endpoint": {"active": {diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 9875c8fc14..01b470762f 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -2182,7 +2182,8 @@},"units_per_carton": {"label": "Sztuk w kartonie"- }+ },+ "quantity_rule_invalid": "Podaj liczbę całkowitą większą od zera lub pozostaw pole puste."},"webhook_endpoint": {"active": {diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 70b8d82d13..c156faf7f3 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -2166,7 +2166,8 @@},"units_per_carton": {"label": "每箱件数"- }+ },+ "quantity_rule_invalid": "请输入大于零的整数,或留空。"},"webhook_endpoint": {"active": {diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsxindex 4c943d518d..5d2dacdcb5 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx@@ -128,10 +128,10 @@ function NewProductPage() {v.hs_code != null ||v.country_of_origin != null ||v.customs_description != null ||- v.minimum_order_quantity != null ||- v.order_multiple != null ||+ !!v.minimum_order_quantity ||+ !!v.order_multiple ||v.purchase_unit != null ||- v.units_per_carton != null ||+ !!v.units_per_carton ||v.track_inventory === false ||v.preorderable === true ||v.preorder_ships_at != null ||diff --git a/spree/api/app/serializers/spree/api/v3/base_serializer.rb b/spree/api/app/serializers/spree/api/v3/base_serializer.rbindex 3511e009a9..5a65303202 100644--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb@@ -123,7 +123,7 @@ module Spreereturn Spree::QuantityRule.new if current_store.nil?Spree::Current.quantity_rules_resolver_for(- company: Spree::Company.sole_standing_for(store: current_store, customer: current_user),+ company: Spree::Current.standing_company_for(current_user),user: current_user).call(variant)enddiff --git a/spree/core/app/models/concerns/spree/purchase/quantity_rules.rb b/spree/core/app/models/concerns/spree/purchase/quantity_rules.rbindex d522f6545d..302c6aa6cd 100644--- a/spree/core/app/models/concerns/spree/purchase/quantity_rules.rb+++ b/spree/core/app/models/concerns/spree/purchase/quantity_rules.rb@@ -11,19 +11,25 @@ module Spreemodule QuantityRulesextend ActiveSupport::Concern- # True when staff keyed this purchase in rather than a buyer building it.- # Two signals, because either alone leaves a gap: a draft order is the- # admin surface whether or not a creator was recorded (both draft- # workflows take `created_by` optionally), and a cart cannot carry one- # at all.+ # True when this purchase is staff's to key in rather than a buyer's to+ # build. Two signals, because either alone leaves a gap: an incomplete+ # order is the admin draft surface whether or not a creator was+ # recorded (both draft workflows take `created_by` optionally), and a+ # cart cannot carry one at all.## Staff are unrestricted by the quantity terms — an admin is entering# what the buyer actually negotiated, and refusing it would make an# agreed exception impossible to record.#+ # A placed order is nobody's draft, so it is excluded: post-placement+ # item changes go through the admin surface with a creator, and the+ # exemption should come from that rather than from the sale having+ # already happened.+ ## @return [Boolean]def staff_initiated?- is_a?(Spree::Order) || (respond_to?(:created_by_id) && created_by_id.present?)+ (is_a?(Spree::Order) && !completed?) ||+ (respond_to?(:created_by_id) && created_by_id.present?)end# Why this buyer may not order that many of a variant, naming what they@@ -93,7 +99,10 @@ module Spree## @return [Array<Array(Spree::LineItem, String)>]def quantity_rule_violations- return [] if staff_initiated?+ # A placed order is history: its terms were checked when it was+ # placed, and re-reporting them against today's agreement would+ # accuse a completed sale of breaking a rule written after it.+ return [] if staff_initiated? || (is_a?(Spree::Order) && completed?)line_items.filter_map do |line_item|variant = line_item.variantdiff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rbindex f577c4a8cb..d1ed62e046 100644--- a/spree/core/app/models/spree/catalog.rb+++ b/spree/core/app/models/spree/catalog.rb@@ -171,12 +171,12 @@ module Spreedef self.for_buyer(store:, customer: nil, company: nil, channel: nil)return [] if store.nil?- company ||= Spree::Company.sole_standing_for(store: store, customer: customer)- channel ||= Spree::Current.channel if store == Spree::Current.store-if store == Spree::Current.store+ company ||= Spree::Current.standing_company_for(customer)+ channel ||= Spree::Current.channelSpree::Current.catalogs_for(company: company, user: customer, channel: channel)else+ company ||= Spree::Company.sole_standing_for(store: store, customer: customer)for_context(store: store, company: company, user: customer, channel: channel)endend@@ -303,6 +303,10 @@ module Spreenext if removed.zero?price_list&.remove_products(product_ids)+ # Terms go with the products they were stated for. Left behind, a+ # merchant who removes a SKU and later re-adds it gets the old+ # minimum back — terms they believe they deleted.+ quantity_rules.where(variant_id: Spree::Variant.where(product_id: product_ids).select(:id)).delete_alltouchenddiff --git a/spree/core/app/models/spree/company.rb b/spree/core/app/models/spree/company.rbindex d57a824a1a..bf23d89288 100644--- a/spree/core/app/models/spree/company.rb+++ b/spree/core/app/models/spree/company.rb@@ -123,11 +123,16 @@ module Spree# @param customer [Object, nil]# @return [Spree::Company, nil]def self.sole_standing_for(store:, customer:)- return nil if customer.nil? || store.nil?-- # Two rather than one-per-membership: `joins` does not populate the- # association, so reading `.company` off each row would be an N+1 on a- # path a product listing takes for every request.+ return nil if store.nil?+ # Matching a bare id would resolve a company for anything answering+ # #id — an admin user sharing an id with a customer, a value object off+ # a request — so the type is checked rather than assumed. Standing is a+ # customer's fact about a business, and nothing else has it.+ return nil unless customer.is_a?(Spree.customer_class)++ # Two rows at most: the question is only "exactly one, or not". Joined+ # rather than read off each membership, because `joins` does not+ # populate the association and a product listing takes this path.companies = where(store_id: store.id).joins(:memberships).where(Spree::CompanyMembership.table_name => { customer_id: customer.id }).diff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rbindex 089c6540b8..fb59f43e82 100644--- a/spree/core/app/models/spree/current.rb+++ b/spree/core/app/models/spree/current.rb@@ -4,7 +4,7 @@ module Spree# All attributes are automatically reset between requests by Rails.# Fallback chains ensure sensible defaults when attributes are not explicitly set.class Current < ::ActiveSupport::CurrentAttributes- attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :applicable_catalogs, :quantity_rules_resolvers, :global_pricing_context, :provider_cache, :integrations+ attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :applicable_catalogs, :quantity_rules_resolvers, :standing_companies, :global_pricing_context, :provider_cache, :integrations# Scratch space for provider strategies to memoize a call across the# request — part of the delivery rate provider contract (nothing in core@@ -139,6 +139,27 @@ module Spreesuper || (self.quantity_rules_resolvers = {})end+ # The company a customer unambiguously buys for in this request. Resolved+ # once: catalog resolution asks for it on every entry, and a product+ # listing prices every variant through that path — unmemoized it was two+ # queries per row.+ #+ # @param customer [Object, nil]+ # @return [Spree::Company, nil]+ def standing_company_for(customer)+ return nil if store.nil? || customer.nil?++ key = [store.id, customer.id]+ return standing_companies[key] if standing_companies.key?(key)++ standing_companies[key] = Spree::Company.sole_standing_for(store: store, customer: customer)+ end++ # @return [Hash]+ def standing_companies+ super || (self.standing_companies = {})+ end+# Drops everything derived from the catalog set, so a write in this# request is not read back through a memo it has already superseded.# One call rather than a list every caller has to keep in step.@@ -146,6 +167,7 @@ module Spreedef reset_catalog_memosself.applicable_catalogs = nilself.quantity_rules_resolvers = nil+ self.standing_companies = nilself.price_lists = nilenddiff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex ae8e93e2ac..e0b0a82626 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -46,6 +46,12 @@ module Spreebefore_destroy :ensure_not_in_complete_ordersafter_destroy :remove_line_items_from_incomplete_orders+ # Terms stated for this variant go with it. Nothing below the cart layer+ # reads them, but a row pointing at a destroyed variant would resolve for+ # nobody and count against the agreement's overrides forever.+ has_many :catalog_quantity_rules, class_name: 'Spree::CatalogQuantityRule',+ dependent: :destroy, inverse_of: :variant+with_options inverse_of: :variant dohas_many :fulfillment_items, class_name: 'Spree::FulfillmentItem'has_many :line_itemsdiff --git a/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb b/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rbindex 9bd39c9158..21bd415f9c 100644--- a/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb+++ b/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb@@ -83,7 +83,7 @@ module Spreedef self.catalogs_for(purchase)Spree::Catalog.for_buyer(store: purchase.store,- customer: purchase.try(:user),+ customer: purchase.try(:customer),company: purchase.try(:resolved_company),channel: purchase.try(:channel))@@ -94,13 +94,16 @@ module Spreeattr_reader :catalogs- # Loaded per catalog on first touch and kept: a cart asks about many- # variants against the same few catalogs, and one query each beats one- # query per line.+ # One indexed row read per (catalog, variant), memoized: an agreement+ # may state terms for thousands of SKUs, so loading the whole table to+ # answer about one variant would put that on the add-to-cart path. The+ # composite unique index makes the keyed read cheap.def override_for(catalog, variant)@overrides ||= {}- @overrides[catalog.id] ||= catalog.quantity_rules.index_by(&:variant_id)- @overrides[catalog.id][variant.id]+ key = [catalog.id, variant.id]+ return @overrides[key] if @overrides.key?(key)++ @overrides[key] = catalog.quantity_rules.find_by(variant_id: variant.id)enddef minimums_for(catalog)diff --git a/spree/core/spec/models/spree/catalog_for_buyer_spec.rb b/spree/core/spec/models/spree/catalog_for_buyer_spec.rbindex dd05d13b19..7cf9714f89 100644--- a/spree/core/spec/models/spree/catalog_for_buyer_spec.rb+++ b/spree/core/spec/models/spree/catalog_for_buyer_spec.rb@@ -43,6 +43,31 @@ RSpec.describe Spree::Catalog, '.for_buyer' doexpect(described_class.for_buyer(store: store, customer: other_customer)).to be_emptyend+ # A bare id match would resolve a company for anything answering #id — an+ # admin user sharing an id with a customer, a value object off a request.+ it 'resolves nothing for a non-customer that merely answers to an id' do+ impostor = Struct.new(:id).new(customer.id)++ expect(described_class.for_buyer(store: store, customer: impostor)).to be_empty+ expect(Spree::Company.sole_standing_for(store: store, customer: impostor)).to be_nil+ end++ # Catalog resolution asks for the company on every entry, and a listing+ # prices every variant through that path.+ it 'resolves the buyer only once per request' do+ Spree::Current.store = store+ Spree::Current.reset_catalog_memos+ queries = 0+ subscriber = ActiveSupport::Notifications.subscribe('sql.active_record') do |*, payload|+ queries += 1 if payload[:sql].to_s.include?('spree_companies')+ end++ 5.times { described_class.for_buyer(store: store, customer: customer) }+ ActiveSupport::Notifications.unsubscribe(subscriber)++ expect(queries).to eq(1)+ end+it 'is empty without a store' doexpect(described_class.for_buyer(store: nil, customer: customer)).to eq([])enddiff --git a/spree/core/spec/models/spree/catalog_quantity_rule_spec.rb b/spree/core/spec/models/spree/catalog_quantity_rule_spec.rbindex e41aa0c77b..b398bcec9a 100644--- a/spree/core/spec/models/spree/catalog_quantity_rule_spec.rb+++ b/spree/core/spec/models/spree/catalog_quantity_rule_spec.rb@@ -44,6 +44,25 @@ RSpec.describe Spree::CatalogQuantityRule do}.to raise_error(ActiveRecord::RecordNotUnique)end+ # Terms go with the products they were stated for: left behind, a merchant+ # who removes a SKU and later re-adds it gets the old minimum back.+ it 'is removed when its product leaves the assortment' do+ catalog.add_products([variant.product_id])+ create(:catalog_quantity_rule, catalog: catalog, variant: variant)++ catalog.remove_products([variant.product_id])++ expect(catalog.quantity_rules.reload).to be_empty+ end++ it 'is removed with the variant it names' do+ create(:catalog_quantity_rule, catalog: catalog, variant: variant)++ variant.destroy++ expect(catalog.quantity_rules.reload).to be_empty+ end+it 'refuses a zero or negative quantity' doexpect(build(:catalog_quantity_rule, catalog: catalog, variant: variant, minimum_order_quantity: 0)).not_to be_validexpect(build(:catalog_quantity_rule, catalog: catalog, variant: variant, order_multiple: -2)).not_to be_valid