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
Add B2B quantity rules to the purchasing layer
Damian Legawiec8682e47aeba2
diff --git a/spree/core/app/models/concerns/spree/purchase/quantity_rules.rb b/spree/core/app/models/concerns/spree/purchase/quantity_rules.rbnew file mode 100644index 0000000000..bb88ceaef2--- /dev/null+++ b/spree/core/app/models/concerns/spree/purchase/quantity_rules.rb@@ -0,0 +1,97 @@+module Spree+ module Purchase+ # How much of a thing this buyer may order, and how much the order as a+ # whole must come to — shared by Spree::Cart and Spree::Order.+ #+ # Everything here is computed from the buyer's catalogs and never stored:+ # an agreement is a live fact about the relationship, so a cart reads+ # today's terms rather than the ones it was built under. A placed order+ # resolves the same way for display, but nothing re-validates it — the+ # sale already happened (docs/plans/6.0-b2b-quantity-rules.md).+ module QuantityRules+ extend ActiveSupport::Concern++ # The buyer's effective rules for one variant: their catalogs' terms+ # resolved per field over the variant's own base rules.+ #+ # @param variant [Spree::Variant]+ # @return [Spree::QuantityRule]+ def quantity_rules_for(variant)+ quantity_rules_resolver.call(variant)+ end++ # The order minimum in force for this purchase's currency, or nil when+ # the buyer's agreements state none.+ #+ # @return [Spree::CatalogOrderMinimum, nil]+ def order_minimum+ return @order_minimum if defined?(@order_minimum)++ @order_minimum = quantity_rules_resolver.order_minimum(currency)+ end++ # @return [BigDecimal, nil] the amount that must be reached, or nil+ def order_minimum_amount+ order_minimum&.amount+ end++ # What still has to be added to reach the minimum, or nil when there is+ # no minimum. Zero once it is met, so callers can render "$180 to go"+ # from one number.+ #+ # Measured against the item total rather than the order total: delivery+ # and tax are not what the buyer bought, and a threshold met by adding+ # a faster shipping option is not a minimum order.+ #+ # @return [BigDecimal, nil]+ def order_minimum_shortfall+ amount = order_minimum_amount+ return nil if amount.nil?++ [amount - item_total, 0].max+ end++ # @return [Boolean] true only when a minimum applies and is not met+ def below_order_minimum?+ shortfall = order_minimum_shortfall+ shortfall.present? && shortfall.positive?+ end++ # Every line whose quantity no longer satisfies the buyer's rules,+ # paired with the rule it breaks. Empty for a retail buyer, and empty+ # for anyone who has not had their terms changed under them.+ #+ # @return [Array<Array(Spree::LineItem, Spree::QuantityRule)>]+ def line_items_violating_quantity_rules+ resolver = quantity_rules_resolver++ line_items.filter_map do |line_item|+ variant = line_item.variant+ next if variant.nil?++ rule = resolver.call(variant)+ next if rule.satisfied_by?(line_item.quantity)++ [line_item, rule]+ end+ end++ # Resolved once per instance: a cart asks about every line, and the+ # catalog walk is the same walk each time.+ #+ # @return [Spree::Catalogs::ResolveQuantityRules]+ def quantity_rules_resolver+ @quantity_rules_resolver ||= Spree::Catalogs::ResolveQuantityRules.for_purchase(self)+ end++ # Dropped on reload, so a cart whose company or catalog terms changed in+ # the same request resolves again rather than answering from a set that+ # no longer applies.+ def reload(*)+ @quantity_rules_resolver = nil+ remove_instance_variable(:@order_minimum) if defined?(@order_minimum)+ super+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rbindex 6c633b8017..0b7d013316 100644--- a/spree/core/app/models/spree/cart.rb+++ b/spree/core/app/models/spree/cart.rb@@ -18,6 +18,7 @@ module Spreeinclude Spree::SingleStoreResourceinclude Spree::Purchase::Channelinclude Spree::Purchase::Company+ include Spree::Purchase::QuantityRulesinclude Spree::Purchase::PurchaseOrderinclude Spree::Purchase::Marketinclude Spree::Purchase::Currencydiff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rbindex 05a0c4bab3..13b74b8aa2 100644--- a/spree/core/app/models/spree/catalog.rb+++ b/spree/core/app/models/spree/catalog.rb@@ -36,7 +36,17 @@ module Spreehas_many :catalog_assignments, class_name: 'Spree::CatalogAssignment', dependent: :destroy,inverse_of: :catalog+ # Commercial terms — typed per grain rather than one rules table, because+ # quantity rules are read on the add-to-cart path and want an indexed+ # lookup, while minimums want DB-enforced per-currency uniqueness.+ has_many :quantity_rules, class_name: 'Spree::CatalogQuantityRule', dependent: :destroy,+ inverse_of: :catalog+ has_many :order_minimums, class_name: 'Spree::CatalogOrderMinimum', dependent: :destroy,+ inverse_of: :catalog+validates :name, presence: true+ validates :minimum_order_quantity, numericality: { only_integer: true, greater_than: 0, allow_nil: true }+ validates :order_multiple, numericality: { only_integer: true, greater_than: 0, allow_nil: true }validate :price_list_in_same_storevalidate :price_list_must_be_resolvablevalidate :price_list_not_owned_elsewhere@@ -286,6 +296,29 @@ module Spreeadd_products(price_list.product_ids)end+ # This catalog's own quantity terms, before any per-variant override —+ # the middle of the three resolution levels. Fields this catalog is+ # silent on stay nil so the level below still answers them.+ #+ # @return [Spree::QuantityRule]+ def default_quantity_rule+ Spree::QuantityRule.new(+ minimum_order_quantity: minimum_order_quantity,+ order_multiple: order_multiple+ )+ 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/catalog_order_minimum.rb b/spree/core/app/models/spree/catalog_order_minimum.rbnew file mode 100644index 0000000000..40ea67f01f--- /dev/null+++ b/spree/core/app/models/spree/catalog_order_minimum.rb@@ -0,0 +1,26 @@+module Spree+ # The least a whole order must come to under a catalog's agreement, in one+ # currency. Born per currency — one row each — because Spree holds no+ # exchange rates and a threshold converted at read time is a different+ # promise every day.+ class CatalogOrderMinimum < Spree.base_class+ has_prefix_id :com++ belongs_to :catalog, class_name: 'Spree::Catalog', touch: true, inverse_of: :order_minimums++ validates :currency, presence: true,+ uniqueness: { scope: [:catalog_id, *spree_base_uniqueness_scope] }+ validates :amount, numericality: { greater_than: 0 }++ normalizes :currency, with: ->(value) { value&.to_s&.strip&.upcase }++ delegate :store, :store_id, to: :catalog++ after_commit -> { Spree::Current.applicable_catalogs = nil }++ # @return [Spree::Money]+ def display_amount+ Spree::Money.new(amount, currency: currency)+ end+ end+enddiff --git a/spree/core/app/models/spree/catalog_quantity_rule.rb b/spree/core/app/models/spree/catalog_quantity_rule.rbnew file mode 100644index 0000000000..26dfb294a8--- /dev/null+++ b/spree/core/app/models/spree/catalog_quantity_rule.rb@@ -0,0 +1,54 @@+module Spree+ # A catalog's purchasing rules for one variant — the narrowest of the three+ # levels a buyer's rules resolve through (variant base -> the catalog's own+ # default columns -> this row).+ #+ # Both fields are independently optional: a row stating only a minimum+ # leaves the multiple to the level below, because agreements are read+ # per-field and one that is silent on a field passes it through rather than+ # waiving it.+ class CatalogQuantityRule < Spree.base_class+ has_prefix_id :cqr++ belongs_to :catalog, class_name: 'Spree::Catalog', touch: true, inverse_of: :quantity_rules+ belongs_to :variant, class_name: 'Spree::Variant'++ validates :variant_id, uniqueness: { scope: [:catalog_id, *spree_base_uniqueness_scope] }+ validates :minimum_order_quantity, numericality: { only_integer: true, greater_than: 0, allow_nil: true }+ validates :order_multiple, numericality: { only_integer: true, greater_than: 0, allow_nil: true }+ validate :states_something+ validate :variant_in_same_store++ delegate :store, :store_id, to: :catalog++ # A catalog's terms are invalidated the moment they change: the resolved+ # set is memoized per request, and a rule edited in the same request must+ # not be read back stale.+ after_commit -> { Spree::Current.applicable_catalogs = nil }++ # @return [Spree::QuantityRule] this row's contribution, unresolved+ def to_quantity_rule+ Spree::QuantityRule.new(+ minimum_order_quantity: minimum_order_quantity,+ order_multiple: order_multiple+ )+ end++ private++ # A row stating neither field says nothing at all, which reads as an+ # override that overrides nothing — almost certainly a half-filled form.+ def states_something+ return if minimum_order_quantity.present? || order_multiple.present?++ errors.add(:base, :quantity_rule_states_nothing)+ end++ def variant_in_same_store+ return if variant.nil? || catalog.nil?+ return if variant.product&.store_id == catalog.store_id++ errors.add(:variant, :invalid)+ end+ end+enddiff --git a/spree/core/app/models/spree/checkout/default_requirements.rb b/spree/core/app/models/spree/checkout/default_requirements.rbindex ae3c74de3e..107c1d4ba0 100644--- a/spree/core/app/models/spree/checkout/default_requirements.rb+++ b/spree/core/app/models/spree/checkout/default_requirements.rb@@ -35,15 +35,50 @@ module Spreer << req('delivery', 'delivery_method', Spree.t('checkout_requirements.delivery_method_required')) if delivery_step_required? && !delivery_method_selected?r << req('payment', 'payment', Spree.t('checkout_requirements.payment_required')) if payment_required? && !payment_satisfied?r << req('address', 'po_number', Spree.t('checkout_requirements.po_number_required')) if po_number_missing?+ r << order_minimum_requirement if below_order_minimum?endenddef completion_requirements- errors = stock_errors+ errors = stock_errors + quantity_rule_errorserrors << req('address', 'email', Spree.t(:guest_checkout_not_allowed), code: 'guest_checkout_not_allowed') if @cart.guest_checkout_disallowed?errorsend+ # Re-checked at completion because an agreement can change between the+ # add and the checkout — a company moved to a different tier, a term+ # edited. Naming the nearest valid quantities rather than rounding: a+ # silent adjustment on a wholesale order is a five-figure surprise.+ def quantity_rule_errors+ return [] if staff_initiated?++ @cart.line_items_violating_quantity_rules.map do |line_item, rule|+ req('cart', 'line_items',+ Spree.t('cart_line_item.quantity_rule_violated',+ li_name: line_item.name,+ quantities: rule.nearest_valid(line_item.quantity).to_sentence),+ code: 'quantity_rule_violated')+ end+ end++ # Advisory rather than completion-only: a buyer has to be able to build+ # the order below the threshold and read how far off they are while+ # they can still add to it. Completion refuses it because the advisory+ # feed is included there too.+ def below_order_minimum?+ !staff_initiated? && @cart.below_order_minimum?+ end++ def order_minimum_requirement+ minimum = @cart.order_minimum+ shortfall = Spree::Money.new(@cart.order_minimum_shortfall, currency: minimum.currency)++ req('cart', 'order_minimum',+ Spree.t('checkout_requirements.order_minimum_not_met',+ minimum: minimum.display_amount.to_s, shortfall: shortfall.to_s),+ code: 'order_minimum_not_met')+ end+# Discontinuation is checked at both levels: a product can stay active# while an individual variant hit its discontinue_on date after it# entered the cart.diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex b09e2289d4..eec3936c38 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -26,6 +26,7 @@ module Spreeinclude Spree::SanitizableRichTextinclude Spree::Purchase::Channelinclude Spree::Purchase::Company+ include Spree::Purchase::QuantityRulesinclude Spree::Purchase::PurchaseOrderinclude Spree::Purchase::Marketinclude Spree::Purchase::Currencydiff --git a/spree/core/app/models/spree/quantity_rule.rb b/spree/core/app/models/spree/quantity_rule.rbnew file mode 100644index 0000000000..795548ca99--- /dev/null+++ b/spree/core/app/models/spree/quantity_rule.rb@@ -0,0 +1,96 @@+module Spree+ # A resolved pair of purchasing rules for one variant and one buyer: the+ # least they may order and the increment they must land on. MOQ 48 with+ # multiple 24 admits 48, 72, 96 and refuses 50.+ #+ # Resolution (variant base -> catalog default -> catalog x variant+ # override) happens in {Spree::Catalogs::ResolveQuantityRules}; this object+ # is only the answer and the arithmetic over it, so the same rules apply+ # identically wherever a quantity is checked or a stepper is drawn.+ class QuantityRule+ include ActiveModel::Model+ include ActiveModel::Attributes++ attribute :minimum_order_quantity, :integer+ attribute :order_multiple, :integer++ # The rule every buyer gets when nothing declares one: buy one at a time.+ def self.default+ new+ end++ # @return [Integer] the least quantity that may be ordered+ def minimum+ value = minimum_order_quantity.to_i+ value.positive? ? value : 1+ end++ # @return [Integer] the increment quantities must land on+ def multiple+ value = order_multiple.to_i+ value.positive? ? value : 1+ end++ # True when neither rule narrows anything — the shape a retail buyer sees.+ # @return [Boolean]+ def unrestricted?+ minimum == 1 && multiple == 1+ end++ # @param quantity [Integer]+ # @return [Boolean]+ def satisfied_by?(quantity)+ quantity = quantity.to_i+ quantity >= minimum && ((quantity - offset) % multiple).zero?+ end++ # The largest valid quantity at or below the given one, or nil when the+ # minimum is already above it.+ # @param quantity [Integer]+ # @return [Integer, nil]+ def previous_valid(quantity)+ quantity = quantity.to_i+ return nil if quantity < minimum++ quantity - ((quantity - offset) % multiple)+ end++ # The smallest valid quantity at or above the given one.+ # @param quantity [Integer]+ # @return [Integer]+ def next_valid(quantity)+ quantity = quantity.to_i+ return minimum if quantity <= minimum++ remainder = (quantity - offset) % multiple+ remainder.zero? ? quantity : quantity + (multiple - remainder)+ end++ # The valid quantities either side of an invalid one, used to tell a buyer+ # what they may order instead. Both are present unless the quantity is+ # below the minimum, where there is nothing lower to offer.+ #+ # @param quantity [Integer]+ # @return [Array<Integer>] one or two ascending quantities+ def nearest_valid(quantity)+ [previous_valid(quantity), next_valid(quantity)].compact.uniq+ end++ # 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.+ def offset+ minimum % multiple+ end++ def ==(other)+ other.is_a?(self.class) && minimum == other.minimum && multiple == other.multiple+ end+ alias eql? ==++ def hash+ [minimum, multiple].hash+ end+ end+enddiff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex 541551d9ed..ae8e93e2ac 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -19,6 +19,10 @@ module SpreeDIMENSION_UNITS = %w[mm cm in ft]WEIGHT_UNITS = %w[g kg lb oz]+ # What a buyer is quoted in. Stored quantities are units at every level;+ # this only changes the vocabulary a storefront presents.+ PURCHASE_UNITS = %w[unit carton]+belongs_to :product, -> { with_deleted }, touch: true, class_name: 'Spree::Product', inverse_of: :variantsbelongs_to :tax_category, class_name: 'Spree::TaxCategory', optional: true# Which seller sells this variant. Nil is the operator's own listing, and@@ -113,6 +117,21 @@ module Spreevalidates :backorder_limit, numericality: { only_integer: true, greater_than_or_equal_to: 0, allow_nil: true }+ # Base purchasing rules. Blank means unrestricted, so the columns start+ # empty and every existing variant keeps buying one at a time.+ validates :minimum_order_quantity, numericality: { only_integer: true, greater_than: 0, allow_nil: true }+ validates :order_multiple, numericality: { only_integer: true, greater_than: 0, allow_nil: true }+ validates :units_per_carton, numericality: { only_integer: true, greater_than: 0, allow_nil: true }+ validates :purchase_unit, inclusion: { in: PURCHASE_UNITS }, allow_blank: true++ # Both are data errors the merchant should hear about while editing, not+ # discover through a customer complaint: an order multiple that straddles+ # carton boundaries can never be shipped whole, and quoting cartons+ # without saying how many units one holds leaves the storefront no way to+ # render the offer.+ validate :order_multiple_fits_cartons+ validate :carton_purchase_unit_has_divisor+# Customs classification. Optional everywhere — only an international# shipment or a duties provider needs it, and each raises its own error# when it does. Carriers reject an HS code outside 6..13 digits, so the@@ -244,7 +263,8 @@ module Spree# applies it, not an allowlist entry that quietly answers a different# question.self.whitelisted_ransackable_attributes = %w[weight depth width height sku discontinue_on cost_price cost_currency track_inventory- deleted_at product_id hs_code country_of_origin]+ deleted_at product_id hs_code country_of_origin+ minimum_order_quantity order_multiple purchase_unit units_per_carton]self.whitelisted_ransackable_scopes = %i(product_name_or_sku_cont search_by_product_name_or_sku search)def self.product_name_or_sku_cont(query)@@ -920,8 +940,54 @@ module Spreedigital_assets.any?end+ # The variant's own purchasing rules — the base every cart obeys, and the+ # floor a buyer falls back to when their catalogs state nothing. A buyer's+ # effective rules resolve through {Spree::Catalogs::ResolveQuantityRules};+ # nothing below the cart layer reads either.+ #+ # @return [Spree::QuantityRule]+ def quantity_rule+ Spree::QuantityRule.new(+ minimum_order_quantity: minimum_order_quantity,+ order_multiple: order_multiple+ )+ end++ # True when this variant is quoted in cartons rather than units. Requires+ # +units_per_carton+, which the validation above guarantees.+ #+ # @return [Boolean]+ def sold_by_carton?+ purchase_unit == 'carton' && units_per_carton.to_i.positive?+ end++ # How many cartons a unit quantity fills, rounded up — a part carton still+ # ships as a carton. Nil when the variant declares no carton size.+ #+ # @param quantity [Integer]+ # @return [Integer, nil]+ def cartons_for(quantity)+ return nil unless units_per_carton.to_i.positive?++ (quantity.to_i / units_per_carton.to_f).ceil+ end+private+ def order_multiple_fits_cartons+ return if order_multiple.to_i.zero? || units_per_carton.to_i.zero?+ return if (order_multiple % units_per_carton).zero? || (units_per_carton % order_multiple).zero?++ errors.add(:order_multiple, :incompatible_with_carton, units_per_carton: units_per_carton)+ end++ def carton_purchase_unit_has_divisor+ return unless purchase_unit == 'carton'+ return if units_per_carton.to_i.positive?++ errors.add(:units_per_carton, :required_for_carton_purchase_unit)+ end+# Resolved through the product's own store, because# +Spree::StockLocation.find_by_param+ is global: an id belonging to another# store would otherwise resolve and put this variant's stock in that store'sdiff --git a/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb b/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rbnew file mode 100644index 0000000000..a198f1924b--- /dev/null+++ b/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb@@ -0,0 +1,116 @@+module Spree+ module Catalogs+ # Answers "how may this buyer order this variant" by walking their+ # catalogs nearest-agreement-first.+ #+ # 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+ # columns. Nothing anywhere leaves the variant's own base rules.+ #+ # Built once per cart or request and reused: resolving a fifty-line cart+ # must not be fifty passes over the same catalogs.+ class ResolveQuantityRules+ # @param catalogs [Array<Spree::Catalog>] nearest agreement first+ def initialize(catalogs)+ @catalogs = Array(catalogs)+ end++ # Builds a resolver for a purchase's buyer, reusing the request's+ # already-resolved catalog set where the purchase belongs to the store+ # being served.+ #+ # @param purchase [Spree::Cart, Spree::Order]+ # @return [Spree::Catalogs::ResolveQuantityRules]+ def self.for_purchase(purchase)+ new(catalogs_for(purchase))+ end++ # @param variant [Spree::Variant]+ # @return [Spree::QuantityRule] the buyer's effective rules+ def call(variant)+ return variant.quantity_rule if catalogs.empty?++ minimum = nil+ multiple = nil++ catalogs.each do |catalog|+ override = override_for(catalog, variant)++ minimum ||= override&.minimum_order_quantity || catalog.minimum_order_quantity+ multiple ||= override&.order_multiple || catalog.order_multiple++ break if minimum && multiple+ end++ Spree::QuantityRule.new(+ minimum_order_quantity: minimum || variant.minimum_order_quantity,+ order_multiple: multiple || variant.order_multiple+ )+ end+ alias for_variant call++ # 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.+ #+ # @param currency [String]+ # @return [Spree::CatalogOrderMinimum, nil]+ def order_minimum(currency)+ return nil if currency.blank?++ code = currency.to_s.upcase+ catalogs.each do |catalog|+ row = minimums_for(catalog)[code]+ return row if row+ end+ nil+ end++ # 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++ 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+ end+ private_class_method :catalogs_for++ private++ attr_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.+ def override_for(catalog, variant)+ @overrides ||= {}+ @overrides[catalog.id] ||= catalog.quantity_rules.index_by(&:variant_id)+ @overrides[catalog.id][variant.id]+ end++ def minimums_for(catalog)+ @minimums ||= {}+ @minimums[catalog.id] ||= catalog.order_minimums.index_by { |row| row.currency.to_s.upcase }+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/carts/add_item.rb b/spree/core/app/workflows/spree/carts/add_item.rbindex c5c9970d76..0eab6509ae 100644--- a/spree/core/app/workflows/spree/carts/add_item.rb+++ b/spree/core/app/workflows/spree/carts/add_item.rb@@ -26,6 +26,12 @@ module Spreestep :parse_manual_price unless price.nil?+ # Core behaviour rather than a hook: an agreement's quantity terms are+ # part of what the merchant sold, not an extension's opinion. Before+ # the hook so a host app's own rules see a quantity that already+ # passed the commercial ones.+ step :validate_quantity_rules+# Veto point — purchase limits, B2B eligibility, per-group rules.# Outside the transaction: nothing has been written yet, so a# rejection costs no rollback.@@ -63,6 +69,38 @@ module Spreereject!(Spree.t('cart_line_item.invalid_price'), cart)end+ # Checked against the quantity the line will END UP at, not the+ # increment: adding 24 to an existing 24 is an order of 48, which a+ # 48/24 rule allows even though neither 24 does on its own.+ #+ # Staff keying an order in are unrestricted — an admin is entering what+ # the buyer actually negotiated, and refusing it would make the+ # exception impossible to record.+ def validate_quantity_rules+ return if staff_initiated?++ rule = cart.quantity_rules_for(variant)+ return if rule.satisfied_by?(resulting_quantity)++ # A symbolic type rather than a bare string, so callers reading+ # `details` get `quantity_rule_violated` rather than the sentence.+ errors.add(+ :base, :quantity_rule_violated,+ message: Spree.t('cart_line_item.quantity_rule_violated',+ li_name: variant.name,+ quantities: rule.nearest_valid(resulting_quantity).to_sentence)+ )+ failure(cart, errors)+ end++ # Draft orders are the admin surface — a cart is always the buyer's own,+ # and only an Order carries a creator. Staff key in what the buyer+ # actually negotiated, so refusing them would make an agreed exception+ # impossible to record.+ def staff_initiated?+ cart.is_a?(Spree::Order)+ end+def add_to_line_itemitem_options = options || {}requested_quantity = quantity || 1diff --git a/spree/core/app/workflows/spree/carts/upsert_items.rb b/spree/core/app/workflows/spree/carts/upsert_items.rbindex 250d2c75bd..1994e5c63f 100644--- a/spree/core/app/workflows/spree/carts/upsert_items.rb+++ b/spree/core/app/workflows/spree/carts/upsert_items.rb@@ -241,6 +241,10 @@ module Spree# deliberate difference between this workflow and every other one.def validated?(item, index)bind_current_item(item)+ # Core behaviour rather than a hook: an agreement's quantity terms are+ # what the merchant sold. Removals are exempt — a buyer must always be+ # able to empty a line, whatever the rules now say about holding it.+ check_quantity_rules(item) unless item.remove?run_hooks :validatetruerescue Spree::Workflow::FailureSignal@@ -259,6 +263,31 @@ module Spreebind_current_item(nil)end+ # This workflow SETS the quantity, so the submitted number is already+ # the resulting one — no increment to add on.+ def check_quantity_rules(item)+ return if staff_initiated?++ rule = cart.quantity_rules_for(item.variant)+ return if rule.satisfied_by?(item.quantity)++ # A symbolic type rather than a bare string, so the warning this+ # becomes carries `quantity_rule_violated` as its code — a client+ # switching on the code must not be handed the sentence.+ errors.add(+ :base, :quantity_rule_violated,+ message: Spree.t('cart_line_item.quantity_rule_violated',+ li_name: item.variant.name,+ quantities: rule.nearest_valid(item.quantity).to_sentence)+ )+ failure(cart, errors)+ end++ # Draft orders are the admin surface — a cart is always the buyer's own.+ def staff_initiated?+ cart.is_a?(Spree::Order)+ end+def bind_current_item(item)@variant = item&.variant@quantity = item&.quantitydiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 5052933bef..a3f7684c31 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -214,13 +214,24 @@ en:email: Emailpassword: Passwordpassword_confirmation: Password Confirmation+ spree/catalog_order_minimum:+ amount: Amount+ currency: Currency+ spree/catalog_quantity_rule:+ minimum_order_quantity: Minimum order quantity+ order_multiple: Order multiple+ variant: Variantspree/variant:cost_currency: Cost Currencycost_price: Cost Pricedepth: Depthheight: Height+ minimum_order_quantity: Minimum order quantity+ order_multiple: Order multipleprice: Price+ purchase_unit: Purchase unitsku: SKU+ units_per_carton: Units per cartonweight: Weightwidth: Widthspree/wished_item:@@ -404,10 +415,18 @@ en:ship_address_id:belongs_to_other_user: belongs to other userdeprecated_in_completed_order: deprecated in completed order+ spree/catalog_quantity_rule:+ attributes:+ base:+ quantity_rule_states_nothing: Set a minimum order quantity, an order multiple, or bothspree/variant:attributes:base:cannot_destroy_if_attached_to_line_items: Cannot delete Variants that are added to placed Orders. In such cases, please discontinue them.+ order_multiple:+ incompatible_with_carton: must divide into or be a multiple of %{units_per_carton} units per carton+ units_per_carton:+ required_for_carton_purchase_unit: is required when the purchase unit is cartonsspree/webhook_endpoint:attributes:url:@@ -720,6 +739,7 @@ en:price_override_not_allowed: Prices cannot be changed on a placed order — use fees or discounts insteadpricing_unavailable: Prices could not be confirmed. Please try again.quantity_must_be_positive: Quantity must be at least 1. Use DELETE to remove the item.+ quantity_rule_violated: "%{li_name} cannot be ordered in that quantity. Try %{quantities}."catalogs:no_price_list_to_import: This catalog has no price list to import products from.categories: Categories@@ -735,6 +755,7 @@ en:email_required: Email address is requiredline_items_required: Add at least one item to your cartpayment_required: Add a payment method+ order_minimum_not_met: "Orders must come to at least %{minimum}. Add %{shortfall} more to check out."po_number_required: A purchase order number is required for this accountship_address_required: Shipping address is requiredchoose_currency: Choose Currencydiff --git a/spree/core/db/migrate/20260831000002_add_quantity_rules_to_spree_variants.rb b/spree/core/db/migrate/20260831000002_add_quantity_rules_to_spree_variants.rbnew file mode 100644index 0000000000..9d7be2b89d--- /dev/null+++ b/spree/core/db/migrate/20260831000002_add_quantity_rules_to_spree_variants.rb@@ -0,0 +1,18 @@+class AddQuantityRulesToSpreeVariants < ActiveRecord::Migration[8.1]+ def change+ # The base purchasing rules every cart obeys. Empty means today's+ # behaviour — buy one at a time, in units.+ add_column :spree_variants, :minimum_order_quantity, :integer+ add_column :spree_variants, :order_multiple, :integer++ # Commercial purchase vocabulary — 'unit' (nil) or 'carton'. Stored+ # quantities stay units at every level; this only changes what a buyer+ # is shown and stepped by.+ add_column :spree_variants, :purchase_unit, :string++ # The carton divisor. The rest of the packing chain+ # (carton_package_type_id, carton_weight, cartons_per_pallet) belongs to+ # docs/plans/6.0-b2b-wholesale-shipping.md and lands with it.+ add_column :spree_variants, :units_per_carton, :integer+ end+enddiff --git a/spree/core/db/migrate/20260831000003_create_spree_catalog_terms.rb b/spree/core/db/migrate/20260831000003_create_spree_catalog_terms.rbnew file mode 100644index 0000000000..7c2e37c226--- /dev/null+++ b/spree/core/db/migrate/20260831000003_create_spree_catalog_terms.rb@@ -0,0 +1,35 @@+class CreateSpreeCatalogTerms < ActiveRecord::Migration[8.1]+ def change+ # The catalog-wide default, the middle of the three levels a buyer's+ # quantity rules resolve through: variant base -> catalog default ->+ # catalog x variant override. Same column pair at each level.+ add_column :spree_catalogs, :minimum_order_quantity, :integer+ add_column :spree_catalogs, :order_multiple, :integer++ # Strictly the per-variant override — the catalog-wide default lives in+ # the columns above, so there is no null-variant row and the index stays+ # a plain unique one.+ create_table :spree_catalog_quantity_rules do |t|+ t.references :catalog, null: false, index: false+ t.references :variant, null: false+ t.integer :minimum_order_quantity+ t.integer :order_multiple+ t.timestamps+ end++ add_index :spree_catalog_quantity_rules, [:catalog_id, :variant_id], unique: true,+ name: 'idx_catalog_quantity_rules_on_catalog_and_variant'++ # Born per currency: one row per currency, never one amount plus a+ # currency column (the recorded no-FX constraint).+ create_table :spree_catalog_order_minimums do |t|+ t.references :catalog, null: false, index: false+ t.string :currency, null: false+ t.decimal :amount, precision: 10, scale: 2, null: false, default: 0+ t.timestamps+ end++ add_index :spree_catalog_order_minimums, [:catalog_id, :currency], unique: true,+ name: 'idx_catalog_order_minimums_on_catalog_and_currency'+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/catalog_factory.rb b/spree/core/lib/spree/testing_support/factories/catalog_factory.rbindex a360797d40..4aec606934 100644--- a/spree/core/lib/spree/testing_support/factories/catalog_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/catalog_factory.rb@@ -13,4 +13,17 @@ FactoryBot.define docatalogassignable { association(:company, store: catalog.store) }end++ factory :catalog_quantity_rule, class: Spree::CatalogQuantityRule do+ catalog+ variant { association(:variant, product: association(:product, store: catalog.store)) }+ minimum_order_quantity { 48 }+ order_multiple { 24 }+ end++ factory :catalog_order_minimum, class: Spree::CatalogOrderMinimum do+ catalog+ currency { 'USD' }+ amount { 500 }+ endenddiff --git a/spree/core/spec/models/spree/catalog_order_minimum_spec.rb b/spree/core/spec/models/spree/catalog_order_minimum_spec.rbnew file mode 100644index 0000000000..59d362cb78--- /dev/null+++ b/spree/core/spec/models/spree/catalog_order_minimum_spec.rb@@ -0,0 +1,36 @@+require 'spec_helper'++RSpec.describe Spree::CatalogOrderMinimum do+ let(:store) { @default_store }+ let(:catalog) { create(:catalog, store: store) }++ it 'upcases the currency it is given' do+ minimum = create(:catalog_order_minimum, catalog: catalog, currency: 'usd')++ expect(minimum.currency).to eq('USD')+ end++ it 'refuses a second row for the same currency' do+ create(:catalog_order_minimum, catalog: catalog, currency: 'USD')++ expect(build(:catalog_order_minimum, catalog: catalog, currency: 'USD')).not_to be_valid+ end++ it 'enforces the per-currency uniqueness in the database as well' do+ create(:catalog_order_minimum, catalog: catalog, currency: 'USD')++ expect {+ described_class.new(catalog: catalog, currency: 'USD', amount: 100).save(validate: false)+ }.to raise_error(ActiveRecord::RecordNotUnique)+ end++ it 'allows the same catalog a row in another currency' do+ create(:catalog_order_minimum, catalog: catalog, currency: 'USD')++ expect(build(:catalog_order_minimum, catalog: catalog, currency: 'EUR')).to be_valid+ end++ it 'refuses a zero amount' do+ expect(build(:catalog_order_minimum, catalog: catalog, amount: 0)).not_to be_valid+ end+enddiff --git a/spree/core/spec/models/spree/catalog_quantity_rule_spec.rb b/spree/core/spec/models/spree/catalog_quantity_rule_spec.rbnew file mode 100644index 0000000000..e41aa0c77b--- /dev/null+++ b/spree/core/spec/models/spree/catalog_quantity_rule_spec.rb@@ -0,0 +1,51 @@+require 'spec_helper'++RSpec.describe Spree::CatalogQuantityRule do+ let(:store) { @default_store }+ let(:catalog) { create(:catalog, store: store) }+ let(:variant) { create(:variant, product: create(:product, store: store)) }++ it 'refuses a row that states neither field' do+ rule = build(:catalog_quantity_rule, catalog: catalog, variant: variant,+ minimum_order_quantity: nil, order_multiple: nil)++ expect(rule).not_to be_valid+ expect(rule.errors[:base]).to be_present+ end++ it 'accepts a row stating only one field' do+ rule = build(:catalog_quantity_rule, catalog: catalog, variant: variant,+ minimum_order_quantity: 48, order_multiple: nil)++ expect(rule).to be_valid+ end++ it 'refuses a variant belonging to another store' do+ foreign = create(:variant, product: create(:product, store: create(:store)))+ rule = build(:catalog_quantity_rule, catalog: catalog, variant: foreign)++ expect(rule).not_to be_valid+ expect(rule.errors[:variant]).to be_present+ end++ it 'allows only one row per catalog and variant' do+ create(:catalog_quantity_rule, catalog: catalog, variant: variant)+ duplicate = build(:catalog_quantity_rule, catalog: catalog, variant: variant)++ expect(duplicate).not_to be_valid+ end++ it 'enforces the uniqueness in the database as well' do+ create(:catalog_quantity_rule, catalog: catalog, variant: variant)++ expect {+ described_class.new(catalog: catalog, variant: variant, minimum_order_quantity: 6).+ save(validate: false)+ }.to raise_error(ActiveRecord::RecordNotUnique)+ end++ it 'refuses a zero or negative quantity' do+ expect(build(:catalog_quantity_rule, catalog: catalog, variant: variant, minimum_order_quantity: 0)).not_to be_valid+ expect(build(:catalog_quantity_rule, catalog: catalog, variant: variant, order_multiple: -2)).not_to be_valid+ end+enddiff --git a/spree/core/spec/models/spree/purchase/quantity_rules_spec.rb b/spree/core/spec/models/spree/purchase/quantity_rules_spec.rbnew file mode 100644index 0000000000..b3c91e1ff0--- /dev/null+++ b/spree/core/spec/models/spree/purchase/quantity_rules_spec.rb@@ -0,0 +1,85 @@+require 'spec_helper'++RSpec.describe Spree::Purchase::QuantityRules do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }+ let(:customer) { create(:user) }+ let(:catalog) { create(:catalog, store: store) }+ let(:cart) { create(:cart, store: store, user: customer, company: company) }++ before do+ create(:company_membership, company: company, customer: customer)+ create(:catalog_assignment, catalog: catalog, assignable: company)+ Spree::Current.applicable_catalogs = nil+ end++ describe 'the order minimum' do+ before { create(:catalog_order_minimum, catalog: catalog, currency: 'USD', amount: 500) }++ it 'reads the buyer catalog row for the cart currency' do+ expect(cart.order_minimum_amount).to eq(500)+ end++ it 'reports how far off an empty cart is' do+ expect(cart.order_minimum_shortfall).to eq(500)+ expect(cart).to be_below_order_minimum+ end++ it 'reports nothing left to add once the items reach it' do+ product = create(:product, store: store, price: 600)+ Spree::Carts::AddItem.call(cart: cart, variant: product.default_variant, quantity: 1)++ expect(cart.reload.order_minimum_shortfall).to eq(0)+ expect(cart.reload).not_to be_below_order_minimum+ end++ # Delivery and tax are not what the buyer bought, so a threshold must not+ # be reachable by choosing faster shipping.+ it 'measures the item total rather than the order total' do+ product = create(:product, store: store, price: 100)+ Spree::Carts::AddItem.call(cart: cart, variant: product.default_variant, quantity: 1)++ expect(cart.reload.order_minimum_shortfall).to eq(400)+ end++ it 'is silent for a currency no catalog prices' do+ cart.update!(currency: 'GBP')++ expect(cart.reload.order_minimum).to be_nil+ expect(cart.reload).not_to be_below_order_minimum+ end+ end++ describe 'a buyer with no catalogs' do+ let(:cart) { create(:cart, store: store) }++ it 'has no minimum' do+ expect(cart.order_minimum).to be_nil+ expect(cart).not_to be_below_order_minimum+ end+ end++ describe '#line_items_violating_quantity_rules' do+ let(:product) { create(:product, store: store, price: 10) }+ let(:variant) { product.default_variant }++ before do+ Spree::Carts::AddItem.call(cart: cart, variant: variant, quantity: 3)+ end++ it 'is empty while every line still fits' do+ expect(cart.reload.line_items_violating_quantity_rules).to be_empty+ end++ it 'names a line the terms no longer admit, with the rule it breaks' do+ create(:catalog_quantity_rule, catalog: catalog, variant: variant,+ minimum_order_quantity: 48, order_multiple: 24)+ Spree::Current.applicable_catalogs = nil++ line_item, rule = cart.reload.line_items_violating_quantity_rules.first++ expect(line_item.variant).to eq(variant)+ expect(rule.minimum).to eq(48)+ end+ end+enddiff --git a/spree/core/spec/models/spree/quantity_rule_spec.rb b/spree/core/spec/models/spree/quantity_rule_spec.rbnew file mode 100644index 0000000000..884508bfae--- /dev/null+++ b/spree/core/spec/models/spree/quantity_rule_spec.rb@@ -0,0 +1,73 @@+require 'spec_helper'++RSpec.describe Spree::QuantityRule do+ describe 'defaults' do+ it 'lets anything through when nothing is declared' do+ rule = described_class.new++ expect(rule.minimum).to eq(1)+ expect(rule.multiple).to eq(1)+ expect(rule).to be_unrestricted+ expect(rule).to be_satisfied_by(7)+ end++ it 'treats zero and negative declarations as unset' do+ rule = described_class.new(minimum_order_quantity: 0, order_multiple: -5)++ expect(rule.minimum).to eq(1)+ expect(rule.multiple).to eq(1)+ end+ end++ describe '#satisfied_by?' do+ subject(:rule) { described_class.new(minimum_order_quantity: 48, order_multiple: 24) }++ it 'accepts the minimum and every step above it' do+ expect(rule).to be_satisfied_by(48)+ expect(rule).to be_satisfied_by(72)+ expect(rule).to be_satisfied_by(96)+ end++ it 'refuses anything below the minimum or off the step' do+ expect(rule).not_to be_satisfied_by(24)+ expect(rule).not_to be_satisfied_by(50)+ expect(rule).not_to be_satisfied_by(100)+ 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' do+ subject(:rule) { described_class.new(minimum_order_quantity: 50, order_multiple: 24) }++ it 'admits its own minimum and steps from there' do+ expect(rule).to be_satisfied_by(50)+ expect(rule).to be_satisfied_by(74)+ expect(rule).not_to be_satisfied_by(48)+ expect(rule).not_to be_satisfied_by(72)+ end+ end+ end++ describe '#nearest_valid' do+ subject(:rule) { described_class.new(minimum_order_quantity: 48, order_multiple: 24) }++ it 'offers both neighbours around an invalid quantity' do+ expect(rule.nearest_valid(60)).to eq([48, 72])+ end++ it 'offers only the minimum when the quantity is below it' do+ expect(rule.nearest_valid(10)).to eq([48])+ end++ it 'collapses to one value when the quantity is already valid' do+ expect(rule.nearest_valid(72)).to eq([72])+ end+ end++ describe 'equality' do+ it 'compares on the resolved pair rather than the raw columns' do+ expect(described_class.new(minimum_order_quantity: nil, order_multiple: nil)).+ to eq(described_class.new(minimum_order_quantity: 1, order_multiple: 1))+ end+ end+enddiff --git a/spree/core/spec/models/spree/variant_quantity_rules_spec.rb b/spree/core/spec/models/spree/variant_quantity_rules_spec.rbnew file mode 100644index 0000000000..05d0ae2976--- /dev/null+++ b/spree/core/spec/models/spree/variant_quantity_rules_spec.rb@@ -0,0 +1,64 @@+require 'spec_helper'++RSpec.describe Spree::Variant, 'quantity rules' do+ let(:store) { @default_store }+ let(:variant) { create(:variant, product: create(:product, store: store)) }++ describe 'validations' do+ it 'refuses a zero or negative rule' do+ expect(build(:variant, minimum_order_quantity: 0)).not_to be_valid+ expect(build(:variant, order_multiple: -1)).not_to be_valid+ expect(build(:variant, units_per_carton: 0)).not_to be_valid+ end++ it 'refuses a purchase unit outside the vocabulary' do+ expect(build(:variant, purchase_unit: 'pallet')).not_to be_valid+ end++ it 'requires a carton size when the purchase unit is cartons' do+ variant = build(:variant, purchase_unit: 'carton', units_per_carton: nil)++ expect(variant).not_to be_valid+ expect(variant.errors[:units_per_carton]).to be_present+ end++ # An order multiple that straddles carton boundaries can never ship whole,+ # so the merchant hears about it at edit time.+ it 'refuses an order multiple that does not line up with the carton' do+ expect(build(:variant, order_multiple: 24, units_per_carton: 20)).not_to be_valid+ end++ it 'accepts a multiple that divides the carton or is a multiple of it' do+ expect(build(:variant, order_multiple: 12, units_per_carton: 24)).to be_valid+ expect(build(:variant, order_multiple: 48, units_per_carton: 24)).to be_valid+ end+ end++ describe '#quantity_rule' do+ it 'reads the variant columns' do+ variant.update!(minimum_order_quantity: 48, order_multiple: 24)++ expect(variant.quantity_rule.minimum).to eq(48)+ expect(variant.quantity_rule.multiple).to eq(24)+ end++ it 'is unrestricted when the columns are empty' do+ expect(variant.quantity_rule).to be_unrestricted+ end+ end++ describe '#sold_by_carton? and #cartons_for' do+ it 'counts part cartons as whole ones' do+ variant.update!(purchase_unit: 'carton', units_per_carton: 24)++ expect(variant).to be_sold_by_carton+ expect(variant.cartons_for(48)).to eq(2)+ expect(variant.cartons_for(25)).to eq(2)+ end++ it 'answers nothing without a carton size' do+ expect(variant.cartons_for(48)).to be_nil+ expect(variant).not_to be_sold_by_carton+ end+ end+enddiff --git a/spree/core/spec/services/spree/catalogs/resolve_quantity_rules_spec.rb b/spree/core/spec/services/spree/catalogs/resolve_quantity_rules_spec.rbnew file mode 100644index 0000000000..7e71be6d1e--- /dev/null+++ b/spree/core/spec/services/spree/catalogs/resolve_quantity_rules_spec.rb@@ -0,0 +1,145 @@+require 'spec_helper'++RSpec.describe Spree::Catalogs::ResolveQuantityRules do+ let(:store) { @default_store }+ let(:product) { create(:product, store: store) }+ let(:variant) { product.default_variant }++ describe '#call' do+ it 'falls back to the variant base rules when no catalog applies' do+ variant.update!(minimum_order_quantity: 12, order_multiple: 6)++ rule = described_class.new([]).call(variant)++ expect(rule.minimum).to eq(12)+ expect(rule.multiple).to eq(6)+ end++ it "reads a catalog's own default columns" do+ catalog = create(:catalog, store: store, minimum_order_quantity: 48, order_multiple: 24)++ rule = described_class.new([catalog]).call(variant)++ expect(rule.minimum).to eq(48)+ expect(rule.multiple).to eq(24)+ end++ it 'lets a per-variant override beat the catalog default' do+ catalog = create(:catalog, store: store, minimum_order_quantity: 48, order_multiple: 24)+ create(:catalog_quantity_rule, catalog: catalog, variant: variant,+ minimum_order_quantity: 480, order_multiple: 240)++ rule = described_class.new([catalog]).call(variant)++ expect(rule.minimum).to eq(480)+ expect(rule.multiple).to eq(240)+ end++ it 'leaves a variant the override does not name on the catalog default' do+ catalog = create(:catalog, store: store, minimum_order_quantity: 48, order_multiple: 24)+ other = create(:variant, product: create(:product, store: store))+ create(:catalog_quantity_rule, catalog: catalog, variant: other,+ minimum_order_quantity: 480, order_multiple: 240)++ rule = described_class.new([catalog]).call(variant)++ expect(rule.minimum).to eq(48)+ end++ # The per-field rule: an agreement silent on a field passes it through+ # rather than waiving it.+ describe 'per-field resolution' do+ it 'takes each field from the nearest catalog that states it' do+ nearest = create(:catalog, store: store, minimum_order_quantity: 100, order_multiple: nil)+ fallback = create(:catalog, store: store, minimum_order_quantity: 48, order_multiple: 24)++ rule = described_class.new([nearest, fallback]).call(variant)++ expect(rule.minimum).to eq(100)+ expect(rule.multiple).to eq(24)+ end++ it 'falls through a catalog that states nothing at all' do+ silent = create(:catalog, store: store)+ fallback = create(:catalog, store: store, minimum_order_quantity: 48, order_multiple: 24)++ rule = described_class.new([silent, fallback]).call(variant)++ expect(rule.minimum).to eq(48)+ expect(rule.multiple).to eq(24)+ end++ it 'reaches the variant base for a field no catalog states' do+ variant.update!(order_multiple: 6)+ catalog = create(:catalog, store: store, minimum_order_quantity: 48)++ rule = described_class.new([catalog]).call(variant)++ expect(rule.minimum).to eq(48)+ expect(rule.multiple).to eq(6)+ end++ it 'mixes an override field with a further catalog for the other field' do+ nearest = create(:catalog, store: store)+ create(:catalog_quantity_rule, catalog: nearest, variant: variant,+ minimum_order_quantity: 12, order_multiple: nil)+ fallback = create(:catalog, store: store, minimum_order_quantity: 48, order_multiple: 24)++ rule = described_class.new([nearest, fallback]).call(variant)++ expect(rule.minimum).to eq(12)+ expect(rule.multiple).to eq(24)+ end+ end+ end++ describe '#order_minimum' do+ let(:catalog) { create(:catalog, store: store) }++ it 'finds the row for the currency asked about' do+ create(:catalog_order_minimum, catalog: catalog, currency: 'USD', amount: 500)+ create(:catalog_order_minimum, catalog: catalog, currency: 'EUR', amount: 450)++ expect(described_class.new([catalog]).order_minimum('USD').amount).to eq(500)+ expect(described_class.new([catalog]).order_minimum('EUR').amount).to eq(450)+ end++ it 'is nil for a currency no catalog states' do+ create(:catalog_order_minimum, catalog: catalog, currency: 'USD', amount: 500)++ expect(described_class.new([catalog]).order_minimum('GBP')).to be_nil+ end++ # A nearer agreement silent on a currency must not waive the fallback's+ # threshold — the same per-field rule the quantity terms follow.+ it 'falls through a nearer catalog that prices a different currency' do+ nearest = create(:catalog, store: store)+ create(:catalog_order_minimum, catalog: nearest, currency: 'EUR', amount: 450)+ fallback = create(:catalog, store: store)+ create(:catalog_order_minimum, catalog: fallback, currency: 'USD', amount: 500)++ expect(described_class.new([nearest, fallback]).order_minimum('USD').amount).to eq(500)+ end++ it 'lets the nearest catalog win a currency both state' do+ nearest = create(:catalog, store: store)+ create(:catalog_order_minimum, catalog: nearest, currency: 'USD', amount: 250)+ fallback = create(:catalog, store: store)+ create(:catalog_order_minimum, catalog: fallback, currency: 'USD', amount: 500)++ expect(described_class.new([nearest, fallback]).order_minimum('USD').amount).to eq(250)+ end+ end++ 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+ end+enddiff --git a/spree/core/spec/workflows/spree/carts/quantity_rules_enforcement_spec.rb b/spree/core/spec/workflows/spree/carts/quantity_rules_enforcement_spec.rbnew file mode 100644index 0000000000..4474c041c2--- /dev/null+++ b/spree/core/spec/workflows/spree/carts/quantity_rules_enforcement_spec.rb@@ -0,0 +1,139 @@+require 'spec_helper'++# The purchasing layer end to end: what the workflows refuse, what they let+# through, and who is exempt.+RSpec.describe 'cart quantity rule enforcement' do+ let(:store) { @default_store }+ let(:product) { create(:product, store: store, price: 10) }+ let(:variant) { product.default_variant }+ let(:cart) { create(:cart, store: store) }++ before { variant.update!(minimum_order_quantity: 48, order_multiple: 24) }++ describe Spree::Carts::AddItem do+ it 'refuses a quantity below the minimum and names the valid ones' do+ result = described_class.call(cart: cart, variant: variant, quantity: 10)++ expect(result).to be_failure+ expect(result.error.to_s).to include('48')+ expect(cart.reload.line_items).to be_empty+ end++ it 'refuses a quantity off the multiple, offering both neighbours' do+ result = described_class.call(cart: cart, variant: variant, quantity: 60)++ expect(result).to be_failure+ expect(result.error.to_s).to include('48')+ expect(result.error.to_s).to include('72')+ end++ it 'accepts a valid quantity' do+ expect(described_class.call(cart: cart, variant: variant, quantity: 72)).to be_success+ end++ # An add is an increment, so what matters is where the line ends up.+ it 'judges the resulting line quantity, not the increment' do+ described_class.call(cart: cart, variant: variant, quantity: 48)++ result = described_class.call(cart: cart, variant: variant, quantity: 24)++ expect(result).to be_success+ expect(cart.reload.line_items.first.quantity).to eq(72)+ end++ it 'refuses an increment that lands the line off the multiple' do+ described_class.call(cart: cart, variant: variant, quantity: 48)++ expect(described_class.call(cart: cart, variant: variant, quantity: 5)).to be_failure+ expect(cart.reload.line_items.first.quantity).to eq(48)+ end++ it 'leaves a variant with no rules alone' do+ variant.update!(minimum_order_quantity: nil, order_multiple: nil)++ expect(described_class.call(cart: cart, variant: variant, quantity: 7)).to be_success+ end++ # The admin surface is a draft order, not a cart — a cart is always the+ # buyer's own.+ it 'lets staff key in whatever the buyer negotiated on a draft order' do+ draft = create(:order, store: store)++ expect(described_class.call(cart: draft, variant: variant, quantity: 5)).to be_success+ end+ end++ describe Spree::Carts::UpsertItems do+ it 'warns about a line it will not apply rather than failing the batch' do+ other = create(:product, store: store, price: 5).default_variant++ result = described_class.call(cart: cart, items: [+ { variant_id: variant.id, quantity: 10 },+ { variant_id: other.id, quantity: 3 }+ ])++ expect(result).to be_success+ # Warnings ride on the returned cart; reading them before touching the+ # record matters, because a reload drops them.+ expect(result.value.warnings.map { |warning| warning[:code] }).to include('quantity_rule_violated')+ expect(cart.reload.line_items.map(&:variant)).to eq([other])+ end++ it 'applies a valid quantity' do+ result = described_class.call(cart: cart, items: [{ variant_id: variant.id, quantity: 96 }])++ expect(result).to be_success+ expect(cart.reload.line_items.first.quantity).to eq(96)+ end++ # This workflow sets rather than increments, so a quantity edit down to an+ # invalid number is refused too.+ it 'refuses a quantity edit that breaks the rule' do+ described_class.call(cart: cart, items: [{ variant_id: variant.id, quantity: 96 }])++ described_class.call(cart: cart, items: [{ variant_id: variant.id, quantity: 30 }])++ expect(cart.reload.line_items.first.quantity).to eq(96)+ end++ # A buyer must always be able to empty a line, whatever the rules now say+ # about holding one.+ it 'always allows a removal' do+ described_class.call(cart: cart, items: [{ variant_id: variant.id, quantity: 96 }])+ variant.update!(minimum_order_quantity: 1000)++ described_class.call(cart: cart, items: [{ variant_id: variant.id, quantity: 0 }])++ expect(cart.reload.line_items).to be_empty+ end+ end++ describe Spree::Checkout::DefaultRequirements do+ let(:requirements) { described_class.new(cart.reload).call(completion: true) }++ before do+ Spree::Carts::AddItem.call(cart: cart, variant: variant, quantity: 48)+ end++ it 'says nothing while the line still satisfies its rules' do+ expect(requirements.map { |r| r[:code] }).not_to include('quantity_rule_violated')+ end++ # Terms can change under a buyer between the add and the checkout.+ it 'refuses a line the rules no longer admit' do+ variant.update!(minimum_order_quantity: 100, order_multiple: 100)++ violation = requirements.detect { |r| r[:code] == 'quantity_rule_violated' }++ expect(violation).to be_present+ expect(violation[:message]).to include('100')+ end++ it 'exempts a staff-keyed purchase' do+ allow(cart).to receive(:created_by_id).and_return(1)+ variant.update!(minimum_order_quantity: 100, order_multiple: 100)++ expect(requirements.map { |r| r[:code] }).not_to include('quantity_rule_violated')+ end+ end+end