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
Consolidate the catalog resolution and quantity-rule plumbing
Damian Legawiece20d1dfe2f34
diff --git a/packages/admin-sdk/src/types/generated/Catalog.ts b/packages/admin-sdk/src/types/generated/Catalog.tsindex efb09800bd..825edb4762 100644--- a/packages/admin-sdk/src/types/generated/Catalog.ts+++ b/packages/admin-sdk/src/types/generated/Catalog.ts@@ -1,4 +1,4 @@-// Typelizer digest 0643266f193be6461c09b87b99bdcada+// Typelizer digest b7baf3eaaa427803931c78108e767569//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {CatalogOrderMinimum, PriceList, CatalogAssignment} from '@/types'@@ -16,8 +16,6 @@ interface Catalog {updated_at: string;price_list_id: string | null;products_count: number;- quantity_rules_count: number;- order_minimums_count: number;order_minimums?: Array<CatalogOrderMinimum>;price_list?: PriceList;assignments?: Array<CatalogAssignment>;diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.tsindex c991590679..1ad839320e 100644--- a/packages/dashboard-core/src/index.ts+++ b/packages/dashboard-core/src/index.ts@@ -105,6 +105,7 @@ export * from './plugin'export * from './products/currency-parts'export * from './products/normalize-customs'export * from './products/normalize-money'+export * from './products/normalize-quantity'export * from './products/product-form-cards'export * from './products/product-form-mapping'export * from './products/product-schema'diff --git a/packages/dashboard/src/components/spree/catalog-terms-card.tsx b/packages/dashboard/src/components/spree/catalog-terms-card.tsxindex 8342d878c4..9183596c0b 100644--- a/packages/dashboard/src/components/spree/catalog-terms-card.tsx+++ b/packages/dashboard/src/components/spree/catalog-terms-card.tsx@@ -1,5 +1,11 @@import type { CatalogOrderMinimum, CatalogQuantityRule, Variant } from '@spree/admin-sdk'-import { adminClient, CurrencySelect, ResourceCombobox, useStore } from '@spree/dashboard-core'+import {+ adminClient,+ CurrencySelect,+ normalizeQuantityRule,+ ResourceCombobox,+ useStore,+} from '@spree/dashboard-core'import {Button,Card,@@ -422,8 +428,8 @@ function AddQuantityRuleDialog({await createMutation.mutateAsync({variant_id: variantId,- minimum_order_quantity: minimum.trim() ? Number(minimum) : null,- order_multiple: multiple.trim() ? Number(multiple) : null,+ minimum_order_quantity: normalizeQuantityRule(minimum),+ order_multiple: normalizeQuantityRule(multiple),}).then(() => {setVariantId('')diff --git a/packages/dashboard/src/hooks/use-catalogs.ts b/packages/dashboard/src/hooks/use-catalogs.tsindex b9fdcf9435..68881be0c5 100644--- a/packages/dashboard/src/hooks/use-catalogs.ts+++ b/packages/dashboard/src/hooks/use-catalogs.ts@@ -174,23 +174,6 @@ export function useCreateCatalogQuantityRule(catalogId: string) {})}-export function useUpdateCatalogQuantityRule(catalogId: string) {- return useResourceMutation<- CatalogQuantityRule,- Error,- { id: string; params: CatalogQuantityRuleParams }- >({- mutationFn: ({ id, params }) =>- adminClient.catalogs.quantityRules.update(catalogId, id, params),- invalidate: [- ['catalogs', catalogId],- ['catalogs', catalogId, 'quantity_rules'],- ],- successMessage: i18n.t('admin.catalogs.terms.messages.rule_updated'),- errorMessage: i18n.t('admin.errors.failed_to_update'),- })-}-export function useDeleteCatalogQuantityRule(catalogId: string) {return useResourceMutation<void, Error, string>({mutationFn: (id) => adminClient.catalogs.quantityRules.delete(catalogId, id),diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.tsindex f485ae4a3d..d3807689ca 100644--- a/packages/dashboard/src/schemas/catalog.ts+++ b/packages/dashboard/src/schemas/catalog.ts@@ -1,5 +1,5 @@import type { CatalogParams, PriceList } from '@spree/admin-sdk'-import { blankToNull } from '@spree/dashboard-core'+import { blankToNull, normalizeQuantityRule } from '@spree/dashboard-core'import { requiredMessage } from '@spree/dashboard-ui'import i18n from 'i18next'import { z } from 'zod/v4'@@ -62,11 +62,18 @@ export const catalogFormSchema = zminimum_order_quantity: z.string().trim().optional(),order_multiple: z.string().trim().optional(),})- .refine((v) => isBlankOrPositiveInteger(v.minimum_order_quantity), {- path: ['minimum_order_quantity'],- error: () => i18n.t('admin.catalogs.terms.validation.positive_integer'),- })- .refine((v) => isBlankOrPositiveInteger(v.order_multiple), {+ // Blank is a valid answer — it means the agreement states nothing — so the+ // shared normalizer's null stands for both "unset" and "unusable", and only+ // a non-blank field that normalizes away is an error.+ .refine(+ (v) =>+ !v.minimum_order_quantity?.trim() || normalizeQuantityRule(v.minimum_order_quantity) !== null,+ {+ path: ['minimum_order_quantity'],+ error: () => i18n.t('admin.catalogs.terms.validation.positive_integer'),+ },+ )+ .refine((v) => !v.order_multiple?.trim() || normalizeQuantityRule(v.order_multiple) !== null, {path: ['order_multiple'],error: () => i18n.t('admin.catalogs.terms.validation.positive_integer'),})@@ -120,18 +127,6 @@ export const CATALOG_DEFAULTS: CatalogFormValues = {staged_products: { adds: [], removes: [] },}-/** Blank is a valid answer — it means the agreement states nothing. */-function isBlankOrPositiveInteger(value: string | undefined): boolean {- if (!value?.trim()) return true- return /^\d+$/.test(value.trim()) && Number(value) > 0-}--/** Parses a terms field, where blank means "say nothing" rather than zero. */-export function parseTermQuantity(value: string | undefined): number | null {- const trimmed = value?.trim()- return trimmed ? Number(trimmed) : null-}-/*** Maps form values to the Admin API payload. The catalog and the list it* prices through are written in one request, so `price_list` rides inline:@@ -148,8 +143,8 @@ export function catalogValuesToParams(name: values.name,description: blankToNull(values.description),active: values.active,- minimum_order_quantity: parseTermQuantity(values.minimum_order_quantity),- order_multiple: parseTermQuantity(values.order_multiple),+ minimum_order_quantity: normalizeQuantityRule(values.minimum_order_quantity),+ order_multiple: normalizeQuantityRule(values.order_multiple),price_list: priceListPayload(values, previousMode),}}diff --git a/spree/api/app/controllers/spree/api/v3/admin/catalogs/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/catalogs/products_controller.rbindex 66d2c47f9d..dd75b05c54 100644--- a/spree/api/app/controllers/spree/api/v3/admin/catalogs/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/catalogs/products_controller.rb@@ -8,17 +8,17 @@ module Spree# Spree::Api::V3::Admin::ProductMembership). A catalog decides what# a buyer sees, never the order they see it in, so membership# carries no position and listing is ordered by name.- class ProductsController < ResourceController+ class ProductsController < BaseControllerinclude Spree::Api::V3::Admin::ProductMembership- scoped_resource :products+ before_action :authorize_parent_access!protecteddef scopeproduct_scope.joins(:catalog_products).- where(Spree::CatalogProduct.table_name => { catalog_id: @parent_catalog.id }).+ where(Spree::CatalogProduct.table_name => { catalog_id: @catalog.id }).order(:name)end@@ -30,20 +30,13 @@ module Spreeenddef add_member_products(products)- @parent_catalog.add_products(products.map(&:id))+ @catalog.add_products(products.map(&:id))end# Through the model, so an owned price list drops the rows it# held for these products along with them.def remove_member_products(products)- @parent_catalog.remove_products(products.map(&:id))- end-- def set_parent- @parent_catalog = current_store.catalogs.- accessible_by(current_ability, parent_ability_action).- find_by_prefix_id!(params[:catalog_id])- authorize_parent!(@parent_catalog)+ @catalog.remove_products(products.map(&:id))endendenddiff --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 b58eb8f1dd..639f5b013a 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, :quantity_rules]+ [:catalog_products, :price_list, :order_minimums]enddef create_workflowdiff --git a/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rbindex 442944bea1..1abe4173a5 100644--- a/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rb@@ -10,7 +10,6 @@ module Spreeprice_list_id: [:string, nullable: true],products_count: :number,minimum_order_quantity: ['number | null'], order_multiple: ['number | null'],- quantity_rules_count: :number, order_minimums_count: :number,metadata: 'Record<string, unknown> | null'attributes :name, :description, :active, :position, :metadata,@@ -25,16 +24,6 @@ module Spreecatalog.catalog_products.sizeend- # Counts rather than the rows themselves: a catalog can carry- # thousands of overrides, and the terms card pages through them.- attribute :quantity_rules_count do |catalog|- catalog.quantity_rules.size- end-- attribute :order_minimums_count do |catalog|- catalog.order_minimums.size- end-# Minimums are few (one per currency) and the card renders them# inline, so they ride along rather than costing a second request.many :order_minimums,diff --git a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rbindex 50c1410067..1596280ad4 100644--- a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb@@ -26,27 +26,16 @@ module Spreepurchase_unit: [:string, nullable: true],metadata: 'Record<string, unknown>'+ # The last three override the store serializer's buyer-resolved+ # values with the variant's OWN: a merchant edits what is stored on+ # the row, not what some catalog resolves to for a buyer they are not.attributes :metadata, :position, :cost_price, :cost_currency,:barcode, :weight_unit, :dimensions_unit, :backorder_limit,:hs_code, :country_of_origin, :customs_description,+ :minimum_order_quantity, :order_multiple, :purchase_unit,preorder_ships_at: :iso8601, deleted_at: :iso8601,created_at: :iso8601, updated_at: :iso8601- # The variant's OWN rules, overriding the store serializer's- # buyer-resolved ones: a merchant edits what is stored on the row,- # not what some catalog resolves to for a buyer they are not.- attribute :minimum_order_quantity do |variant|- variant.minimum_order_quantity- end-- attribute :order_multiple do |variant|- variant.order_multiple- end-- attribute :purchase_unit do |variant|- variant.purchase_unit- end-attribute :preorderable do |variant|variant.preorderable?enddiff --git a/spree/api/app/serializers/spree/api/v3/base_serializer.rb b/spree/api/app/serializers/spree/api/v3/base_serializer.rbindex d7e8f03484..3511e009a9 100644--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb@@ -114,21 +114,18 @@ module Spree# rules. Read from the request context the same way price_for does,# so a storefront gets the stepper matching the price it is quoted.#- # One resolver per render rather than one per variant: a listing page- # asks about every row against the same few catalogs.+ # The resolver is request-scoped, not instance-scoped: Alba builds a+ # fresh serializer for every element of a collection, so a memo held+ # here would reload each catalog's override rows once per row on the+ # page. Resolving without the buyer's company would also answer from+ # a different agreement than the one pricing the same page.def quantity_rule_for(variant)- @quantity_rule_cache ||= {}- @quantity_rule_cache[variant.id] ||= quantity_rules_resolver.call(variant)- end+ return Spree::QuantityRule.new if current_store.nil?- # 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::Catalog.for_buyer(store: current_store, customer: current_user)- )+ Spree::Current.quantity_rules_resolver_for(+ company: Spree::Company.sole_standing_for(store: current_store, customer: current_user),+ user: current_user+ ).call(variant)end# Returns the base price for a variant without Price List resolutiondiff --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.rbindex 4923e73431..dbdb36078b 100644--- 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.rb@@ -13,7 +13,7 @@ RSpec.describe Spree::Api::V3::VariantSerializer, 'quantity rules' dobefore doSpree::Current.store = store- Spree::Current.applicable_catalogs = nil+ Spree::Current.reset_catalog_memosendit 'reads 1 and 1 when nothing declares a rule' do@@ -42,7 +42,7 @@ RSpec.describe Spree::Api::V3::VariantSerializer, 'quantity rules' docatalog = 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+ Spree::Current.reset_catalog_memosjson = render(user: customer)diff --git a/spree/core/app/models/concerns/spree/purchase/company.rb b/spree/core/app/models/concerns/spree/purchase/company.rbindex f52cf7cc22..a30bdf6e0f 100644--- a/spree/core/app/models/concerns/spree/purchase/company.rb+++ b/spree/core/app/models/concerns/spree/purchase/company.rb@@ -87,18 +87,9 @@ module Spree# this safely needs the reset-on-reload machinery; the repeated query is# the cheaper problem.def sole_standing_company- return nil if customer.nil? || store_id.nil?+ return nil if store_id.nil?- # Scoped to this sale's store. Customers are global, so without this a- # buyer who is a member at a company in another store would resolve to- # that business here — and its registration and exemption certificates- # would then decide this sale's tax.- memberships = customer.company_memberships.- joins(:company).- merge(Spree::Company.where(store_id: store_id)).- to_a.uniq-- memberships.one? ? memberships.first.company : nil+ Spree::Company.sole_standing_for(store: store, customer: customer)endendenddiff --git a/spree/core/app/models/concerns/spree/purchase/quantity_rules.rb b/spree/core/app/models/concerns/spree/purchase/quantity_rules.rbindex bb88ceaef2..d522f6545d 100644--- a/spree/core/app/models/concerns/spree/purchase/quantity_rules.rb+++ b/spree/core/app/models/concerns/spree/purchase/quantity_rules.rb@@ -11,6 +11,36 @@ 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.+ #+ # 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.+ #+ # @return [Boolean]+ def staff_initiated?+ is_a?(Spree::Order) || (respond_to?(:created_by_id) && created_by_id.present?)+ end++ # Why this buyer may not order that many of a variant, naming what they+ # may order instead — nil when the quantity is fine, and nil for staff,+ # who are unrestricted. The one place the three enforcement points get+ # their answer, so they all refuse in the same words.+ #+ # @param variant [Spree::Variant]+ # @param quantity [Integer]+ # @param name [String, nil] what to call the item; defaults to the variant+ # @return [String, nil]+ def quantity_rule_violation(variant, quantity, name: nil)+ return nil if staff_initiated?++ quantity_rules_for(variant).violation_message(name || variant.name, quantity)+ end+# The buyer's effective rules for one variant: their catalogs' terms# resolved per field over the variant's own base rules.#@@ -57,22 +87,22 @@ module Spreeshortfall.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.+ # Why each line may no longer be ordered as it stands, in the same words+ # add-to-cart used. Empty for a retail buyer, and empty for anyone whose+ # terms have not changed under them since they built the cart.#- # @return [Array<Array(Spree::LineItem, Spree::QuantityRule)>]- def line_items_violating_quantity_rules- resolver = quantity_rules_resolver+ # @return [Array<Array(Spree::LineItem, String)>]+ def quantity_rule_violations+ return [] if staff_initiated?line_items.filter_map do |line_item|variant = line_item.variantnext if variant.nil?- rule = resolver.call(variant)- next if rule.satisfied_by?(line_item.quantity)+ message = quantity_rules_for(variant).violation_message(line_item.name, line_item.quantity)+ next if message.nil?- [line_item, rule]+ [line_item, message]endenddiff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rbindex 417303b60b..f577c4a8cb 100644--- a/spree/core/app/models/spree/catalog.rb+++ b/spree/core/app/models/spree/catalog.rb@@ -67,10 +67,7 @@ module Spree# `update_all` and so never runs PriceList's own callback — without this# the released list stays missing from the request's matching set, and# anything priced later in that request misses it.- after_commit -> {- Spree::Current.applicable_catalogs = nil- Spree::Current.price_lists = nil- }+ after_commit -> { Spree::Current.reset_catalog_memos }scope :active, -> { where(active: true) }scope :by_position, -> { order(position: :asc) }@@ -174,7 +171,7 @@ module Spreedef self.for_buyer(store:, customer: nil, company: nil, channel: nil)return [] if store.nil?- company ||= sole_standing_company(store, customer)+ company ||= Spree::Company.sole_standing_for(store: store, customer: customer)channel ||= Spree::Current.channel if store == Spree::Current.storeif store == Spree::Current.store@@ -184,24 +181,6 @@ module Spreeendend- # 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@@ -342,18 +321,6 @@ 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-private# Runs before anything is written, so a foreign-store list is a validationdiff --git a/spree/core/app/models/spree/catalog_assignment.rb b/spree/core/app/models/spree/catalog_assignment.rbindex a80613a690..de2f14d2f2 100644--- a/spree/core/app/models/spree/catalog_assignment.rb+++ b/spree/core/app/models/spree/catalog_assignment.rb@@ -22,7 +22,7 @@ module Spreevalidates :catalog_id, uniqueness: { scope: [:assignable_type, :assignable_id, *spree_base_uniqueness_scope] }validate :assignable_in_same_store- after_commit -> { Spree::Current.applicable_catalogs = nil }+ after_commit -> { Spree::Current.reset_catalog_memos }delegate :store, :store_id, to: :catalogdiff --git a/spree/core/app/models/spree/catalog_order_minimum.rb b/spree/core/app/models/spree/catalog_order_minimum.rbindex 40ea67f01f..0d51059311 100644--- a/spree/core/app/models/spree/catalog_order_minimum.rb+++ b/spree/core/app/models/spree/catalog_order_minimum.rb@@ -16,7 +16,7 @@ module Spreedelegate :store, :store_id, to: :catalog- after_commit -> { Spree::Current.applicable_catalogs = nil }+ after_commit -> { Spree::Current.reset_catalog_memos }# @return [Spree::Money]def display_amountdiff --git a/spree/core/app/models/spree/catalog_quantity_rule.rb b/spree/core/app/models/spree/catalog_quantity_rule.rbindex 26dfb294a8..cdf03c8f44 100644--- a/spree/core/app/models/spree/catalog_quantity_rule.rb+++ b/spree/core/app/models/spree/catalog_quantity_rule.rb@@ -24,15 +24,7 @@ module Spree# 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+ after_commit -> { Spree::Current.reset_catalog_memos }privatediff --git a/spree/core/app/models/spree/checkout/default_requirements.rb b/spree/core/app/models/spree/checkout/default_requirements.rbindex 7a754f7498..56c52eeb4d 100644--- a/spree/core/app/models/spree/checkout/default_requirements.rb+++ b/spree/core/app/models/spree/checkout/default_requirements.rb@@ -50,14 +50,8 @@ module Spree# 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')+ @cart.quantity_rule_violations.map do |_line_item, message|+ req('cart', 'line_items', message, code: 'quantity_rule_violated')endend@@ -66,7 +60,7 @@ module Spree# 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?+ [email protected]_initiated? && @cart.below_order_minimum?enddef order_minimum_requirement@@ -117,18 +111,17 @@ module Spree# from the steps of a cart that owes nothing, and a requirement naming a# step the buyer never visits is one they cannot clear.def po_number_missing?- @cart.po_number.blank? && @cart.po_number_required? && !staff_initiated?+ @cart.po_number.blank? && @cart.po_number_required? && !keyed_in_by_staff?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.is_a?(Spree::Order) ||- (@cart.respond_to?(:created_by_id) && @cart.created_by_id.present?)+ # Narrower than {Spree::Purchase::QuantityRules#staff_initiated?} on+ # purpose. A buyer's PO reference commonly arrives with the paperwork,+ # so only an order someone actually keyed in is excused — a draft with+ # no recorded creator still has to ask for it. Quantity terms take the+ # wider exemption: any draft order is the admin surface, and refusing+ # staff there would make an agreed exception impossible to record.+ def keyed_in_by_staff?+ @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/company.rb b/spree/core/app/models/spree/company.rbindex 2e4b6e3748..d57a824a1a 100644--- a/spree/core/app/models/spree/company.rb+++ b/spree/core/app/models/spree/company.rb@@ -103,6 +103,41 @@ module Spreeself.whitelisted_ransackable_attributes = %w[name kind parent_id po_number_required]self.whitelisted_ransackable_associations = %w[parent children memberships external_references]+ # The node a buyer browses and buys as when they name none: the single+ # node they hold a membership on. Nil when they hold none, or several —+ # guessing would invoice one business for another's purchase.+ #+ # Deliberately the membership node rather than +Customer#company_standing+,+ # which expands to the whole subtree: a buyer with one membership over a+ # parent with three divisions has standing for four nodes but is still+ # unambiguous, and counting the expansion would refuse to resolve. Where+ # standing covers several nodes the buyer picks one on the cart, and+ # catalogs follow that choice — so what they browse, what they are charged+ # and how much they must take all agree.+ #+ # Scoped to the store: customers are global, so without it a buyer who is+ # a member at a company in another store would resolve to that business+ # here, and its agreement would decide this sale.+ #+ # @param store [Spree::Store, nil]+ # @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.+ companies = where(store_id: store.id).+ joins(:memberships).+ where(Spree::CompanyMembership.table_name => { customer_id: customer.id }).+ distinct.+ limit(2).+ to_a++ companies.one? ? companies.first : nil+ end+# @return [Array<Spree::Company>] parent chain, nearest first (leaf → root)def ancestorschain = []diff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rbindex 7d26a7c322..089c6540b8 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, :global_pricing_context, :provider_cache, :integrations+ attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :applicable_catalogs, :quantity_rules_resolvers, :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@@ -115,6 +115,40 @@ module Spreesuper || (self.applicable_catalogs = {})end+ # The quantity-rule resolver for a buyer in this request, keyed the same+ # way their catalogs are.+ #+ # Request-scoped rather than per-caller because a serializer is built+ # fresh for every variant on a listing: a per-instance memo would reload+ # and re-hash each catalog's override rows once per row on the page.+ #+ # @param company [Spree::Company, nil]+ # @param user [Object, nil]+ # @param channel [Spree::Channel, nil]+ # @return [Spree::Catalogs::ResolveQuantityRules]+ def quantity_rules_resolver_for(company: nil, user: nil, channel: nil)+ channel ||= self.channel+ key = [store&.id, company&.id, user&.id, channel&.id]+ quantity_rules_resolvers[key] ||= Spree::Catalogs::ResolveQuantityRules.new(+ catalogs_for(company: company, user: user, channel: channel)+ )+ end++ # @return [Hash]+ def quantity_rules_resolvers+ super || (self.quantity_rules_resolvers = {})+ 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.+ # @return [void]+ def reset_catalog_memos+ self.applicable_catalogs = nil+ self.quantity_rules_resolvers = nil+ self.price_lists = nil+ end+# Returns the current global pricing context, built from store, currency, country, and market.# @return [Spree::Pricing::Context]def global_pricing_contextdiff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rbindex bd869d4a9b..4fc5ce148d 100644--- a/spree/core/app/models/spree/pricing_provider/internal.rb+++ b/spree/core/app/models/spree/pricing_provider/internal.rb@@ -84,18 +84,17 @@ module Spreeselect { |list| list.applicable?(context) }end- # Catalogs that apply to this buyer. Reused from {Spree::Current}- # when the context is the current store, so a product listing does- # not re-resolve the same company / group / channel set per variant.+ # Catalogs that apply to this buyer, through the one entry point+ # visibility and quantity terms also use — what a buyer is shown, what+ # they pay and how much they must take have to come from the same+ # agreement. Reuses the request-scoped set for the current store, so a+ # listing does not re-resolve the same buyer per variant.# @return [Array<Spree::Catalog>]def catalogs_for_context- if context.store == Spree::Current.store- Spree::Current.catalogs_for(company: context.company, user: context.user, channel: context.channel)- else- Spree::Catalog.for_context(- store: context.store, company: context.company, user: context.user, channel: context.channel- )- end+ Spree::Catalog.for_buyer(+ store: context.store, customer: context.user,+ company: context.company, channel: context.channel+ )end# Returns the price lists for the context's storediff --git a/spree/core/app/models/spree/quantity_rule.rb b/spree/core/app/models/spree/quantity_rule.rbindex a0f56f4b6b..a7cb0e6637 100644--- a/spree/core/app/models/spree/quantity_rule.rb+++ b/spree/core/app/models/spree/quantity_rule.rb@@ -14,11 +14,6 @@ module Spreeattribute :minimum_order_quantity, :integerattribute :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 ordereddef minimumvalue = minimum_order_quantity.to_i@@ -31,7 +26,8 @@ module Spreevalue.positive? ? value : 1end- # True when neither rule narrows anything — the shape a retail buyer sees.+ # True when neither rule narrows anything — the shape a retail buyer sees,+ # and what a variant with empty columns resolves to.# @return [Boolean]def unrestricted?minimum == 1 && multiple == 1@@ -76,6 +72,21 @@ module Spree[previous_valid(quantity), next_valid(quantity)].compact.uniqend+ # Why a quantity was refused, naming what may be ordered instead — nil+ # when the quantity is fine. Lives here beside the arithmetic so the two+ # cart workflows and the completion check all refuse in the same words;+ # the server never rounds, so the neighbours are the whole answer.+ #+ # @param name [String] what the buyer called for+ # @param quantity [Integer]+ # @return [String, nil]+ def violation_message(name, quantity)+ return nil if satisfied_by?(quantity)++ Spree.t('cart_line_item.quantity_rule_violated',+ li_name: name, quantities: nearest_valid(quantity).to_sentence)+ end+# 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.diff --git a/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb b/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rbindex 7464f1941c..9bd39c9158 100644--- a/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb+++ b/spree/core/app/services/spree/catalogs/resolve_quantity_rules.rb@@ -59,7 +59,6 @@ module Spreeorder_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,@@ -69,7 +68,7 @@ module Spree# @param currency [String]# @return [Spree::CatalogOrderMinimum, nil]def order_minimum(currency)- return nil if currency.blank?+ return nil if currency.blank? || catalogs.empty?code = currency.to_s.upcasecatalogs.each do |catalog|diff --git a/spree/core/app/services/spree/products/for_context.rb b/spree/core/app/services/spree/products/for_context.rbindex 7fcc2ab138..59ef2c0649 100644--- a/spree/core/app/services/spree/products/for_context.rb+++ b/spree/core/app/services/spree/products/for_context.rb@@ -49,19 +49,6 @@ module Spree))end- private-- # The node a buyer browses as when they name none: the single node they- # hold a membership on.- #- # Deliberately the membership node rather than- # +Customer#company_standing+, which expands to the whole subtree — a- # buyer with one membership over a parent with three divisions has- # standing for four nodes but is still unambiguous, and counting the- # expansion would refuse to resolve. Where standing covers several- # 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.endendenddiff --git a/spree/core/app/workflows/spree/carts/add_item.rb b/spree/core/app/workflows/spree/carts/add_item.rbindex 0eab6509ae..8bca73f97a 100644--- a/spree/core/app/workflows/spree/carts/add_item.rb+++ b/spree/core/app/workflows/spree/carts/add_item.rb@@ -72,35 +72,16 @@ module Spree# 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)+ message = cart.quantity_rule_violation(variant, resulting_quantity)+ return if message.nil?# 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)- )+ errors.add(:base, :quantity_rule_violated, message: message)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 1994e5c63f..7ebf026ea3 100644--- a/spree/core/app/workflows/spree/carts/upsert_items.rb+++ b/spree/core/app/workflows/spree/carts/upsert_items.rb@@ -266,28 +266,16 @@ module Spree# 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)+ message = cart.quantity_rule_violation(item.variant, item.quantity)+ return if message.nil?# 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)- )+ errors.add(:base, :quantity_rule_violated, message: message)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/spec/models/spree/catalog_for_buyer_spec.rb b/spree/core/spec/models/spree/catalog_for_buyer_spec.rbindex 319f43bd45..dd05d13b19 100644--- a/spree/core/spec/models/spree/catalog_for_buyer_spec.rb+++ b/spree/core/spec/models/spree/catalog_for_buyer_spec.rb@@ -9,7 +9,7 @@ RSpec.describe Spree::Catalog, '.for_buyer' dobefore docreate(:company_membership, company: company, customer: customer)create(:catalog_assignment, catalog: catalog, assignable: company)- Spree::Current.applicable_catalogs = nil+ Spree::Current.reset_catalog_memosend# Every catalog-reading surface has to answer from the same set. A callerdiff --git a/spree/core/spec/models/spree/purchase/quantity_rules_spec.rb b/spree/core/spec/models/spree/purchase/quantity_rules_spec.rbindex b3c91e1ff0..3f2562bba6 100644--- a/spree/core/spec/models/spree/purchase/quantity_rules_spec.rb+++ b/spree/core/spec/models/spree/purchase/quantity_rules_spec.rb@@ -10,7 +10,7 @@ RSpec.describe Spree::Purchase::QuantityRules dobefore docreate(:company_membership, company: company, customer: customer)create(:catalog_assignment, catalog: catalog, assignable: company)- Spree::Current.applicable_catalogs = nil+ Spree::Current.reset_catalog_memosenddescribe 'the order minimum' do@@ -59,7 +59,7 @@ RSpec.describe Spree::Purchase::QuantityRules doendend- describe '#line_items_violating_quantity_rules' do+ describe '#quantity_rule_violations' dolet(:product) { create(:product, store: store, price: 10) }let(:variant) { product.default_variant }@@ -68,18 +68,29 @@ RSpec.describe Spree::Purchase::QuantityRules doendit 'is empty while every line still fits' do- expect(cart.reload.line_items_violating_quantity_rules).to be_empty+ expect(cart.reload.quantity_rule_violations).to be_emptyend- it 'names a line the terms no longer admit, with the rule it breaks' do+ it 'names a line the terms no longer admit, in the words add-to-cart used' docreate(:catalog_quantity_rule, catalog: catalog, variant: variant,minimum_order_quantity: 48, order_multiple: 24)- Spree::Current.applicable_catalogs = nil+ Spree::Current.reset_catalog_memos- line_item, rule = cart.reload.line_items_violating_quantity_rules.first+ line_item, message = cart.reload.quantity_rule_violations.firstexpect(line_item.variant).to eq(variant)- expect(rule.minimum).to eq(48)+ expect(message).to include('48')+ end++ # Staff key in what the buyer negotiated, so a draft order is never+ # refused at completion for a quantity they deliberately entered.+ it 'is empty for a staff-keyed purchase' do+ create(:catalog_quantity_rule, catalog: catalog, variant: variant,+ minimum_order_quantity: 48, order_multiple: 24)+ Spree::Current.reset_catalog_memos+ allow(cart).to receive(:staff_initiated?).and_return(true)++ expect(cart.quantity_rule_violations).to be_emptyendendenddiff --git a/spree/core/spec/models/spree/quantity_rule_spec.rb b/spree/core/spec/models/spree/quantity_rule_spec.rbindex 7f594fc685..3a6b5cfc66 100644--- a/spree/core/spec/models/spree/quantity_rule_spec.rb+++ b/spree/core/spec/models/spree/quantity_rule_spec.rb@@ -7,7 +7,6 @@ RSpec.describe Spree::QuantityRule doexpect(rule.minimum).to eq(1)expect(rule.multiple).to eq(1)- expect(rule).to be_unrestrictedexpect(rule).to be_satisfied_by(7)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.rbindex 4474c041c2..06ae02118f 100644--- a/spree/core/spec/workflows/spree/carts/quantity_rules_enforcement_spec.rb+++ b/spree/core/spec/workflows/spree/carts/quantity_rules_enforcement_spec.rb@@ -129,6 +129,22 @@ RSpec.describe 'cart quantity rule enforcement' doexpect(violation[:message]).to include('100')end+ # The two exemptions are deliberately different widths: quantity terms+ # excuse any draft order, a buyer's PO reference only one someone+ # actually keyed in. Widening one must not quietly widen the other.+ it 'still asks a draft order with no recorded creator for its PO number' do+ customer = create(:user)+ buyer_company = create(:company, store: store, po_number_required: true)+ create(:company_membership, company: buyer_company, customer: customer)+ draft = create(:order, store: store)+ draft.update_columns(customer_id: customer.id, company_id: buyer_company.id)++ codes = described_class.new(draft.reload).call(completion: true).map { |r| r[:code] }++ expect(codes).to include('po_number_required')+ expect(codes).not_to include('quantity_rule_violated')+ end+it 'exempts a staff-keyed purchase' doallow(cart).to receive(:created_by_id).and_return(1)variant.update!(minimum_order_quantity: 100, order_multiple: 100)