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
Fix two quantity-rule resolution bugs found in review
Damian Legawiec3fac18b1c5e4
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.jsonindex e9d55d82f0..8a4bb6f8d0 100644--- a/packages/dashboard-core/src/locales/ar.json+++ b/packages/dashboard-core/src/locales/ar.json@@ -1573,7 +1573,8 @@"remove_rule_description": "سيعود {{name}} إلى الإعداد الافتراضي للكتالوج. يسري هذا فورًا.","validation": {"positive_integer": "أدخل عددًا صحيحًا أكبر من صفر، أو اترك الحقل فارغًا.",- "currency_taken": "هذه العملة لديها حد أدنى بالفعل."+ "currency_taken": "هذه العملة لديها حد أدنى بالفعل.",+ "positive_amount": "أدخل مبلغًا أكبر من صفر."},"messages": {"rule_created": "تمت إضافة قاعدة المنتج",diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.jsonindex 646bcc12c8..a43b298282 100644--- a/packages/dashboard-core/src/locales/de.json+++ b/packages/dashboard-core/src/locales/de.json@@ -1568,7 +1568,8 @@"remove_rule_description": "{{name}} nutzt wieder den Katalogstandard. Dies wirkt sofort.","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."+ "currency_taken": "Für diese Währung gibt es bereits einen Mindestwert.",+ "positive_amount": "Geben Sie einen Betrag größer als null ein."},"messages": {"rule_created": "Produktregel hinzugefügt",diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.jsonindex ee00449952..3ae05fa0a2 100644--- a/packages/dashboard-core/src/locales/en.json+++ b/packages/dashboard-core/src/locales/en.json@@ -1570,7 +1570,8 @@"remove_rule_description": "{{name}} will fall back to the catalog default. This takes effect immediately.","validation": {"positive_integer": "Enter a whole number greater than zero, or leave blank.",- "currency_taken": "This currency already has a minimum."+ "currency_taken": "This currency already has a minimum.",+ "positive_amount": "Enter an amount greater than zero."},"messages": {"rule_created": "Product rule added",diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.jsonindex be2b03b478..4576c219a7 100644--- a/packages/dashboard-core/src/locales/fr.json+++ b/packages/dashboard-core/src/locales/fr.json@@ -1568,7 +1568,8 @@"remove_rule_description": "{{name}} reviendra à la valeur par défaut du catalogue. Effet immédiat.","validation": {"positive_integer": "Saisissez un nombre entier supérieur à zéro, ou laissez vide.",- "currency_taken": "Cette devise a déjà un minimum."+ "currency_taken": "Cette devise a déjà un minimum.",+ "positive_amount": "Saisissez un montant supérieur à zéro."},"messages": {"rule_created": "Règle produit ajoutée",diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.jsonindex 0a2896c204..ff35e16d18 100644--- a/packages/dashboard-core/src/locales/pl.json+++ b/packages/dashboard-core/src/locales/pl.json@@ -1594,7 +1594,8 @@"remove_rule_description": "{{name}} wróci do wartości domyślnej katalogu. Zmiana działa natychmiast.","validation": {"positive_integer": "Podaj liczbę całkowitą większą od zera lub pozostaw pole puste.",- "currency_taken": "Ta waluta ma już ustawione minimum."+ "currency_taken": "Ta waluta ma już ustawione minimum.",+ "positive_amount": "Podaj kwotę większą od zera."},"messages": {"rule_created": "Dodano regułę produktu",diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.jsonindex 975db5b2db..ebbb0a0b89 100644--- a/packages/dashboard-core/src/locales/zh-CN.json+++ b/packages/dashboard-core/src/locales/zh-CN.json@@ -1567,7 +1567,8 @@"remove_rule_description": "{{name}} 将回退到目录默认值。此更改立即生效。","validation": {"positive_integer": "请输入大于零的整数,或留空。",- "currency_taken": "该币种已设置最低金额。"+ "currency_taken": "该币种已设置最低金额。",+ "positive_amount": "请输入大于零的金额。"},"messages": {"rule_created": "已添加商品规则",diff --git a/packages/dashboard/src/components/spree/catalog-terms-card.tsx b/packages/dashboard/src/components/spree/catalog-terms-card.tsxindex 96f5152ad7..8342d878c4 100644--- a/packages/dashboard/src/components/spree/catalog-terms-card.tsx+++ b/packages/dashboard/src/components/spree/catalog-terms-card.tsx@@ -235,9 +235,14 @@ function AddOrderMinimumDialog({const [amount, setAmount] = useState('')const duplicate = usedCurrencies.includes(currency)+ // Never coerced: "12,50" parses as 12 in JavaScript too, and a minimum an+ // order can trivially clear is worse than one the merchant has to retype.+ const parsedAmount = /^\d+(\.\d{1,2})?$/.test(amount.trim()) ? Number(amount.trim()) : null+ const amountValid = parsedAmount !== null && parsedAmount > 0+ const showAmountError = amount.trim() !== '' && !amountValidasync function handleSubmit() {- if (!amount.trim() || duplicate) return+ if (!amountValid || duplicate) returnawait createMutation.mutateAsync({ currency, amount })@@ -270,9 +275,13 @@ function AddOrderMinimumDialog({<Inputid="minimum-amount"inputMode="decimal"+ aria-invalid={showAmountError}value={amount}onChange={(event) => setAmount(event.target.value)}/>+ {showAmountError && (+ <FieldError>{t('admin.catalogs.terms.validation.positive_amount')}</FieldError>+ )}</Field></FieldGroup></DialogBody>@@ -282,7 +291,7 @@ function AddOrderMinimumDialog({</Button><Buttontype="button"- disabled={createMutation.isPending || !amount.trim() || duplicate}+ disabled={createMutation.isPending || !amountValid || duplicate}onClick={handleSubmit}>{t('admin.actions.add')}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 85f69e38cf..f1ac961f2a 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -180,7 +180,8 @@"remove_rule_description": "سيعود {{name}} إلى الإعداد الافتراضي للكتالوج. يسري هذا فورًا.","validation": {"positive_integer": "أدخل عددًا صحيحًا أكبر من صفر، أو اترك الحقل فارغًا.",- "currency_taken": "هذه العملة لديها حد أدنى بالفعل."+ "currency_taken": "هذه العملة لديها حد أدنى بالفعل.",+ "positive_amount": "أدخل مبلغًا أكبر من صفر."},"messages": {"rule_created": "تمت إضافة قاعدة المنتج",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex f9874d98d9..110c83663d 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -180,7 +180,8 @@"remove_rule_description": "{{name}} nutzt wieder den Katalogstandard. Dies wirkt sofort.","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."+ "currency_taken": "Für diese Währung gibt es bereits einen Mindestwert.",+ "positive_amount": "Geben Sie einen Betrag größer als null ein."},"messages": {"rule_created": "Produktregel hinzugefügt",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 6d933ccb18..a64bf84cf9 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -180,7 +180,8 @@"remove_rule_description": "{{name}} will fall back to the catalog default. This takes effect immediately.","validation": {"positive_integer": "Enter a whole number greater than zero, or leave blank.",- "currency_taken": "This currency already has a minimum."+ "currency_taken": "This currency already has a minimum.",+ "positive_amount": "Enter an amount greater than zero."},"messages": {"rule_created": "Product rule added",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 37133ebb49..d92c1939b6 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -180,7 +180,8 @@"remove_rule_description": "{{name}} reviendra à la valeur par défaut du catalogue. Effet immédiat.","validation": {"positive_integer": "Saisissez un nombre entier supérieur à zéro, ou laissez vide.",- "currency_taken": "Cette devise a déjà un minimum."+ "currency_taken": "Cette devise a déjà un minimum.",+ "positive_amount": "Saisissez un montant supérieur à zéro."},"messages": {"rule_created": "Règle produit ajoutée",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex c03ae018ea..9875c8fc14 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -182,7 +182,8 @@"remove_rule_description": "{{name}} wróci do wartości domyślnej katalogu. Zmiana działa natychmiast.","validation": {"positive_integer": "Podaj liczbę całkowitą większą od zera lub pozostaw pole puste.",- "currency_taken": "Ta waluta ma już ustawione minimum."+ "currency_taken": "Ta waluta ma już ustawione minimum.",+ "positive_amount": "Podaj kwotę większą od zera."},"messages": {"rule_created": "Dodano regułę produktu",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 79737d2e6b..70b8d82d13 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -180,7 +180,8 @@"remove_rule_description": "{{name}} 将回退到目录默认值。此更改立即生效。","validation": {"positive_integer": "请输入大于零的整数,或留空。",- "currency_taken": "该币种已设置最低金额。"+ "currency_taken": "该币种已设置最低金额。",+ "positive_amount": "请输入大于零的金额。"},"messages": {"rule_created": "已添加商品规则",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.rbindex 639f5b013a..b58eb8f1dd 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@@ -58,7 +58,7 @@ module Spreeenddef collection_includes- [:catalog_products, :price_list, :order_minimums]+ [:catalog_products, :price_list, :order_minimums, :quantity_rules]enddef create_workflowdiff --git a/spree/api/app/serializers/spree/api/v3/base_serializer.rb b/spree/api/app/serializers/spree/api/v3/base_serializer.rbindex f02206699d..d7e8f03484 100644--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb@@ -121,9 +121,13 @@ module Spree@quantity_rule_cache[variant.id] ||= quantity_rules_resolver.call(variant)end+ # Through the same entry point visibility and pricing use, so the+ # stepper a storefront draws matches the price beside it and the+ # quantity the cart will actually accept. Resolving without the+ # buyer's company would answer from a different agreement.def quantity_rules_resolver@quantity_rules_resolver ||= Spree::Catalogs::ResolveQuantityRules.new(- Spree::Current.catalogs_for(user: current_user)+ Spree::Catalog.for_buyer(store: current_store, customer: current_user))enddiff --git a/spree/api/spec/serializers/spree/api/v3/variant_quantity_rules_spec.rb b/spree/api/spec/serializers/spree/api/v3/variant_quantity_rules_spec.rbnew file mode 100644index 0000000000..4923e73431--- /dev/null+++ b/spree/api/spec/serializers/spree/api/v3/variant_quantity_rules_spec.rb@@ -0,0 +1,61 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::VariantSerializer, 'quantity rules' do+ let(:store) { @default_store }+ let(:product) { create(:product, store: store) }+ let(:variant) { product.default_variant }++ def render(user: nil)+ described_class.new(+ variant, params: { store: store, currency: store.default_currency, user: user }+ ).to_h+ end++ before do+ Spree::Current.store = store+ Spree::Current.applicable_catalogs = nil+ end++ it 'reads 1 and 1 when nothing declares a rule' do+ json = render++ expect(json['minimum_order_quantity']).to eq(1)+ expect(json['order_multiple']).to eq(1)+ expect(json['purchase_unit']).to eq('unit')+ end++ it "falls back to the variant's own rules for a buyer with no agreement" do+ variant.update!(minimum_order_quantity: 6, order_multiple: 3)++ json = render(user: create(:user))++ expect(json['minimum_order_quantity']).to eq(6)+ expect(json['order_multiple']).to eq(3)+ end++ # The stepper a storefront draws has to match the quantity the cart will+ # accept. Resolving without the buyer's company would answer from a+ # different agreement than the one pricing the same page.+ it "renders the terms of the buyer's company agreement" do+ customer = create(:user)+ company = create(:company, store: store)+ catalog = create(:catalog, store: store, minimum_order_quantity: 48, order_multiple: 24)+ create(:company_membership, company: company, customer: customer)+ create(:catalog_assignment, catalog: catalog, assignable: company)+ Spree::Current.applicable_catalogs = nil++ json = render(user: customer)++ expect(json['minimum_order_quantity']).to eq(48)+ expect(json['order_multiple']).to eq(24)+ end++ it 'exposes the carton vocabulary when the variant is quoted in cartons' do+ variant.update!(purchase_unit: 'carton', units_per_carton: 24)++ json = render++ expect(json['purchase_unit']).to eq('carton')+ expect(json['units_per_carton']).to eq(24)+ end+enddiff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rbindex 13b74b8aa2..417303b60b 100644--- a/spree/core/app/models/spree/catalog.rb+++ b/spree/core/app/models/spree/catalog.rb@@ -156,6 +156,52 @@ module Spreecatalogsend+ # The catalogs applying to a buyer, resolving the company for them when+ # the caller does not already know it, and reusing the request's memoized+ # set where the store being asked about is the one being served.+ #+ # The single entry point for "what are this buyer's catalogs": visibility,+ # pricing and quantity terms must answer from the same set, and a caller+ # that resolved the company differently — or not at all — would show a+ # storefront one agreement's prices under another's rules.+ #+ # @param store [Spree::Store, nil]+ # @param customer [Object, nil]+ # @param company [Spree::Company, nil] the purchase node; defaults to the+ # customer's sole standing within the store+ # @param channel [Spree::Channel, nil]+ # @return [Array<Spree::Catalog>]+ def self.for_buyer(store:, customer: nil, company: nil, channel: nil)+ return [] if store.nil?++ company ||= sole_standing_company(store, customer)+ channel ||= Spree::Current.channel if store == Spree::Current.store++ if store == Spree::Current.store+ Spree::Current.catalogs_for(company: company, user: customer, channel: channel)+ else+ for_context(store: store, company: company, user: customer, channel: channel)+ end+ end++ # The one company a customer unambiguously buys for in this store, or nil+ # when they belong to none or to several — guessing would put one+ # business's agreement on another's purchase.+ #+ # @param store [Spree::Store]+ # @param customer [Object, nil]+ # @return [Spree::Company, nil]+ def self.sole_standing_company(store, customer)+ return nil if customer.nil?++ companies = customer.company_memberships.+ joins(:company).+ merge(Spree::Company.where(store_id: store.id)).+ map(&:company).uniq++ companies.one? ? companies.first : nil+ end+# The owned list's id. Reads like the column the binding replaced, so# serializers and write payloads keep their shape while the FK lives on# the list side. An assigned-but-unsaved binding reads back as itself, so@@ -308,17 +354,6 @@ module Spree)end- # True when this catalog states any commercial term at all. A catalog can- # legitimately carry terms and nothing else — that is how a channel's- # default catalog sets a store-wide minimum without narrowing what anyone- # sees or pays.- #- # @return [Boolean]- def commercial_terms?- minimum_order_quantity.present? || order_multiple.present? ||- quantity_rules.any? || order_minimums.any?- end-private# Runs before anything is written, so a foreign-store list is a validationdiff --git a/spree/core/app/models/spree/checkout/default_requirements.rb b/spree/core/app/models/spree/checkout/default_requirements.rbindex 107c1d4ba0..7a754f7498 100644--- a/spree/core/app/models/spree/checkout/default_requirements.rb+++ b/spree/core/app/models/spree/checkout/default_requirements.rb@@ -120,8 +120,15 @@ module Spree@cart.po_number.blank? && @cart.po_number_required? && !staff_initiated?end+ # Two signals, because either alone leaves a gap: a draft order is the+ # admin surface whether or not a creator was recorded (the draft+ # workflows take `created_by` optionally), and a cart cannot carry one+ # at all. The item workflows exempt staff on the same terms, so an+ # order that passed the add is never refused at completion for the+ # quantities staff deliberately keyed in.def staff_initiated?- @cart.respond_to?(:created_by_id) && @cart.created_by_id.present?+ @cart.is_a?(Spree::Order) ||+ (@cart.respond_to?(:created_by_id) && @cart.created_by_id.present?)enddef req(step, field, message, code: nil)diff --git a/spree/core/app/models/spree/quantity_rule.rb b/spree/core/app/models/spree/quantity_rule.rbindex 795548ca99..a0f56f4b6b 100644--- a/spree/core/app/models/spree/quantity_rule.rb+++ b/spree/core/app/models/spree/quantity_rule.rb@@ -76,11 +76,18 @@ module Spree[previous_valid(quantity), next_valid(quantity)].compact.uniqend- # Steps are counted from the minimum rather than from zero, so a rule of- # "at least 50, in 24s" offers 50 / 74 / 98 instead of refusing its own- # minimum. A minimum that already sits on the multiple leaves this at 0- # and the arithmetic is the plain modulo it looks like.+ # Steps are counted from a DECLARED minimum rather than from zero, so a+ # rule of "at least 50, in 24s" offers 50 / 74 / 98 instead of refusing+ # its own minimum.+ #+ # Only a declared one: the implicit minimum of 1 is the absence of a rule,+ # and letting it set the offset would turn "sold in packs of 5" into+ # 1 / 6 / 11, refusing a buyer who orders exactly one pack. A minimum that+ # already sits on the multiple leaves this at 0 either way, and the+ # arithmetic is the plain modulo it looks like.def offset+ return 0 unless minimum_order_quantity.to_i.positive?+minimum % multipleenddiff --git a/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb b/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rbindex a198f1924b..7464f1941c 100644--- a/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb+++ b/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb@@ -6,11 +6,19 @@ module Spree# Resolution is **per field**, not all-or-nothing: the first catalog that# states a minimum wins the minimum, the first that states a multiple wins# the multiple, and an agreement silent on a field passes it through to- # the next one rather than waiving it — a distributor catalog with no- # stated minimum must not silently drop the channel default's. Within one- # catalog the variant override row beats the catalog's own default+ # the next rather than waiving it — a nearer catalog with no stated+ # minimum must not silently drop the one behind it. Within a single+ # catalog the variant override row beats that catalog's own default# columns. Nothing anywhere leaves the variant's own base rules.#+ # The catalogs walked are whatever {Spree::Catalog.for_buyer} resolved,+ # and that chain is exclusive by tier: a buyer with company catalogs never+ # also carries their customer group's or the channel's default. So a+ # channel-wide term is the floor for buyers who resolve NO company or+ # group catalog, not a fallback beneath one — a company agreement that+ # states nothing about a field lands on the variant's base rule, not on+ # the channel default.+ ## Built once per cart or request and reused: resolving a fifty-line cart# must not be fifty passes over the same catalogs.class ResolveQuantityRules@@ -55,8 +63,8 @@ module Spree# The order minimum in effect for a currency: the first catalog with a# row for it. Catalogs saying nothing about this currency pass through,- # so a distributor agreement priced only in EUR does not waive the- # channel default's USD threshold.+ # so an agreement priced only in EUR does not waive a USD threshold set+ # by another catalog in the same tier.## @param currency [String]# @return [Spree::CatalogOrderMinimum, nil]@@ -71,26 +79,15 @@ module Spreenilend- # True when no catalog states any quantity term, so every variant- # resolves to its own base rules. Lets callers skip the walk entirely.- # @return [Boolean]- def blank?- catalogs.none? { |catalog| catalog.commercial_terms? }- end-+ # Through the one entry point every catalog-reading surface uses, so a+ # cart's terms come from the same agreement its prices did.def self.catalogs_for(purchase)- store = purchase.store- return [] if store.nil?-- company = purchase.try(:resolved_company)- user = purchase.try(:user)- channel = purchase.try(:channel)-- if store == Spree::Current.store- Spree::Current.catalogs_for(company: company, user: user, channel: channel)- else- Spree::Catalog.for_context(store: store, company: company, user: user, channel: channel)- end+ Spree::Catalog.for_buyer(+ store: purchase.store,+ customer: purchase.try(:user),+ company: purchase.try(:resolved_company),+ channel: purchase.try(:channel)+ )endprivate_class_method :catalogs_fordiff --git a/spree/core/app/services/spree/products/for_context.rb b/spree/core/app/services/spree/products/for_context.rbindex a95f66a6b6..7fcc2ab138 100644--- a/spree/core/app/services/spree/products/for_context.rb+++ b/spree/core/app/services/spree/products/for_context.rb@@ -25,17 +25,14 @@ module Spree# @return [Spree::ServiceModule::Result] value is a Product relationdef call(store:, channel:, customer: nil, company: nil, base: nil)base ||= store.products.for_channel(channel)- company ||= sole_standing_company(store, customer)- # Reuses the request-scoped set when resolving for the current store,- # so a listing that prices its variants right after does not resolve- # the same buyer's catalogs twice in one request.- catalogs =- if store == Spree::Current.store- Spree::Current.catalogs_for(company: company, user: customer, channel: channel)- else- Spree::Catalog.for_context(store: store, company: company, user: customer, channel: channel)- end+ # One resolution for every surface: visibility, pricing and quantity+ # terms have to answer from the same catalogs, and it reuses the+ # request-scoped set so a listing that prices its variants right after+ # does not resolve the same buyer twice.+ catalogs = Spree::Catalog.for_buyer(+ store: store, customer: customer, company: company, channel: channel+ )return success(base) if catalogs.empty?@@ -65,16 +62,6 @@ module Spree# nodes the buyer picks one on the cart, and catalogs follow that# choice; matches +Purchase::Company#resolved_company+ exactly, so# what they browse and what they are charged agree.- def sole_standing_company(store, customer)- return nil if customer.nil?-- companies = customer.company_memberships.- joins(:company).- merge(Spree::Company.where(store_id: store.id)).- map(&:company).uniq-- companies.one? ? companies.first : nil- endendendenddiff --git a/spree/core/spec/models/spree/catalog_for_buyer_spec.rb b/spree/core/spec/models/spree/catalog_for_buyer_spec.rbnew file mode 100644index 0000000000..319f43bd45--- /dev/null+++ b/spree/core/spec/models/spree/catalog_for_buyer_spec.rb@@ -0,0 +1,49 @@+require 'spec_helper'++RSpec.describe Spree::Catalog, '.for_buyer' do+ let(:store) { @default_store }+ let(:customer) { create(:user) }+ let(:company) { create(:company, store: store) }+ let!(:catalog) { create(:catalog, store: store, minimum_order_quantity: 48) }++ before do+ create(:company_membership, company: company, customer: customer)+ create(:catalog_assignment, catalog: catalog, assignable: company)+ Spree::Current.applicable_catalogs = nil+ end++ # Every catalog-reading surface has to answer from the same set. A caller+ # that knows only the customer must still reach their company's agreement,+ # or a storefront shows one agreement's prices under another's rules.+ it "resolves a customer's sole company without being told it" do+ expect(described_class.for_buyer(store: store, customer: customer)).to eq([catalog])+ end++ it 'honours an explicitly named company' do+ expect(described_class.for_buyer(store: store, customer: customer, company: company)).to eq([catalog])+ end++ it 'resolves nothing for a customer with no standing' do+ expect(described_class.for_buyer(store: store, customer: create(:user))).to be_empty+ end++ # Guessing would put one business's agreement on another's purchase.+ it 'refuses to guess between two memberships' do+ create(:company_membership, company: create(:company, store: store), customer: customer)++ expect(described_class.for_buyer(store: store, customer: customer)).to be_empty+ end++ # Customers are global; a membership in another store must not reach here.+ it 'ignores a membership at a company in another store' do+ other_customer = create(:user)+ other_company = create(:company, store: create(:store))+ create(:company_membership, company: other_company, customer: other_customer)++ expect(described_class.for_buyer(store: store, customer: other_customer)).to be_empty+ end++ it 'is empty without a store' do+ expect(described_class.for_buyer(store: nil, customer: customer)).to eq([])+ end+enddiff --git a/spree/core/spec/models/spree/quantity_rule_spec.rb b/spree/core/spec/models/spree/quantity_rule_spec.rbindex 884508bfae..7f594fc685 100644--- a/spree/core/spec/models/spree/quantity_rule_spec.rb+++ b/spree/core/spec/models/spree/quantity_rule_spec.rb@@ -34,6 +34,23 @@ RSpec.describe Spree::QuantityRule doexpect(rule).not_to be_satisfied_by(100)end+ # "Sold in packs of 5, no minimum" must accept one pack. Steps count from+ # a DECLARED minimum only — the implicit 1 is the absence of a rule, and+ # letting it set the offset would offer 1 / 6 / 11 and refuse 5.+ context 'when only a multiple is declared' do+ subject(:rule) { described_class.new(order_multiple: 5) }++ it 'accepts whole packs from the first one' do+ expect(rule).to be_satisfied_by(5)+ expect(rule).to be_satisfied_by(10)+ expect(rule).not_to be_satisfied_by(7)+ end++ it 'offers whole packs as the neighbours' do+ expect(rule.nearest_valid(7)).to eq([5, 10])+ end+ end+# A minimum that does not sit on the multiple still has to be orderable,# so steps are counted from the minimum rather than from zero.context 'when the minimum is not itself a multiple' dodiff --git a/spree/core/spec/services/spree/catalogs/resolve_quantity_rules_spec.rb b/spree/core/spec/services/spree/catalogs/resolve_quantity_rules_spec.rbindex bb8487b3e6..24b3efb62f 100644--- a/spree/core/spec/services/spree/catalogs/resolve_quantity_rules_spec.rb+++ b/spree/core/spec/services/spree/catalogs/resolve_quantity_rules_spec.rb@@ -141,16 +141,4 @@ RSpec.describe Spree::Catalogs::ResolveQuantityRules doexpect(described_class.new([nearest, fallback]).order_minimum('USD').amount).to eq(250)endend-- describe '#blank?' do- it 'is true when no catalog states any term' do- expect(described_class.new([create(:catalog, store: store)])).to be_blank- end-- it 'is false once a catalog carries terms' do- catalog = create(:catalog, store: store, minimum_order_quantity: 48)-- expect(described_class.new([catalog])).not_to be_blank- end- endend