Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Let a store take its prices and stock from elsewhere

Damian Legawiece1e4a935d21e
diff --git a/spree/core/app/models/concerns/spree/integration_backed_provider.rb b/spree/core/app/models/concerns/spree/integration_backed_provider.rb
new file mode 100644
index 0000000000..14f2cc8dfe
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/integration_backed_provider.rb
@@ -0,0 +1,70 @@
+module Spree
+ # Shared contract for provider classes whose credentials live on a
+ # {Spree::Integration}: delivery rates, fulfillment, pricing and inventory.
+ #
+ # A provider declares only +integration_class+; whether a store may use it,
+ # how it is labelled in the admin, and how its credentials are resolved all
+ # follow from that. Stating those three rules once means a change to what
+ # "connected" means — an expired OAuth grant, say — lands in one place
+ # rather than in each provider family.
+ module IntegrationBackedProvider
+ extend ActiveSupport::Concern
+
+ class_methods do
+ # The Spree::Integration subclass holding this provider's credentials,
+ # as a class name string. Internal providers need none.
+ #
+ # @return [String, nil]
+ def integration_class
+ nil
+ end
+
+ # Whether the store can use this provider at all — admin pickers hide or
+ # prompt-to-connect providers whose integration is not connected.
+ #
+ # @param store [Spree::Store, nil]
+ # @return [Boolean]
+ def available_for_store?(store)
+ return true if integration_class.blank?
+
+ store.present? && store.integrations.active.exists?(type: integration_class)
+ end
+
+ # The name a merchant sees when choosing a provider.
+ #
+ # A gem's provider is conventionally named for its family
+ # (+SpreeEasyPost::PricingProvider+), so demodulizing yields the useless
+ # "Pricing Provider" — those derive the label from the gem's outer module
+ # instead (+SpreeEasyPost+ → "EasyPost"), matching
+ # {Spree::Integration.api_type}.
+ #
+ # @return [String]
+ def provider_name
+ leaf = name.demodulize
+ outer = name.deconstantize.delete_prefix('Spree')
+
+ return leaf.titleize if outer.blank? || !leaf.end_with?('Provider')
+
+ # Not `titleize` — it would split the gem's own casing
+ # ("SpreeEasyPost" → "Easy Post"). Brands that need more than the
+ # module name override this method.
+ outer.delete_prefix('::')
+ end
+ end
+
+ # The connected, active integration carrying this provider's credentials.
+ # Memoizes the missing case too — an unconnected integration must not cost
+ # a query per call on a hot path.
+ #
+ # @param store [Spree::Store, nil]
+ # @return [Spree::Integration, nil]
+ def integration_for(store)
+ return if self.class.integration_class.blank?
+
+ @integration_for ||= {}
+ return @integration_for[store&.id] if @integration_for.key?(store&.id)
+
+ @integration_for[store&.id] = store&.integrations&.active&.find_by(type: self.class.integration_class)
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/provider_failure_policy.rb b/spree/core/app/models/concerns/spree/provider_failure_policy.rb
new file mode 100644
index 0000000000..f430ae940a
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/provider_failure_policy.rb
@@ -0,0 +1,38 @@
+module Spree
+ # What a store wants to happen when an external pricing or inventory system
+ # cannot be reached.
+ #
+ # The two defaults differ on purpose. Selling an item the warehouse turns out
+ # not to have is recoverable — the merchant contacts the customer. Charging
+ # the wrong price is not: the money moves, and a contract customer billed at
+ # list price is a dispute rather than an apology. So inventory falls back to
+ # the local snapshot and pricing refuses to proceed.
+ module ProviderFailurePolicy
+ # - +fallback+ use Spree's own answer and warn
+ # - +strict+ fail the step and tell the customer to retry
+ VALUES = %w[fallback strict].freeze
+
+ DEFAULT_PRICING_POLICY = 'strict'.freeze
+ DEFAULT_INVENTORY_POLICY = 'fallback'.freeze
+
+ # Records that a provider could not answer and Spree used its own figure
+ # instead. Emitted from one place because the payload keys are public API
+ # (docs/plans/6.0-opentelemetry.md) and must stay PII-safe — an error
+ # message can carry order or customer detail, so only its class is sent.
+ #
+ # @param kind [String] 'pricing' or 'inventory'
+ # @param provider [String, nil] the provider's registry key
+ # @param store [Spree::Store, nil]
+ # @param error [StandardError]
+ # @return [void]
+ def self.report_fallback(kind:, provider:, store:, error:)
+ ActiveSupport::Notifications.instrument(
+ 'provider.fallback.spree',
+ provider: provider,
+ kind: kind,
+ store_id: store&.id,
+ reason: error.class.name
+ )
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/store_data_sources.rb b/spree/core/app/models/concerns/spree/store_data_sources.rb
new file mode 100644
index 0000000000..a6ab566146
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/store_data_sources.rb
@@ -0,0 +1,75 @@
+module Spree
+ # Where a store gets its prices and stock levels from.
+ #
+ # The preference stores the provider's registry **key** rather than a class
+ # name, because the same string is written to
+ # +spree_line_items.price_source+ — an order has to be able to say where its
+ # price came from years later, and a class name is not a stable thing to keep
+ # in a data column.
+ #
+ # An unregistered key resolves to Internal rather than raising: a provider
+ # gem being uninstalled must not take checkout down with it, and the merchant
+ # sees the setting fall back in the admin.
+ module StoreDataSources
+ extend ActiveSupport::Concern
+
+ INTERNAL_KEY = 'internal'.freeze
+
+ included do
+ validates :preferred_pricing_provider_failure_policy,
+ inclusion: { in: Spree::ProviderFailurePolicy::VALUES }
+ validates :preferred_inventory_provider_failure_policy,
+ inclusion: { in: Spree::ProviderFailurePolicy::VALUES }
+ end
+
+ # Deliberately not memoized. A store object outlives a preference change —
+ # a merchant switching provider in the admin, a job holding a store for
+ # hours — and a cached instance would keep answering from the old setting.
+ # Construction is a registry lookup and an argless +new+.
+ #
+ # @return [Spree::PricingProvider::Base]
+ def pricing_provider_instance
+ resolve_provider(
+ Spree.pricing_providers, preferred_pricing_provider, Spree::PricingProvider::Internal
+ ).new
+ end
+
+ # @return [Spree::InventoryProvider::Base]
+ def inventory_provider_instance
+ resolve_provider(
+ Spree.inventory_providers, preferred_inventory_provider, Spree::InventoryProvider::Internal
+ ).new
+ end
+
+ # @return [Boolean] true when prices come from Spree's own catalog
+ def internal_pricing?
+ pricing_provider_instance.is_a?(Spree::PricingProvider::Internal)
+ end
+
+ # @return [Boolean] true when stock levels come from Spree's own records
+ def internal_inventory?
+ inventory_provider_instance.is_a?(Spree::InventoryProvider::Internal)
+ end
+
+ # @return [String] 'fallback' or 'strict'
+ def pricing_failure_policy
+ preferred_pricing_provider_failure_policy.presence ||
+ Spree::ProviderFailurePolicy::DEFAULT_PRICING_POLICY
+ end
+
+ # @return [String] 'fallback' or 'strict'
+ def inventory_failure_policy
+ preferred_inventory_provider_failure_policy.presence ||
+ Spree::ProviderFailurePolicy::DEFAULT_INVENTORY_POLICY
+ end
+
+ private
+
+ def resolve_provider(registry, key, fallback)
+ key = key.to_s
+ return fallback if key.blank? || key == INTERNAL_KEY
+
+ registry.detect { |provider| provider.key == key } || fallback
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index 941d86cbac..90b60fefed 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -225,11 +225,18 @@ module Spree
# recalculation-on-write replacement for transition-triggered rebuilds.
# Called by Carts::Update after address/market changes.
def recalculate_for_address_change!
- # recalculate_price, not update_price: the latter only assigns, and nothing
- # here saves the line items — rebuild_fulfillments! and recalculate_totals!
- # reset the association cache and drop the new figures. Order#update_line_item_prices!
- # gets away with update_price because it follows it with save!.
- line_items.reload.each(&:recalculate_price)
+ # One provider round for the whole cart, and persisted: a per-item loop
+ # would ask an external pricing system once per line, and nothing here
+ # saves the line items — rebuild_fulfillments! and recalculate_totals!
+ # reset the association cache and would drop assigned-but-unsaved
+ # figures.
+ # A strict store would rather refuse than reprice on a figure it cannot
+ # stand behind, so a pricing failure stops the recalculation instead of
+ # carrying on with stale prices and a rebuilt delivery quote around them.
+ result = Spree::Carts::PriceItems.new.call(cart: self, line_items: line_items.reload)
+ raise Spree::Pricing::PriceResolution::ProviderUnavailable, result.error.to_s if result.failure?
+
+ Spree::Carts::PriceItems.apply(result.value)
rebuild_fulfillments!
set_fulfillments_cost
recalculate_totals!
diff --git a/spree/core/app/models/spree/inventory_provider/base.rb b/spree/core/app/models/spree/inventory_provider/base.rb
new file mode 100644
index 0000000000..feac71becd
--- /dev/null
+++ b/spree/core/app/models/spree/inventory_provider/base.rb
@@ -0,0 +1,44 @@
+module Spree
+ module InventoryProvider
+ # Contract for inventory sources — what answers "how many of this variant
+ # exist, and where".
+ #
+ # A provider returns {Spree::StockLevel} rows: {Internal} the persisted
+ # ones, an external provider **unsaved, readonly** instances carrying the
+ # remote system's counts. {Spree::Stock::Quantifier} does the arithmetic
+ # over whatever rows it is handed, so backorder limits, preorders and local
+ # checkout reservations behave the same either way — an external system
+ # does not know about our carts, so those holds must stay local.
+ #
+ # **Only decision points consult a provider.** Add-to-cart, taking a
+ # reservation and completing checkout ask; listings, product pages and
+ # search read the local snapshot the sync feed maintains. A provider on the
+ # read path would mean one remote call per product tile, and would take the
+ # storefront down with the remote system.
+ class Base
+ include Spree::IntegrationBackedProvider
+
+ # @param variant [Spree::Variant]
+ # @param stock_location [Spree::StockLocation, nil] narrows to one location
+ # @return [Enumerable<Spree::StockLevel>]
+ def stock_levels_for(_variant, stock_location: nil)
+ raise NotImplementedError, "#{self.class} must implement #stock_levels_for"
+ end
+
+ # How long an answer may be cached. nil means no caching, which is only
+ # correct for a provider reading the local database.
+ #
+ # @return [ActiveSupport::Duration, Integer, nil]
+ def cache_ttl
+ nil
+ end
+
+ # The key a merchant's store preference stores.
+ #
+ # @return [String]
+ def self.key
+ name.demodulize.underscore
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/inventory_provider/internal.rb b/spree/core/app/models/spree/inventory_provider/internal.rb
new file mode 100644
index 0000000000..24ba1e999a
--- /dev/null
+++ b/spree/core/app/models/spree/inventory_provider/internal.rb
@@ -0,0 +1,22 @@
+module Spree
+ module InventoryProvider
+ # Spree's own stock records. Returns the association untouched so
+ # {Spree::Stock::Quantifier} keeps its loaded-association fast path — a
+ # preloaded variant must not fall back to a query per stock item.
+ #
+ # Location narrowing and active-location filtering stay in the Quantifier,
+ # which already does both; doing them here as well would break that
+ # preload branch for no gain.
+ class Internal < Base
+ # @param variant [Spree::Variant]
+ # @param stock_location [Spree::StockLocation, nil]
+ # @return [Enumerable<Spree::StockLevel>]
+ def stock_levels_for(variant, stock_location: nil)
+ return variant.stock_levels if stock_location.blank?
+ return variant.stock_levels.select { |item| item.stock_location_id == stock_location.id } if variant.association(:stock_levels).loaded?
+
+ variant.stock_levels.where(stock_location: stock_location)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rb
index a7c304e5d5..a592a41713 100644
--- a/spree/core/app/models/spree/line_item.rb
+++ b/spree/core/app/models/spree/line_item.rb
@@ -34,6 +34,13 @@ module Spree
has_many :digital_links, dependent: :destroy
has_many :stock_reservations, class_name: 'Spree::StockReservation', inverse_of: :line_item, dependent: :destroy
+ # Set by Spree::Carts::PriceItems when a workflow has already resolved
+ # this line's price outside the transaction. The quantity-change callback
+ # then stands down rather than asking the provider a second time from
+ # inside the save — which is the network-call-in-transaction the workflow
+ # split exists to prevent, and would overwrite the fresher answer.
+ attr_accessor :price_resolved
+
before_validation :copy_price
before_validation :copy_tax_category
before_validation :copy_seller
@@ -127,26 +134,51 @@ module Spree
def copy_price
if variant
- update_price if price.nil?
+ # Local catalog only: this runs inside a save, and the workflows have
+ # already priced the line through the provider before the transaction
+ # opened. Reaching a provider from a validation callback would put a
+ # network call inside every line-item save.
+ copy_catalog_price if price.nil?
self.cost_price = variant.cost_price if cost_price.nil?
self.currency = owner.currency if currency.nil? && owner
end
end
+ # Assigns the current price without saving — the caller is expected to.
+ # {#recalculate_price} persists instead.
+ #
+ # Restatement for a tax-inclusive market happens inside
+ # {Spree::Carts::PriceItems}: an address-less cart still has a taxing
+ # country (its market's own), and without it a cross-border cart is taxed
+ # for the destination at a price quoted for home, leaving the merchant to
+ # absorb the difference.
def update_price
+ return if owner.blank?
+
+ result = Spree::Carts::PriceItems.new.call(cart: owner, line_items: [self])
+ # persist: false — this runs mid-build and from callers that save the
+ # record themselves.
+ Spree::Carts::PriceItems.apply(result.value, persist: false) if result.success?
+ end
+
+ # Assigns the price the local catalog gives for this line, with no pricing
+ # provider consulted — the fallback for a line built outside a workflow
+ # (seeds, console, an extension) that would otherwise be saved with no
+ # price at all. Assigns without saving; the caller is mid-save.
+ #
+ # @return [void]
+ def copy_catalog_price
context = Spree::Pricing::Context.from_order(variant, owner, quantity: quantity)
- currency_price = variant.price_for(context)
-
- # country:, not just address: — an address-less cart still has a taxing
- # country (the market's own), and the provider already estimates against it.
- # Without it a cross-border cart is taxed for the destination at a price
- # quoted for home, and the merchant silently absorbs the rate difference.
- if currency_price.present?
- self.price = currency_price.price_including_vat_for(
- address: owner&.tax_address, country: owner&.tax_country, market: owner&.market
- )
- end
- self.price_list_id = currency_price.price_list_id if currency_price.present?
+ price_record = Spree::PricingProvider::Internal.new.price_for(context)
+ return if price_record.blank?
+
+ amount = price_record.price_including_vat_for(
+ address: owner&.tax_address, country: owner&.tax_country, market: owner&.market
+ )
+ return if amount.blank?
+
+ self.price = amount
+ self.price_list_id = price_record.price_list_id
end
def copy_tax_category
@@ -341,27 +373,20 @@ module Spree
variant.with_digital_assets?
end
- # Recalculates and persists the price based on the current quantity and pricing context
- # This is used for volume-based pricing and other price list rules
+ # Recalculates and persists the price based on the current quantity and
+ # pricing context — volume breaks, price list rules, contract pricing.
+ #
+ # A thin delegate to {Spree::Carts::PriceItems}, which is where a store's
+ # pricing provider is consulted. Prefer calling that service directly for
+ # anything touching more than one line: it asks the provider once for the
+ # batch, while this asks once per item.
+ #
# @return [void]
def recalculate_price
- context = Spree::Pricing::Context.from_order(variant, owner, quantity: quantity)
- currency_price = variant.price_for(context)
+ return if owner.blank?
- return unless currency_price.present?
-
- new_price = currency_price.price_including_vat_for(
- address: owner&.tax_address, country: owner&.tax_country, market: owner&.market
- )
-
- return unless new_price.present?
-
- new_price_list_id = currency_price.price_list_id
-
- # Only update if price or price list changed
- if new_price != price || new_price_list_id != price_list_id
- update_columns(price: new_price, price_list_id: new_price_list_id, updated_at: Time.current)
- end
+ result = Spree::Carts::PriceItems.new.call(cart: owner, line_items: [self])
+ Spree::Carts::PriceItems.apply(result.value) if result.success?
end
private
@@ -409,8 +434,14 @@ module Spree
# recalculation, which every cart/checkout flow runs after the save —
# recalculating from here would cache the owner's associations
# mid-mutation and hide later changes from that run.
+ # One-shot: the mark covers the save that is happening now, not the
+ # instance forever, or a later quantity change on the same object would
+ # never re-price.
+ already_priced = price_resolved
+ self.price_resolved = false
+
if saved_change_to_quantity? && owner&.persisted? && !owner.completed?
- recalculate_price if should_update_price? && !previously_new_record?
+ recalculate_price if should_update_price? && !previously_new_record? && !already_priced
end
end
diff --git a/spree/core/app/models/spree/price.rb b/spree/core/app/models/spree/price.rb
index 19158f79ce..67f50d905e 100644
--- a/spree/core/app/models/spree/price.rb
+++ b/spree/core/app/models/spree/price.rb
@@ -1,5 +1,12 @@
module Spree
class Price < Spree.base_class
+ # Which engine produced this answer — nil for Spree's own catalog, a
+ # provider's registry key otherwise. Transient: set by
+ # Spree::Pricing::PriceResolution on the way out and copied onto the line
+ # item as price_source. Not a column, because a catalog row is the same
+ # row whoever asked for it.
+ attr_accessor :price_source
+
has_prefix_id :price
include Spree::VatPriceCalculation
diff --git a/spree/core/app/models/spree/pricing_provider/base.rb b/spree/core/app/models/spree/pricing_provider/base.rb
new file mode 100644
index 0000000000..6562589695
--- /dev/null
+++ b/spree/core/app/models/spree/pricing_provider/base.rb
@@ -0,0 +1,59 @@
+module Spree
+ module PricingProvider
+ # Contract for pricing engines — what answers "what does this variant cost
+ # for this shopper, right now".
+ #
+ # A provider returns a {Spree::Price}: {Internal} returns the persisted
+ # catalog row, an external provider an **unsaved, readonly** instance. The
+ # Active Record shape is deliberately the contract, so everything
+ # downstream — tax-inclusive restatement, +discounted?+, the serializers —
+ # keeps working without knowing where the number came from. +readonly!+ is
+ # what stops an external answer being written back into the catalog.
+ #
+ # Providers are stateless and constructed without arguments; everything
+ # request-specific arrives in the {Spree::Pricing::Context}.
+ #
+ # **This runs on the catalog read path.** The Store API serializers price
+ # every row of every listing, so a provider that calls out to a remote
+ # system must declare a +cache_ttl+ and use +handles?+ to send traffic it
+ # has no special answer for straight to the internal resolver. A provider
+ # that does neither will make an ERP call per product tile.
+ class Base
+ include Spree::IntegrationBackedProvider
+
+ # @param context [Spree::Pricing::Context]
+ # @return [Spree::Price, nil] nil when this provider has no price
+ def price_for(_context)
+ raise NotImplementedError, "#{self.class} must implement #price_for"
+ end
+
+ # Whether this provider wants to answer for this context at all. Return
+ # false and the internal resolver answers instead — the escape hatch that
+ # keeps anonymous catalog browsing off a contract-pricing system.
+ #
+ # @param context [Spree::Pricing::Context]
+ # @return [Boolean]
+ def handles?(_context)
+ true
+ end
+
+ # How long an answer may be cached, keyed by the context. nil means no
+ # caching, which is only correct for a provider reading the local
+ # database.
+ #
+ # @return [ActiveSupport::Duration, Integer, nil]
+ def cache_ttl
+ nil
+ end
+
+ # The key a merchant's store preference stores, and the value written to
+ # +spree_line_items.price_source+ so an order can say where its price
+ # came from.
+ #
+ # @return [String]
+ def self.key
+ name.demodulize.underscore
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rb
new file mode 100644
index 0000000000..58043135f7
--- /dev/null
+++ b/spree/core/app/models/spree/pricing_provider/internal.rb
@@ -0,0 +1,148 @@
+module Spree
+ module PricingProvider
+ # Spree's own pricing: price lists and their rules, falling back to the
+ # variant's base price. What every store uses until it connects something
+ # else.
+ #
+ # The resolution lives here rather than in a separate Pricing::Resolver —
+ # it is this provider's implementation, not a seam of its own, and having
+ # two entry points invited callers to reach past the provider contract.
+ # {Spree::Pricing::Context} stays where it is: it is the question every
+ # provider is asked, not part of any one answer.
+ class Internal < Base
+ # @param context [Spree::Pricing::Context]
+ # @return [Spree::Price, nil]
+ def price_for(context)
+ Resolution.new(context).resolve
+ end
+
+ # The price-list walk itself. A separate object because it memoizes per
+ # context (+applicable_price_lists+), while a provider instance is
+ # stateless and reused across calls — keeping that state here means a
+ # cached provider can never serve one shopper the lists resolved for
+ # another.
+ class Resolution
+ attr_reader :context
+
+ # Initializes the resolver
+ # @param context [Spree::Pricing::Context]
+ def initialize(context)
+ @context = context
+ end
+
+ # Returns the best price for the variant
+ # @return [Spree::Price]
+ def resolve
+ find_best_price
+ end
+
+ private
+
+ # Returns the best price for the variant
+ # @return [Spree::Price]
+ def find_best_price
+ # Try to find a price from applicable price lists first
+ price_from_list = find_price_from_lists
+ return price_from_list if price_from_list
+
+ # Fall back to base price (no price_list_id)
+ find_base_price
+ end
+
+ # Returns the price from applicable price lists
+ # @return [Spree::Price]
+ def find_price_from_lists
+ applicable_price_lists.each do |price_list|
+ price = find_price_for_list(price_list)
+ return price if price
+ end
+
+ nil
+ end
+
+ # Returns the price lists that are applicable to the context
+ # @return [Array<Spree::PriceList>]
+ def applicable_price_lists
+ @applicable_price_lists ||= price_lists_for_context.select { |list| list.applicable?(context) }
+ end
+
+ # Returns the price lists for the context's store
+ # Uses Spree::Current.price_lists if the context matches, otherwise fetches directly
+ # @return [ActiveRecord::Relation<Spree::PriceList>]
+ def price_lists_for_context
+ if context.store == Spree::Current.store && context.currency == Spree::Current.currency
+ Spree::Current.price_lists
+ else
+ Spree::PriceList.for_context(context)
+ end
+ end
+
+ # Returns the price for a given price list
+ # @param price_list [Spree::PriceList]
+ # @return [Spree::Price]
+ def find_price_for_list(price_list)
+ currency = context.currency&.upcase
+
+ # Zero is a valid override (free for this list); only nil placeholder
+ # rows (materialized by PriceList#add_products) are skipped.
+ if prices.loaded?
+ prices.detect do |p|
+ p.currency == currency &&
+ p.price_list_id == price_list.id &&
+ !p.amount.nil?
+ end
+ else
+ context.variant.prices
+ .with_currency(currency)
+ .where(price_list_id: price_list.id)
+ .where.not(amount: nil)
+ .first
+ end
+ end
+
+ # Returns the base price for the variant in the current currency
+ # @return [Spree::Price]
+ def find_base_price
+ currency = context.currency&.upcase
+
+ price = if prices.loaded?
+ prices.detect do |p|
+ p.currency == currency &&
+ p.price_list_id.nil? &&
+ p.amount.present?
+ end
+ else
+ context.variant.prices
+ .with_currency(currency)
+ .where(price_list_id: nil)
+ .where.not(amount: nil)
+ .first
+ end
+
+ price || build_empty_price
+ end
+
+ # Returns the prices for the variant
+ # @return [ActiveRecord::Relation<Spree::Price>]
+ def prices
+ context.variant.prices
+ end
+
+ # Returns an empty price placeholder for the variant.
+ # Uses Price.new instead of prices.build to avoid polluting the association
+ # with an unsaved record that would fail validation on variant save.
+ # @return [Spree::Price]
+ def build_empty_price
+ Spree::Price.new(
+ variant_id: context.variant.id,
+ # Upcased like every lookup above, so the placeholder's currency
+ # cannot differ in casing from the prices it stood in for.
+ currency: context.currency&.upcase,
+ amount: nil,
+ price_list_id: nil
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/stock/quantifier.rb b/spree/core/app/models/spree/stock/quantifier.rb
index 789b79ebc9..565f4d4b65 100644
--- a/spree/core/app/models/spree/stock/quantifier.rb
+++ b/spree/core/app/models/spree/stock/quantifier.rb
@@ -1,17 +1,21 @@
module Spree
module Stock
class Quantifier
- attr_reader :variant, :stock_location, :excluded_order
+ attr_reader :variant, :stock_location, :excluded_order, :provided_stock_levels
# @param excluded_order [Spree::Cart, Spree::Order, nil] when given,
# reservations belonging to this cart/order are not counted against
# availability. Used when checking a cart's own line items so the
# customer's own checkout hold doesn't make their item look out of
# stock.
- def initialize(variant, stock_location = nil, excluded_order: nil)
+ # @param stock_levels [Enumerable<Spree::StockLevel>, nil] rows to count
+ # instead of the variant's own. Passed by the inventory provider when
+ # stock lives in an external system; the rows may be unsaved.
+ def initialize(variant, stock_location = nil, excluded_order: nil, stock_levels: nil)
@variant = variant
@stock_location = stock_location
@excluded_order = excluded_order
+ @provided_stock_levels = stock_levels
end
# Units a customer can purchase right now: physical pool minus
@@ -72,7 +76,7 @@ module Spree
reservations.sum(&:quantity)
end
else
- reservations = Spree::StockReservation.active.where(stock_level_id: stock_levels.map(&:id))
+ reservations = Spree::StockReservation.active.where(stock_level_id: persisted_stock_level_ids)
reservations = reservations.where.not(excluded_owner_key => excluded_owner_id) if excluded_owner_id
reservations.sum(:quantity)
end
@@ -108,7 +112,24 @@ module Spree
end
def stock_levels
- @stock_levels ||= scope_to_location(variant.stock_levels)
+ @stock_levels ||= scope_to_location(provided_stock_levels || variant.stock_levels)
+ end
+
+ # Reservations hang off Spree's own rows, so an external provider's
+ # unsaved rows carry no id to match on. Resolve them by (variant,
+ # location) instead: a checkout hold is Spree's to honour whoever owns
+ # the stock figure, and matching on a nil id would silently subtract
+ # nothing and oversell the hold.
+ #
+ # @return [Array<Integer>]
+ def persisted_stock_level_ids
+ ids = stock_levels.map(&:id).compact
+ return ids if ids.length == stock_levels.size
+
+ locations = stock_levels.map(&:stock_location_id).compact
+ return ids if locations.empty?
+
+ ids | Spree::StockLevel.where(variant_id: variant.id, stock_location_id: locations).ids
end
private
@@ -121,13 +142,25 @@ module Spree
Spree::StorePreferences.read(store, :stock_reservations_enabled)
end
+ # Whether the rows being counted are already in memory. Injected provider
+ # rows always are — they are a plain Array with no association to ask, and
+ # an empty one is a complete answer (the variant is unknown to that
+ # system), not a signal to fall back to the local records.
def association_loaded?
+ return true unless provided_stock_levels.nil?
+
variant.association(:stock_levels).loaded?
end
+ # association_loaded? first: it is a memory check, while stock_levels
+ # loads the relation. An external provider's rows are new records whose
+ # reservation association reads as empty rather than unloaded, which
+ # would count every local hold as zero — force those down the query path.
def reservations_preloaded?
- association_loaded? &&
- stock_levels.all? { |si| si.association(:active_stock_reservations).loaded? }
+ return false unless association_loaded?
+ return false if stock_levels.any?(&:new_record?)
+
+ stock_levels.all? { |si| si.association(:active_stock_reservations).loaded? }
end
def scope_to_location(collection)
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 5354ca6181..58753b1fdf 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -13,6 +13,7 @@ module Spree
include Spree::Stores::Setup
include Spree::Stores::Markets
include Spree::Stores::Channels
+ include Spree::StoreDataSources
include Spree::Security::Stores if defined?(Spree::Security::Stores)
include Spree::UserManagement
include Spree::OrderRouting::HasStrategyPreference
@@ -91,6 +92,15 @@ module Spree
# follows the destination keep this on; billing-address jurisdictions turn
# it off.
preference :tax_using_ship_address, :boolean, default: true
+ # Where prices and stock levels come from. 'internal' is Spree's own
+ # catalog and stock records; a connector gem registers others.
+ preference :pricing_provider, :string, default: 'internal'
+ preference :inventory_provider, :string, default: 'internal'
+ # What happens when an external source cannot be reached.
+ preference :pricing_provider_failure_policy, :string,
+ default: Spree::ProviderFailurePolicy::DEFAULT_PRICING_POLICY
+ preference :inventory_provider_failure_policy, :string,
+ default: Spree::ProviderFailurePolicy::DEFAULT_INVENTORY_POLICY
# Catalog preferences
preference :track_inventory_levels, :boolean, default: true
preference :show_products_without_price, :boolean, default: false
@@ -237,6 +247,7 @@ module Spree
has_many :customer_groups, class_name: 'Spree::CustomerGroup', dependent: :destroy, inverse_of: :store
has_many :companies, class_name: 'Spree::Company', dependent: :destroy, inverse_of: :store
+ has_many :external_references, class_name: 'Spree::ExternalReference', dependent: :destroy, inverse_of: :store
has_many :api_keys, class_name: 'Spree::ApiKey', dependent: :destroy
has_many :allowed_origins, class_name: 'Spree::AllowedOrigin', dependent: :destroy
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index f46d13fdda..b38a6f37c9 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -8,6 +8,7 @@ module Spree
include Spree::MemoizedData
include Spree::HasCustomFields
include Spree::Metadata
+ include Spree::HasExternalReferences
include Spree::Searchable
include Spree::StorePreferences
@@ -705,7 +706,8 @@ module Spree
def set_price(currency, amount, compare_at_amount = nil)
# When the prices association is already loaded (eager-loaded for
# serialization), reuse the cached base-price instance so readers that
- # branch on `prices.loaded?` (Pricing::Resolver, #price_in, serializers)
+ # branch on `prices.loaded?` (the Internal provider's resolution,
+ # #price_in, serializers)
# observe the write without a reload. `base_prices.find_or_initialize_by`
# would issue a fresh query and return a detached object, leaving the
# loaded collection — and the serialized response — stale.
@@ -740,8 +742,13 @@ module Spree
end
# Returns the price for the given context or options.
+ #
+ # Answered by the store's pricing provider, which is Spree's own resolver
+ # unless a connector has been configured. An external provider's price is
+ # an unsaved, readonly Spree::Price — see Spree::PricingProvider::Base.
+ #
# @param context_or_options [Spree::Pricing::Context|Hash] the context or options to get the price for
- # @return [Spree::Price] the price for the given context or options
+ # @return [Spree::Price, nil] the price for the given context or options
def price_for(context_or_options)
context = if context_or_options.is_a?(Spree::Pricing::Context)
context_or_options
@@ -751,7 +758,7 @@ module Spree
raise ArgumentError, 'Must provide a Pricing::Context or options hash'
end
- Spree::Pricing::Resolver.new(context).resolve
+ Spree::Pricing::PriceResolution.call(context)
end
# Sets the count at a location. The correction goes through an `adjusted`
diff --git a/spree/core/app/services/spree/carts/check_availability.rb b/spree/core/app/services/spree/carts/check_availability.rb
new file mode 100644
index 0000000000..861df8f865
--- /dev/null
+++ b/spree/core/app/services/spree/carts/check_availability.rb
@@ -0,0 +1,71 @@
+module Spree
+ module Carts
+ # Asks the store's inventory source whether these items can actually be
+ # supplied.
+ #
+ # Runs outside any transaction, as an +external_step+: the provider may be
+ # an external warehouse system, and holding a transaction open across that
+ # call is what turns a slow warehouse into stuck locks.
+ #
+ # The provider only supplies the *rows*; {Spree::Stock::Quantifier} still
+ # does the arithmetic over them, so backorder limits, preorders and local
+ # checkout holds behave identically whoever owns the stock figure.
+ class CheckAvailability
+ prepend ::Spree::ServiceModule::Base
+
+ # @param cart [Spree::Cart, Spree::Order]
+ # @param items [Array<Hash>] +[{ variant:, quantity: }]+ to check
+ # @return [Spree::ServiceModule::Result] value is an array of
+ # +[variant, requested_quantity]+ pairs that cannot be supplied
+ def call(cart:, items:)
+ entries = Array(items).filter_map do |item|
+ item = item.to_h.symbolize_keys
+ variant = item[:variant]
+ next if variant.blank?
+
+ [variant, item[:quantity].to_i]
+ end
+ return success([]) if entries.empty?
+
+ provider = cart&.store&.inventory_provider_instance
+ return success([]) if provider.blank?
+
+ internal = provider.is_a?(Spree::InventoryProvider::Internal)
+
+ unsupplyable = entries.reject do |variant, quantity|
+ supplyable?(variant, quantity, cart: cart, provider: provider, internal: internal)
+ end
+
+ success(unsupplyable)
+ rescue StandardError => e
+ handle_failure(e, cart: cart)
+ end
+
+ private
+
+ def supplyable?(variant, quantity, cart:, provider:, internal:)
+ stock_levels = internal ? nil : provider.stock_levels_for(variant)
+
+ Spree::Stock::Quantifier.new(variant, excluded_order: cart, stock_levels: stock_levels).
+ can_supply?(quantity)
+ end
+
+ def handle_failure(error, cart:)
+ raise error if error.is_a?(Spree::ServiceModule::ResultError)
+
+ store = cart&.store
+ Spree::ProviderFailurePolicy.report_fallback(
+ kind: 'inventory', provider: store&.inventory_provider_instance&.class&.key,
+ store: store, error: error
+ )
+
+ # Strict stores would rather refuse than sell on a figure they cannot
+ # confirm; the default is to trust the local snapshot, since an
+ # oversell is recoverable and a blocked checkout is not.
+ return failure(cart, error.message) if store&.inventory_failure_policy == 'strict'
+
+ success([])
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/carts/price_items.rb b/spree/core/app/services/spree/carts/price_items.rb
new file mode 100644
index 0000000000..d407d70696
--- /dev/null
+++ b/spree/core/app/services/spree/carts/price_items.rb
@@ -0,0 +1,89 @@
+module Spree
+ module Carts
+ # Resolves what each line item should cost, through the store's pricing
+ # provider.
+ #
+ # Split deliberately into two calls. {#call} only *asks* — it may reach an
+ # external system, so it runs outside any transaction, as an
+ # +external_step+. {.apply} then writes what was resolved, inside the
+ # caller's transaction. Holding a database transaction open across a
+ # network call is what turns a slow ERP into a table full of stuck locks.
+ #
+ # A line item on a completed order is never re-priced: the price it was
+ # sold at is a fact about that sale, not a question to ask again.
+ class PriceItems
+ prepend ::Spree::ServiceModule::Base
+
+ # @param cart [Spree::Cart, Spree::Order]
+ # @param line_items [Enumerable<Spree::LineItem>, nil] defaults to all of them
+ # @return [Spree::ServiceModule::Result] value is an array of
+ # +[line_item, price, price_source]+ triples for {.apply}
+ def call(cart:, line_items: nil)
+ return success([]) if cart.blank?
+
+ items = Array(line_items.presence || cart.line_items)
+ # A placed order's existing lines are frozen — what they sold at is a
+ # fact. A line being added to it now still needs a price, or an admin
+ # amendment bills list price to a contract customer.
+ items = items.reject(&:persisted?) if money_frozen?(cart)
+ return success([]) if items.empty?
+
+ # The source comes from the answer, not the store's setting: a
+ # provider that declined the context, or fell back, priced from the
+ # catalog and the line must say so.
+ resolutions = items.filter_map do |line_item|
+ price = resolve_price(line_item, cart)
+ next if price.blank?
+
+ [line_item, price, price.price_source]
+ end
+
+ success(resolutions)
+ rescue Spree::Pricing::PriceResolution::ProviderUnavailable => e
+ # Strict policy: the store would rather sell nothing than sell at a
+ # price it cannot stand behind.
+ failure(cart, e.message)
+ end
+
+ # Writes resolved prices. Safe inside a transaction — no provider is
+ # consulted here.
+ #
+ # @param resolutions [Array<Array>] triples from {#call}
+ # @param persist [Boolean] false assigns without saving, for callers
+ # that save the record themselves
+ # @return [void]
+ def self.apply(resolutions, persist: true)
+ Array(resolutions).each do |line_item, price, source|
+ owner = line_item.owner
+ amount = price.price_including_vat_for(
+ address: owner&.tax_address, country: owner&.tax_country, market: owner&.market
+ )
+ next if amount.blank?
+
+ line_item.assign_attributes(price: amount, price_list_id: price.price_list_id, price_source: source)
+ # Only the assign-for-a-coming-save case marks the line: the caller
+ # is about to save it, and that save must not re-price. A persisted
+ # write goes through update_columns and fires no callbacks.
+ line_item.price_resolved = true unless persist
+ next unless persist && line_item.persisted? && line_item.changed?
+
+ line_item.update_columns(line_item.changes.transform_values(&:last).merge(updated_at: Time.current))
+ end
+ end
+
+ private
+
+ # The same rule Carts::RecalculateTotals uses: once an order is placed
+ # its money stops being a question. Re-pricing here would rewrite what a
+ # customer was actually charged.
+ def money_frozen?(cart)
+ cart.is_a?(Spree::Order) && cart.completed?
+ end
+
+ def resolve_price(line_item, cart)
+ context = Spree::Pricing::Context.from_order(line_item.variant, cart, quantity: line_item.quantity)
+ line_item.variant.price_for(context)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/carts/update.rb b/spree/core/app/services/spree/carts/update.rb
index df1feb20c5..5ff499ff04 100644
--- a/spree/core/app/services/spree/carts/update.rb
+++ b/spree/core/app/services/spree/carts/update.rb
@@ -25,6 +25,27 @@ module Spree
success(cart)
rescue ActiveRecord::RecordNotFound
raise
+ rescue Spree::Pricing::PriceResolution::ProviderUnavailable => e
+ # A strict store could not confirm a price. The transaction has rolled
+ # back, so the address change is not committed either — better than
+ # saving a destination whose prices nobody stood behind.
+ #
+ # The in-memory cart still holds the rolled-back attributes, though, so
+ # a caller that renders the object it passed in would show the customer
+ # an address the database never accepted. Reload it to match what was
+ # actually kept, carrying the transient warnings across as try_advance
+ # does.
+ Rails.error.report(e, context: { order_id: cart.id }, source: 'spree.checkout')
+
+ warnings = cart.warnings
+ begin
+ cart.reload
+ rescue StandardError # rubocop:disable Lint/SuppressedException
+ # a reload failure must not mask the pricing failure being reported
+ end
+ cart.warnings |= warnings if warnings.present?
+
+ failure(cart, Spree.t('cart_line_item.pricing_unavailable'))
rescue ActiveRecord::RecordInvalid => e
failure(cart, e.record.errors.full_messages.to_sentence)
rescue StandardError => e
@@ -182,6 +203,11 @@ module Spree
else
cart.recalculate_totals!
end
+ rescue Spree::Pricing::PriceResolution::ProviderUnavailable
+ # Deliberately not swallowed like the rest: a strict store refusing to
+ # price must roll the whole update back, so `call` sees it and the
+ # address change does not commit around unconfirmed prices.
+ raise
rescue StandardError => e
Rails.error.report(e, context: { order_id: cart.id }, source: 'spree.checkout')
ensure
diff --git a/spree/core/app/workflows/spree/carts/add_item.rb b/spree/core/app/workflows/spree/carts/add_item.rb
index b9ca406c70..ca1a81fe27 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 Spree
# rejection costs no rollback.
run_hooks :validate
+ # Both providers are consulted before the transaction opens: they may
+ # be external systems, and a database transaction held open across a
+ # network call is how a slow warehouse becomes a table of stuck locks.
+ external_step :check_availability
+ external_step :resolve_price
+
ApplicationRecord.transaction do
step :add_to_line_item
step :handle_stock_reservations if cart.in_checkout?
@@ -42,9 +48,16 @@ module Spree
item_options = options || {}
requested_quantity = quantity || 1
- failure(variant, "#{variant.name} is not available in #{cart.currency}") if variant.amount_in(cart.currency).nil?
+ # A provider that quoted a real amount is proof the currency is
+ # sellable, even when the local catalog holds no price for it — an
+ # external system can be the only source for a currency. The internal
+ # resolver returns a placeholder with a nil amount when it has none,
+ # which is not a quote.
+ if resolved_amount.nil? && variant.amount_in(cart.currency).nil?
+ failure(variant, "#{variant.name} is not available in #{cart.currency}")
+ end
- @line_item = Spree.line_item_by_variant_finder.new.execute(cart: cart, variant: variant, options: item_options)
+ @line_item = existing_line_item
@line_item_created = @line_item.nil?
if @line_item.nil?
@@ -72,9 +85,12 @@ module Spree
@line_item.metadata = metadata.to_h if metadata.present?
+ # Before the save, so the resolved price rides the same write and the
+ # quantity-change callback sees the line as already priced.
+ apply_resolved_price
failure(@line_item) unless @line_item.save
- @line_item.reload.recalculate_price
+ @line_item.reload
return unless @line_item_created
@@ -82,6 +98,76 @@ module Spree
owner.tax_provider.estimate(owner, [@line_item], **owner.tax_estimate_inputs)
end
+ # Only external inventory needs asking here — Spree's own stock records
+ # are already checked by the line item's availability validator on save,
+ # and duplicating that would mean two answers that can disagree.
+ def check_availability
+ return if cart.store.nil? || cart.store.internal_inventory?
+
+ result = Spree::Carts::CheckAvailability.call(
+ cart: cart, items: [{ variant: variant, quantity: resulting_quantity }]
+ )
+ failure(variant, result.error) if result.failure?
+
+ return if result.value.blank?
+
+ failure(variant, Spree.t(:selected_quantity_not_available, item: variant.name.inspect))
+ end
+
+ # Asked before the item exists, so the context carries the quantity the
+ # line will end up at — a volume price must reflect the whole line, not
+ # the increment.
+ def resolve_price
+ result = Spree::Carts::PriceItems.new.call(cart: cart, line_items: [pricing_probe_line_item])
+ failure(variant, result.error) if result.failure?
+
+ @resolved_price = result.value.first
+ end
+
+ # The provider is asked about a line item that does not exist yet, so the
+ # answer arrives against a stand-in and is transferred onto the real row
+ # once it does.
+ #
+ # Built detached rather than through +cart.line_items.new+: that appends
+ # the stand-in to the association, and the line-item finder would then
+ # find it and add the new quantity to a row that was never meant to
+ # exist.
+ def pricing_probe_line_item
+ Spree::LineItem.new(variant: variant, quantity: resulting_quantity,
+ currency: cart.currency).tap do |probe|
+ probe.association(:cart).target = cart if probe.respond_to?(:cart)
+ end
+ end
+
+ # The amount the pricing step actually resolved, or nil when nothing
+ # priced this line.
+ def resolved_amount
+ @resolved_price&.at(1)&.amount
+ end
+
+ def apply_resolved_price
+ return if @resolved_price.blank?
+
+ _probe, price, source = @resolved_price
+ Spree::Carts::PriceItems.apply([[@line_item, price, source]], persist: false)
+ end
+
+ # What the line will hold once this add is applied. Volume pricing and
+ # the availability check both care about the whole line, not the
+ # increment. +to_i+ because quantity arrives off a request as a string.
+ def resulting_quantity
+ existing_line_item&.quantity.to_i + (quantity.presence || 1).to_i
+ end
+
+ # Memoized because the price and availability steps ask for it before
+ # the transaction, and +add_to_line_item+ needs the same row inside it.
+ def existing_line_item
+ return @existing_line_item if defined?(@existing_line_item)
+
+ @existing_line_item = Spree.line_item_by_variant_finder.new.
+ execute(cart: cart, variant: variant, options: options || {})
+ end
+
def handle_stock_reservations
result = Spree::StockReservations::Reserve.call(cart: cart)
failure(line_item, result.error) if result.failure?
diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rb
index e8b0bac0b8..36050ad404 100644
--- a/spree/core/app/workflows/spree/carts/complete.rb
+++ b/spree/core/app/workflows/spree/carts/complete.rb
@@ -40,6 +40,11 @@ module Spree
# P1 — replay: a double-clicked Place Order must get the order back.
step :replay_completed
+ # Last chance to catch a contract price that moved while the customer
+ # was in checkout. Outside the lock, since an external provider is a
+ # network call and the lock is held across the whole placement.
+ external_step :confirm_prices
+
cart.with_lock do
step :guard_concurrent_completion
step :recalculate_in_lock
@@ -110,7 +115,21 @@ module Spree
# In-lock recalculation — the totals about to be charged are computed
# here, not trusted from earlier requests.
+ # Only external pricing is re-confirmed: Spree's own catalog is read
+ # inside the lock by the recalculation anyway, so asking twice would buy
+ # nothing.
+ def confirm_prices
+ return if cart.store.nil? || cart.store.internal_pricing?
+ return if cart.is_a?(Spree::Order) && cart.completed?
+
+ result = Spree::Carts::PriceItems.new.call(cart: cart)
+ failure(cart, code: 'provider_unavailable', message: result.error.to_s) if result.failure?
+
+ @confirmed_prices = result.value
+ end
+
def recalculate_in_lock
+ Spree::Carts::PriceItems.apply(@confirmed_prices) if @confirmed_prices.present?
cart.recalculate_totals!
end
diff --git a/spree/core/app/workflows/spree/carts/upsert_items.rb b/spree/core/app/workflows/spree/carts/upsert_items.rb
index fa25ddea87..7275f84cc7 100644
--- a/spree/core/app/workflows/spree/carts/upsert_items.rb
+++ b/spree/core/app/workflows/spree/carts/upsert_items.rb
@@ -37,6 +37,12 @@ module Spree
step :resolve_items
return success(cart) if resolved_items.empty?
+ # Before the transaction: both may be external systems, and a database
+ # transaction held open across a network call is how a slow warehouse
+ # becomes a table of stuck locks.
+ external_step :check_availability
+ external_step :resolve_prices
+
ApplicationRecord.transaction do
step :apply_items
step :handle_stock_reservations if cart.in_checkout?
@@ -93,6 +99,61 @@ module Spree
end
end
+ # Only external inventory is asked here: Spree's own records are already
+ # checked by the line item's availability validator on save, and two
+ # answers that can disagree is worse than one.
+ def check_availability
+ return if cart.store.nil? || cart.store.internal_inventory?
+
+ return if additions.empty?
+
+ result = Spree::Carts::CheckAvailability.call(
+ cart: cart, items: additions.map { |item| { variant: item.variant, quantity: item.quantity } }
+ )
+ failure(cart, result.error) if result.failure?
+
+ @unsupplyable_variant_ids = Array(result.value).map { |variant, _quantity| variant.id }.to_set
+ end
+
+ # One provider round per batch rather than one per line: a fifty-line
+ # cart restore must not become fifty calls to an ERP.
+ def resolve_prices
+ return if additions.empty?
+
+ # Detached, not cart.line_items.new: that appends the stand-in to the
+ # association, and the line-item finder would then find it and treat a
+ # row that was never meant to exist as the one to update.
+ probes = additions.map do |item|
+ Spree::LineItem.new(variant: item.variant, quantity: item.quantity, currency: cart.currency)
+ end
+
+ result = Spree::Carts::PriceItems.new.call(cart: cart, line_items: probes)
+ failure(cart, result.error) if result.failure?
+
+ @resolved_prices = Array(result.value).index_by { |probe, _price, _source| probe.variant_id }
+ end
+
+ def additions
+ @additions ||= resolved_items.reject(&:remove?)
+ end
+
+ def apply_resolved_price(line_item)
+ resolution = resolved_prices[line_item.variant_id]
+ return if resolution.blank?
+
+ _probe, price, source = resolution
+ Spree::Carts::PriceItems.apply([[line_item, price, source]], persist: false)
+ end
+
+ def resolved_prices
+ @resolved_prices ||= {}
+ end
+
+ def unsupplyable?(item)
+ @unsupplyable_variant_ids ||= Set.new
+ @unsupplyable_variant_ids.include?(item.variant.id)
+ end
+
def apply_items
resolved_items.each_with_index do |item, index|
next unless validated?(item, index)
@@ -104,7 +165,10 @@ module Spree
next
end
- if item.variant.amount_in(cart.currency).nil?
+ # A provider that already quoted this line is proof the currency is
+ # sellable, even when the local catalog holds no price for it — an
+ # external system can be the only source for a currency.
+ if resolved_prices[item.variant.id]&.at(1)&.amount.nil? && item.variant.amount_in(cart.currency).nil?
message = Spree.t('cart_line_item.currency_unavailable', li_name: item.variant.name, currency: cart.currency)
failure(item.variant, message) unless partial_success?
@@ -112,6 +176,14 @@ module Spree
next
end
+ if unsupplyable?(item)
+ message = Spree.t(:selected_quantity_not_available, item: item.variant.name.inspect)
+ failure(item.variant, message) unless partial_success?
+
+ warn(index, item, :selected_quantity_not_available, message)
+ next
+ end
+
apply_item(item, line_item, index)
end
end
@@ -160,6 +232,9 @@ module Spree
end
created = line_item.new_record?
+ # Before the save, so the resolved price rides the same write and the
+ # quantity-change callback sees the line as already priced.
+ apply_resolved_price(line_item)
# A line that won't save — most often the stock availability
# validator — is this item's problem, not the batch's. Failing here
@@ -173,7 +248,7 @@ module Spree
return
end
- line_item.reload.recalculate_price
+ line_item.reload
return unless created
# Per-market provider rather than a global one, and carrying the same
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 7685cdb4d6..14babbf2ee 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -675,6 +675,7 @@ en:
delivery_unavailable: "%{li_name} cannot be delivered to the selected address"
discontinued: "%{li_name} was removed because it was discontinued"
out_of_stock: "%{li_name} was removed because it was sold out"
+ pricing_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.
categories: Categories
category: Category
diff --git a/spree/core/db/migrate/20260818000002_add_price_source_to_spree_line_items.rb b/spree/core/db/migrate/20260818000002_add_price_source_to_spree_line_items.rb
new file mode 100644
index 0000000000..918fa54157
--- /dev/null
+++ b/spree/core/db/migrate/20260818000002_add_price_source_to_spree_line_items.rb
@@ -0,0 +1,9 @@
+class AddPriceSourceToSpreeLineItems < ActiveRecord::Migration[8.1]
+ def change
+ # Which engine priced this line. NULL means Spree's own catalog, where
+ # price_list_id already says which list won; a value names the provider,
+ # because an external price leaves no catalog row to point at and an order
+ # still has to be able to say why it charged what it charged.
+ add_column :spree_line_items, :price_source, :string
+ end
+end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 0ba1a358f3..e80eac1b0d 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -352,6 +352,29 @@ module Spree
Rails.application.config.spree.tax_providers = value
end
+ # Pricing engines a store can be pointed at. Connector gems append their own,
+ # so a merchant picks from what is actually installed.
+ #
+ # @return [Array<Class>]
+ def self.pricing_providers
+ Rails.application.config.spree.pricing_providers
+ end
+
+ def self.pricing_providers=(value)
+ Rails.application.config.spree.pricing_providers = value
+ end
+
+ # Inventory sources a store can be pointed at.
+ #
+ # @return [Array<Class>]
+ def self.inventory_providers
+ Rails.application.config.spree.inventory_providers
+ end
+
+ def self.inventory_providers=(value)
+ Rails.application.config.spree.inventory_providers = value
+ end
+
# Validator enforcing the password policy on the default auth models
# ({Spree::Customer}, {Spree::AdminUser}). Defaults to
# {Spree::PasswordLengthValidator}, which reads the configurable length bounds.
@@ -768,4 +791,4 @@ require 'spree/core/preferences/masking'
require 'spree/core/permission_configuration'
require 'spree/core/ransack_configuration'
require 'spree/core/pricing/context'
-require 'spree/core/pricing/resolver'
+require 'spree/core/pricing/price_resolution'
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 1c7ccae924..cce3dc43f7 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -13,6 +13,8 @@ module Spree
:media_viewable_types,
:default_tax_provider,
:tax_providers,
+ :pricing_providers,
+ :inventory_providers,
:password_validator,
:fulfillment_providers,
:tracking_carriers,
@@ -156,6 +158,16 @@ module Spree
app.config.spree.tax_providers = []
end
+ # Same reason as the tax providers above: a connector gem registers its
+ # engine from an initializer file, and core's Internal concatenates below.
+ initializer 'spree.register.pricing_providers', before: :load_config_initializers do |app|
+ app.config.spree.pricing_providers = []
+ end
+
+ initializer 'spree.register.inventory_providers', before: :load_config_initializers do |app|
+ app.config.spree.inventory_providers = []
+ end
+
initializer 'spree.register.delivery_profile_types', before: :load_config_initializers do |app|
app.config.spree.delivery_profile_types = []
end
@@ -246,6 +258,12 @@ module Spree
# and host apps append theirs from initializer files, which run first.
Rails.application.config.spree.tax_providers.concat [Spree::TaxProvider::Internal]
+ # Pricing and inventory sources. Internal is Spree's own catalog and
+ # stock records; connector gems append theirs so a merchant picks from
+ # what is installed (see docs/plans/6.0-third-party-pricing-inventory.md).
+ Rails.application.config.spree.pricing_providers.concat [Spree::PricingProvider::Internal]
+ Rails.application.config.spree.inventory_providers.concat [Spree::InventoryProvider::Internal]
+
# Password policy for the default auth models. Swap for corporate rules,
# breach-list lookups or entropy scoring.
Rails.application.config.spree.password_validator = Spree::PasswordLengthValidator
diff --git a/spree/core/lib/spree/core/pricing/price_resolution.rb b/spree/core/lib/spree/core/pricing/price_resolution.rb
new file mode 100644
index 0000000000..f6723e9162
--- /dev/null
+++ b/spree/core/lib/spree/core/pricing/price_resolution.rb
@@ -0,0 +1,150 @@
+module Spree
+ module Pricing
+ # Picks the engine that answers a price, and stands between it and the rest
+ # of Spree.
+ #
+ # This sits on the catalog read path — the Store API serializers price every
+ # row of every listing — so three things happen here rather than in each
+ # provider:
+ #
+ # * a provider that declines the context (+handles?+) never gets asked, so
+ # anonymous browsing stays on the local catalog even when a contract
+ # pricing system is connected;
+ # * an answer is cached for providers that declare a +cache_ttl+, keyed by
+ # the context;
+ # * a provider that raises is handled per the store's failure policy —
+ # +strict+ re-raises as {ProviderUnavailable} so the caller decides,
+ # +fallback+ quietly uses Spree's own price.
+ class PriceResolution
+ # Raised when the configured provider could not answer and the store's
+ # policy is to refuse rather than substitute a catalog price. Callers in
+ # a checkout flow turn this into a retryable failure; the catalog read
+ # path treats it as "no price".
+ class ProviderUnavailable < StandardError
+ attr_reader :provider_key
+
+ def initialize(message = nil, provider_key: nil)
+ @provider_key = provider_key
+ super(message)
+ end
+ end
+
+ # @param context [Spree::Pricing::Context]
+ # @return [Spree::Price, nil]
+ def self.call(context)
+ new(context).resolve
+ end
+
+ attr_reader :context
+
+ def initialize(context)
+ @context = context
+ end
+
+ # @return [Spree::Price, nil]
+ def resolve
+ return internal_price unless external_provider?
+
+ provider_price
+ rescue ProviderUnavailable
+ raise
+ rescue StandardError => e
+ handle_failure(e)
+ end
+
+ private
+
+ def store
+ context.store
+ end
+
+ def provider
+ @provider ||= store&.pricing_provider_instance || Spree::PricingProvider::Internal.new
+ end
+
+ # Internal is not "an external system that happens to be local": skipping
+ # the cache and the rescue for it keeps the default path exactly as it
+ # was before providers existed.
+ def external_provider?
+ !provider.is_a?(Spree::PricingProvider::Internal) && provider.handles?(context)
+ end
+
+ def provider_price
+ ttl = provider.cache_ttl
+ return stamp(provider.price_for(context)) if ttl.blank?
+
+ cached = Rails.cache.fetch(provider_cache_key(store_id: store&.id), expires_in: ttl) do
+ price = provider.price_for(context)
+ price&.attributes
+ end
+
+ return if cached.blank?
+
+ stamp(build_price(cached))
+ end
+
+ # An internal answer carries no source: NULL on the line item means
+ # "Spree's own catalog", where price_list_id already says which list.
+ def internal_price
+ Spree::PricingProvider::Internal.new.price_for(context)
+ end
+
+ # A cached price is rebuilt from attributes rather than stored as an
+ # object: a marshalled Active Record instance carries the schema it was
+ # dumped under, and comes back broken after a migration.
+ def build_price(attributes)
+ Spree::Price.new(attributes.except('id')).tap do |price|
+ price.variant ||= context.variant
+ end
+ end
+
+ # An external price must never be saved into the catalog — readonly! is
+ # what turns "someone called save" from silent corruption into an error.
+ # It also carries which provider answered, so the line item can record
+ # that rather than whatever the store happens to be configured for.
+ def stamp(price)
+ return if price.blank?
+
+ # The context always knows the variant, and the tax-inclusive
+ # restatement reads it — a provider that builds a Price without one
+ # would otherwise fail deep in that call with an obscure NoMethodError
+ # rather than anywhere near the provider that omitted it.
+ price.variant ||= context.variant
+ price.readonly!
+ price.price_source = provider.class.key
+ price
+ end
+
+ # The store id is passed in rather than read here so the key visibly
+ # carries it — core's cache-key audit reads the call site, and a reader
+ # should not have to follow Pricing::Context to satisfy themselves that
+ # two stores cannot share an entry.
+ #
+ # Deliberately not Context#cache_key: that includes the context's date
+ # to the second, which would make every entry unique and the TTL
+ # meaningless. Staleness is bounded by the provider's cache_ttl instead.
+ def provider_cache_key(store_id:)
+ [
+ 'spree', 'pricing_provider', provider.class.key, store_id,
+ context.variant&.id, context.currency, context.country_code,
+ context.market&.id, context.channel&.id, context.user&.id, context.quantity
+ ].join('/')
+ end
+
+ # Strict refuses to *charge* an unconfirmed price — it must not take the
+ # catalog down. A checkout context carries the order and gets the
+ # exception, so the workflow can fail the step; a catalog read (no
+ # order) gets nil, which the serializers already render as "no price".
+ def handle_failure(error)
+ Spree::ProviderFailurePolicy.report_fallback(
+ kind: 'pricing', provider: provider.class.key, store: store, error: error
+ )
+
+ return internal_price unless store&.pricing_failure_policy == 'strict'
+ return nil if context.order.blank?
+
+ raise ProviderUnavailable.new(error.message, provider_key: provider.class.key)
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/pricing/resolver.rb b/spree/core/lib/spree/core/pricing/resolver.rb
deleted file mode 100644
index 5b5d7aad1a..0000000000
--- a/spree/core/lib/spree/core/pricing/resolver.rb
+++ /dev/null
@@ -1,124 +0,0 @@
-module Spree
- module Pricing
- class Resolver
- attr_reader :context
-
- # Initializes the resolver
- # @param context [Spree::Pricing::Context]
- def initialize(context)
- @context = context
- end
-
- # Returns the best price for the variant
- # @return [Spree::Price]
- def resolve
- find_best_price
- end
-
- private
-
- # Returns the best price for the variant
- # @return [Spree::Price]
- def find_best_price
- # Try to find a price from applicable price lists first
- price_from_list = find_price_from_lists
- return price_from_list if price_from_list
-
- # Fall back to base price (no price_list_id)
- find_base_price
- end
-
- # Returns the price from applicable price lists
- # @return [Spree::Price]
- def find_price_from_lists
- applicable_price_lists.each do |price_list|
- price = find_price_for_list(price_list)
- return price if price
- end
-
- nil
- end
-
- # Returns the price lists that are applicable to the context
- # @return [Array<Spree::PriceList>]
- def applicable_price_lists
- @applicable_price_lists ||= price_lists_for_context.select { |list| list.applicable?(context) }
- end
-
- # Returns the price lists for the context's store
- # Uses Spree::Current.price_lists if the context matches, otherwise fetches directly
- # @return [ActiveRecord::Relation<Spree::PriceList>]
- def price_lists_for_context
- if context.store == Spree::Current.store && context.currency == Spree::Current.currency
- Spree::Current.price_lists
- else
- Spree::PriceList.for_context(context)
- end
- end
-
- # Returns the price for a given price list
- # @param price_list [Spree::PriceList]
- # @return [Spree::Price]
- def find_price_for_list(price_list)
- currency = context.currency&.upcase
-
- # Zero is a valid override (free for this list); only nil placeholder
- # rows (materialized by PriceList#add_products) are skipped.
- if prices.loaded?
- prices.detect do |p|
- p.currency == currency &&
- p.price_list_id == price_list.id &&
- !p.amount.nil?
- end
- else
- context.variant.prices
- .with_currency(currency)
- .where(price_list_id: price_list.id)
- .where.not(amount: nil)
- .first
- end
- end
-
- # Returns the base price for the variant in the current currency
- # @return [Spree::Price]
- def find_base_price
- currency = context.currency&.upcase
-
- price = if prices.loaded?
- prices.detect do |p|
- p.currency == currency &&
- p.price_list_id.nil? &&
- p.amount.present?
- end
- else
- context.variant.prices
- .with_currency(currency)
- .where(price_list_id: nil)
- .where.not(amount: nil)
- .first
- end
-
- price || build_empty_price
- end
-
- # Returns the prices for the variant
- # @return [ActiveRecord::Relation<Spree::Price>]
- def prices
- context.variant.prices
- end
-
- # Returns an empty price placeholder for the variant.
- # Uses Price.new instead of prices.build to avoid polluting the association
- # with an unsaved record that would fail validation on variant save.
- # @return [Spree::Price]
- def build_empty_price
- Spree::Price.new(
- variant_id: context.variant.id,
- currency: context.currency,
- amount: nil,
- price_list_id: nil
- )
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/inventory_provider_spec.rb b/spree/core/spec/models/spree/inventory_provider_spec.rb
new file mode 100644
index 0000000000..6d3b61fa32
--- /dev/null
+++ b/spree/core/spec/models/spree/inventory_provider_spec.rb
@@ -0,0 +1,128 @@
+require 'spec_helper'
+
+RSpec.describe 'Inventory providers' do
+ let(:store) { @default_store }
+ let(:stock_location) { create(:stock_location, store: store) }
+ let(:variant) { create(:variant) }
+
+ before do
+ variant.stock_levels.destroy_all
+ # adjust_count_on_hand: false — the factory otherwise adds ten on top of
+ # whatever count_on_hand was asked for.
+ create(:stock_level, variant: variant, stock_location: stock_location,
+ count_on_hand: 10, backorderable: false, adjust_count_on_hand: false)
+ variant.stock_levels.reload
+ end
+
+ describe 'the default store' do
+ it 'counts Spree stock records, exactly as before providers existed' do
+ expect(store.inventory_provider_instance).to be_a(Spree::InventoryProvider::Internal)
+ expect(Spree::Stock::Quantifier.new(variant).total_on_hand).to eq(10)
+ end
+ end
+
+ describe 'counting an external system rows' do
+ # What an external provider returns: rows shaped like stock items but never
+ # saved, so nothing can write a remote count into Spree's own records.
+ def external_rows(count_on_hand:, backorderable: false)
+ [Spree::StockLevel.new(variant: variant, stock_location: stock_location,
+ count_on_hand: count_on_hand, backorderable: backorderable)]
+ end
+
+ it 'counts the rows it is handed rather than the local ones' do
+ quantifier = Spree::Stock::Quantifier.new(variant, stock_levels: external_rows(count_on_hand: 3))
+
+ expect(quantifier.total_on_hand).to eq(3)
+ end
+
+ it 'answers can_supply? from those rows' do
+ quantifier = Spree::Stock::Quantifier.new(variant, stock_levels: external_rows(count_on_hand: 3))
+
+ expect(quantifier.can_supply?(3)).to be(true)
+ expect(quantifier.can_supply?(4)).to be(false)
+ end
+
+ # A provider that knows nothing about the variant returns no rows at all.
+ # That is an answer — zero — not a reason to fall back to local records
+ # (which would let a variant the warehouse has never heard of be sold).
+ it 'treats no rows from the provider as nothing in stock' do
+ quantifier = Spree::Stock::Quantifier.new(variant, stock_levels: [])
+
+ expect(quantifier.total_on_hand).to eq(0)
+ expect(quantifier.can_supply?(1)).to be(false)
+ end
+
+ it 'honours backorderable as the external system reports it' do
+ quantifier = Spree::Stock::Quantifier.new(
+ variant, stock_levels: external_rows(count_on_hand: 0, backorderable: true)
+ )
+
+ expect(quantifier.can_supply?(50)).to be(true)
+ end
+
+ # The external system knows nothing about our carts, so a hold taken during
+ # checkout has to keep reducing what the next shopper can buy. The rows
+ # carry no id to match reservations on, which is exactly where this can go
+ # quietly wrong and oversell.
+ it 'still subtracts a local checkout hold' do
+ cart = create(:cart, store: store)
+ line_item = create(:line_item, order: cart, variant: variant, quantity: 4)
+ local_item = variant.stock_levels.reload.first
+ create(:stock_reservation, stock_level: local_item, line_item: line_item, cart: cart, quantity: 4)
+
+ quantifier = Spree::Stock::Quantifier.new(variant, stock_levels: external_rows(count_on_hand: 10))
+
+ expect(quantifier.total_on_hand).to eq(6)
+ end
+
+ it 'leaves a cart its own hold when checking its own items' do
+ cart = create(:cart, store: store)
+ line_item = create(:line_item, order: cart, variant: variant, quantity: 4)
+ local_item = variant.stock_levels.reload.first
+ create(:stock_reservation, stock_level: local_item, line_item: line_item, cart: cart, quantity: 4)
+
+ quantifier = Spree::Stock::Quantifier.new(
+ variant, excluded_order: cart, stock_levels: external_rows(count_on_hand: 10)
+ )
+
+ expect(quantifier.total_on_hand).to eq(10)
+ end
+ end
+
+ describe 'Internal provider rows' do
+ let(:provider) { Spree::InventoryProvider::Internal.new }
+
+ it 'returns the variant stock items' do
+ expect(provider.stock_levels_for(variant).map(&:id)).to eq(variant.stock_levels.map(&:id))
+ end
+
+ it 'narrows to one location when asked' do
+ other = create(:stock_location, store: store)
+ create(:stock_level, variant: variant, stock_location: other, count_on_hand: 5, adjust_count_on_hand: false)
+ variant.stock_levels.reload
+
+ expect(provider.stock_levels_for(variant, stock_location: other).map(&:stock_location_id)).to eq([other.id])
+ end
+
+ it 'keeps a preloaded association in memory rather than querying again' do
+ loaded = Spree::Variant.includes(:stock_levels).find(variant.id)
+
+ queries = 0
+ counter = ->(*, payload) { queries += 1 unless payload[:name].to_s.in?(['SCHEMA', 'TRANSACTION']) }
+
+ ActiveSupport::Notifications.subscribed(counter, 'sql.active_record') do
+ provider.stock_levels_for(loaded, stock_location: stock_location).to_a
+ end
+
+ expect(queries).to eq(0)
+ end
+ end
+
+ describe 'an unknown provider key' do
+ it 'falls back to Spree stock records rather than taking checkout down' do
+ stub_store_preferences(store, inventory_provider: 'uninstalled_gem')
+
+ expect(store.inventory_provider_instance).to be_a(Spree::InventoryProvider::Internal)
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/pricing/resolver_spec.rb b/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb
similarity index 96%
rename from spree/core/spec/lib/spree/pricing/resolver_spec.rb
rename to spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb
index 48be8ac868..999cfd3e29 100644
--- a/spree/core/spec/lib/spree/pricing/resolver_spec.rb
+++ b/spree/core/spec/models/spree/pricing_provider/internal_resolution_spec.rb
@@ -1,6 +1,9 @@
require 'spec_helper'
-describe Spree::Pricing::Resolver do
+# The price-list walk that backs Spree's own pricing. Exercised directly
+# rather than through Internal#price_for so a failure names the rule that
+# broke; the provider's own contract is covered in pricing_provider_spec.rb.
+describe Spree::PricingProvider::Internal::Resolution do
let(:variant) { create(:variant) }
let(:store) { create(:store) }
let(:currency) { 'USD' }
diff --git a/spree/core/spec/models/spree/pricing_provider_spec.rb b/spree/core/spec/models/spree/pricing_provider_spec.rb
new file mode 100644
index 0000000000..23c057f93a
--- /dev/null
+++ b/spree/core/spec/models/spree/pricing_provider_spec.rb
@@ -0,0 +1,188 @@
+require 'spec_helper'
+
+RSpec.describe 'Pricing providers' do
+ let(:store) { @default_store }
+ let(:variant) { create(:variant, price: 20) }
+ let(:context) { Spree::Pricing::Context.new(variant: variant, currency: 'USD', store: store) }
+
+ # Answers a fixed amount so a test can tell a provider price from the catalog
+ # one, and can be made to fail on demand.
+ let(:external_provider_class) do
+ Class.new(Spree::PricingProvider::Base) do
+ class << self
+ attr_accessor :key_name, :fail_with, :handles, :ttl, :calls
+ end
+ self.key_name = 'contract'
+ self.calls = 0
+
+ def self.key = key_name
+
+ def handles?(_context)
+ self.class.handles.nil? ? true : self.class.handles
+ end
+
+ def cache_ttl = self.class.ttl
+
+ def price_for(context)
+ self.class.calls += 1
+ raise self.class.fail_with if self.class.fail_with
+
+ Spree::Price.new(variant: context.variant, currency: context.currency, amount: 5)
+ end
+ end
+ end
+
+ before do
+ stub_const('SpreeTest::ContractPricingProvider', external_provider_class)
+ external_provider_class.fail_with = nil
+ external_provider_class.handles = nil
+ external_provider_class.ttl = nil
+ external_provider_class.calls = 0
+ end
+
+ describe 'the default store' do
+ it 'prices from the catalog, exactly as before providers existed' do
+ expect(store.pricing_provider_instance).to be_a(Spree::PricingProvider::Internal)
+ expect(variant.price_for(context).amount).to eq(20)
+ end
+
+ it 'returns a persisted, writable price' do
+ expect(variant.price_for(context)).to be_persisted
+ end
+ end
+
+ context 'with an external provider selected' do
+ before do
+ Spree.pricing_providers << external_provider_class
+ stub_store_preferences(store, pricing_provider: 'contract')
+ end
+
+ after { Spree.pricing_providers.delete(external_provider_class) }
+
+ it 'answers with the provider price' do
+ expect(variant.price_for(context).amount).to eq(5)
+ end
+
+ it 'marks the provider price readonly so it cannot leak into the catalog' do
+ price = variant.price_for(context)
+
+ expect(price).to be_readonly
+ expect { price.save }.to raise_error(ActiveRecord::ReadOnlyRecord)
+ end
+
+ # The contract does not require a provider to set the variant, and the
+ # tax-inclusive restatement reads it — without this the price fails deep
+ # inside that call with an obscure NoMethodError.
+ it 'fills in the variant when a provider builds a price without one' do
+ bare = Class.new(Spree::PricingProvider::Base) do
+ def self.key = 'bare'
+ def price_for(pricing_context) = Spree::Price.new(currency: pricing_context.currency, amount: 7)
+ end
+ Spree.pricing_providers << bare
+ stub_store_preferences(store, pricing_provider: 'bare')
+
+ expect(variant.price_for(context).variant).to eq(variant)
+ ensure
+ Spree.pricing_providers.delete(bare)
+ end
+
+ it 'falls back to the catalog for a context the provider declines' do
+ external_provider_class.handles = false
+
+ expect(variant.price_for(context).amount).to eq(20)
+ expect(external_provider_class.calls).to eq(0)
+ end
+
+ it 'caches by context when the provider asks for it' do
+ external_provider_class.ttl = 5.minutes
+
+ with_memory_cache do
+ expect(variant.price_for(context).amount).to eq(5)
+ expect(variant.price_for(context).amount).to eq(5)
+ end
+
+ expect(external_provider_class.calls).to eq(1)
+ end
+
+ # Contexts carry the moment they were built; two shoppers a second apart
+ # must still share the entry or the cache never hits at all.
+ it 'shares the cached answer across requests made at different moments' do
+ external_provider_class.ttl = 5.minutes
+ later = Spree::Pricing::Context.new(variant: variant, currency: 'USD', store: store, date: 1.second.from_now)
+
+ with_memory_cache do
+ variant.price_for(context)
+ variant.price_for(later)
+ end
+
+ expect(external_provider_class.calls).to eq(1)
+ end
+
+ it 'does not serve one shopper the price cached for another' do
+ external_provider_class.ttl = 5.minutes
+ other = Spree::Pricing::Context.new(variant: variant, currency: 'USD', store: store,
+ user: create(:user), quantity: 10)
+
+ with_memory_cache do
+ variant.price_for(context)
+ variant.price_for(other)
+ end
+
+ expect(external_provider_class.calls).to eq(2)
+ end
+
+ describe 'when the provider is unreachable' do
+ before { external_provider_class.fail_with = Timeout::Error }
+
+ it 'refuses to price a cart under the default strict policy' do
+ cart = create(:cart, store: store)
+ checkout_context = Spree::Pricing::Context.from_order(variant, cart, quantity: 1)
+
+ expect { variant.price_for(checkout_context) }.
+ to raise_error(Spree::Pricing::PriceResolution::ProviderUnavailable)
+ end
+
+ # Strict is about not charging an unconfirmed price. The catalog must
+ # keep rendering; a listing that 500s while the ERP hiccups is worse
+ # than a tile with no price on it.
+ it 'answers no price, rather than raising, on a catalog read' do
+ expect(variant.price_for(context)).to be_nil
+ end
+
+ it 'uses the catalog price when the store opts into falling back' do
+ stub_store_preferences(store, pricing_provider: 'contract', pricing_provider_failure_policy: 'fallback')
+
+ expect(variant.price_for(context).amount).to eq(20)
+ end
+
+ it 'reports the fallback so an operator can see it happening' do
+ stub_store_preferences(store, pricing_provider: 'contract', pricing_provider_failure_policy: 'fallback')
+ events = []
+ callback = ->(*, payload) { events << payload }
+
+ ActiveSupport::Notifications.subscribed(callback, 'provider.fallback.spree') do
+ variant.price_for(context)
+ end
+
+ expect(events.first).to include(provider: 'contract', kind: 'pricing', reason: 'Timeout::Error')
+ end
+ end
+ end
+
+ describe 'an unknown provider key' do
+ it 'falls back to the catalog rather than taking the store down' do
+ stub_store_preferences(store, pricing_provider: 'uninstalled_gem')
+
+ expect(store.pricing_provider_instance).to be_a(Spree::PricingProvider::Internal)
+ expect(variant.price_for(context).amount).to eq(20)
+ end
+ end
+
+ def with_memory_cache
+ original = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+ yield
+ ensure
+ Rails.cache = original
+ end
+end
diff --git a/spree/core/spec/services/spree/carts/check_availability_spec.rb b/spree/core/spec/services/spree/carts/check_availability_spec.rb
new file mode 100644
index 0000000000..dbdca568d1
--- /dev/null
+++ b/spree/core/spec/services/spree/carts/check_availability_spec.rb
@@ -0,0 +1,91 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Carts::CheckAvailability do
+ let(:store) { @default_store }
+ let(:cart) { create(:cart, store: store) }
+ let(:stock_location) { create(:stock_location, store: store) }
+ let(:variant) { create(:variant) }
+
+ before do
+ variant.stock_levels.destroy_all
+ create(:stock_level, variant: variant, stock_location: stock_location,
+ count_on_hand: 5, backorderable: false, adjust_count_on_hand: false)
+ variant.stock_levels.reload
+ end
+
+ let(:external_provider_class) do
+ Class.new(Spree::InventoryProvider::Base) do
+ class << self
+ attr_accessor :count, :fail_with
+ end
+ self.count = 2
+
+ def self.key = 'wms'
+
+ def stock_levels_for(variant, stock_location: nil)
+ raise self.class.fail_with if self.class.fail_with
+
+ [Spree::StockLevel.new(variant: variant, stock_location: variant.stock_levels.first&.stock_location,
+ count_on_hand: self.class.count, backorderable: false)]
+ end
+ end
+ end
+
+ describe 'with Spree own stock records' do
+ it 'reports nothing unsupplyable when there is enough' do
+ result = described_class.call(cart: cart, items: [{ variant: variant, quantity: 5 }])
+
+ expect(result).to be_success
+ expect(result.value).to be_empty
+ end
+
+ it 'reports the item when more is asked for than exists' do
+ result = described_class.call(cart: cart, items: [{ variant: variant, quantity: 6 }])
+
+ expect(result.value.map(&:first)).to eq([variant])
+ end
+ end
+
+ describe 'with an external warehouse' do
+ before do
+ stub_const('SpreeTest::WmsProvider', external_provider_class)
+ external_provider_class.fail_with = nil
+ external_provider_class.count = 2
+ Spree.inventory_providers << external_provider_class
+ stub_store_preferences(store, inventory_provider: 'wms')
+ end
+
+ after { Spree.inventory_providers.delete(external_provider_class) }
+
+ it 'believes the warehouse over the local snapshot' do
+ result = described_class.call(cart: cart, items: [{ variant: variant, quantity: 4 }])
+
+ expect(result.value.map(&:first)).to eq([variant])
+ end
+
+ it 'allows what the warehouse says it has' do
+ result = described_class.call(cart: cart, items: [{ variant: variant, quantity: 2 }])
+
+ expect(result.value).to be_empty
+ end
+
+ # Default policy: an oversell is recoverable, a blocked checkout is not.
+ it 'sells on the local figure when the warehouse is unreachable' do
+ external_provider_class.fail_with = Timeout::Error
+
+ result = described_class.call(cart: cart, items: [{ variant: variant, quantity: 5 }])
+
+ expect(result).to be_success
+ expect(result.value).to be_empty
+ end
+
+ it 'refuses when the store would rather not sell than guess' do
+ external_provider_class.fail_with = Timeout::Error
+ stub_store_preferences(store, inventory_provider: 'wms', inventory_provider_failure_policy: 'strict')
+
+ result = described_class.call(cart: cart, items: [{ variant: variant, quantity: 5 }])
+
+ expect(result).to be_failure
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/carts/price_items_spec.rb b/spree/core/spec/services/spree/carts/price_items_spec.rb
new file mode 100644
index 0000000000..d735f6ee77
--- /dev/null
+++ b/spree/core/spec/services/spree/carts/price_items_spec.rb
@@ -0,0 +1,142 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Carts::PriceItems do
+ let(:store) { @default_store }
+ let(:cart) { create(:cart, store: store) }
+ let(:variant) { create(:variant, price: 20) }
+
+ let(:external_provider_class) do
+ Class.new(Spree::PricingProvider::Base) do
+ class << self
+ attr_accessor :amount, :fail_with, :calls
+ end
+ self.amount = 5
+ self.calls = 0
+
+ def self.key = 'contract'
+
+ def price_for(context)
+ self.class.calls += 1
+ raise self.class.fail_with if self.class.fail_with
+
+ Spree::Price.new(variant: context.variant, currency: context.currency, amount: self.class.amount)
+ end
+ end
+ end
+
+ describe 'with Spree own catalog' do
+ it 'prices from the catalog and records no provider' do
+ line_item = create(:line_item, order: cart, variant: variant, quantity: 1)
+
+ result = described_class.new.call(cart: cart, line_items: [line_item])
+ described_class.apply(result.value)
+
+ expect(line_item.reload.price).to eq(20)
+ expect(line_item.price_source).to be_nil
+ end
+
+ it 'never re-prices a completed order — what it sold at is a fact, not a question' do
+ order = create(:completed_order_with_totals, store: store)
+ line_item = order.line_items.first
+ original = line_item.price
+ line_item.variant.prices.each { |price| price.update!(amount: 999) }
+
+ result = described_class.new.call(cart: order, line_items: [line_item])
+ described_class.apply(result.value)
+
+ expect(line_item.reload.price).to eq(original)
+ end
+
+ # The freeze covers what was sold, not what is being added: an admin
+ # amending a placed order still needs the new line priced through the
+ # price lists (and a provider), or a contract customer is billed list.
+ it 'still prices a line being added to a completed order' do
+ order = create(:completed_order_with_totals, store: store)
+ price_list = create(:price_list, :active, store: store)
+ create(:price, variant: variant, price_list: price_list, currency: 'USD', amount: 15)
+ new_line = order.line_items.new(variant: variant, quantity: 1, currency: 'USD')
+
+ result = described_class.new.call(cart: order, line_items: [new_line])
+ described_class.apply(result.value)
+
+ expect(new_line.price).to eq(15)
+ expect(new_line.price_list_id).to eq(price_list.id)
+ end
+ end
+
+ describe 'with an external provider' do
+ before do
+ stub_const('SpreeTest::ContractProvider', external_provider_class)
+ external_provider_class.fail_with = nil
+ external_provider_class.calls = 0
+ Spree.pricing_providers << external_provider_class
+ stub_store_preferences(store, pricing_provider: 'contract')
+ end
+
+ after { Spree.pricing_providers.delete(external_provider_class) }
+
+ it 'writes the provider price and names the provider on the line' do
+ line_item = create(:line_item, order: cart, variant: variant, quantity: 1)
+
+ result = described_class.new.call(cart: cart, line_items: [line_item])
+ described_class.apply(result.value)
+
+ expect(line_item.reload.price).to eq(5)
+ expect(line_item.price_source).to eq('contract')
+ end
+
+ it 'asks once per line and no more, so a large cart is one round per item' do
+ 3.times { create(:line_item, order: cart, variant: create(:variant), quantity: 1) }
+
+ described_class.new.call(cart: cart)
+
+ expect(external_provider_class.calls).to eq(3)
+ end
+
+ it 'refuses to price when the provider is down and the store is strict' do
+ external_provider_class.fail_with = Timeout::Error
+ line_item = create(:line_item, order: cart, variant: variant, quantity: 1)
+
+ result = described_class.new.call(cart: cart, line_items: [line_item])
+
+ expect(result).to be_failure
+ end
+
+ it 'falls back to the catalog price when the store opts into that, and says so on the line' do
+ external_provider_class.fail_with = Timeout::Error
+ stub_store_preferences(store, pricing_provider: 'contract', pricing_provider_failure_policy: 'fallback')
+ line_item = create(:line_item, order: cart, variant: variant, quantity: 1)
+
+ result = described_class.new.call(cart: cart, line_items: [line_item])
+ described_class.apply(result.value)
+
+ expect(result).to be_success
+ expect(line_item.reload.price).to eq(20)
+ # Priced from the catalog, so the line must not claim the provider did it.
+ expect(line_item.price_source).to be_nil
+ end
+ end
+
+ describe 'applying' do
+ it 'leaves a line item alone when the price has not moved' do
+ line_item = create(:line_item, order: cart, variant: variant, quantity: 1)
+ result = described_class.new.call(cart: cart, line_items: [line_item])
+ described_class.apply(result.value)
+ before = line_item.reload.updated_at
+
+ described_class.apply(result.value)
+
+ expect(line_item.reload.updated_at).to eq(before)
+ end
+
+ it 'assigns without saving for a line item that does not exist yet' do
+ line_item = cart.line_items.new(variant: variant, quantity: 1, currency: cart.currency)
+
+ result = described_class.new.call(cart: cart, line_items: [line_item])
+ described_class.apply(result.value)
+
+ expect(line_item.price).to eq(20)
+ expect(line_item).to be_new_record
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/carts/update_spec.rb b/spree/core/spec/services/spree/carts/update_spec.rb
index 036b040ab2..521449dd6a 100644
--- a/spree/core/spec/services/spree/carts/update_spec.rb
+++ b/spree/core/spec/services/spree/carts/update_spec.rb
@@ -848,5 +848,44 @@ module Spree
end
end
+
+ describe 'when a strict store cannot confirm prices' do
+ let(:store) { @default_store }
+ let(:cart) { create(:cart, store: store) }
+ let(:variant) { create(:variant, price: 20) }
+
+ let(:failing_provider) do
+ Class.new(Spree::PricingProvider::Base) do
+ def self.key = 'contract'
+ def price_for(_context) = raise(Timeout::Error)
+ end
+ end
+
+ before do
+ create(:line_item, order: cart, variant: variant, quantity: 1)
+ Spree.pricing_providers << failing_provider
+ stub_store_preferences(store, pricing_provider: 'contract')
+ end
+
+ after { Spree.pricing_providers.delete(failing_provider) }
+
+ # The address change and the prices are one decision: committing a new
+ # destination while refusing to price for it would leave the cart showing
+ # figures nobody stood behind.
+ it 'rolls the address change back rather than committing it unpriced' do
+ result = described_class.call(
+ cart: cart,
+ params: { shipping_address: { firstname: 'Ada', lastname: 'Lovelace', address1: '1 Main St',
+ city: 'New York', zipcode: '10001', phone: '555-0100',
+ country_code: 'US', state_code: 'NY' } }
+ )
+
+ expect(result).to be_failure
+ # The object handed back must not still carry the rolled-back address:
+ # a caller that renders it would show an address the database refused.
+ expect(cart.ship_address_id).to be_nil
+ expect(cart.reload.shipping_address).to be_nil
+ end
+ end
end
end
diff --git a/spree/core/spec/workflows/spree/carts/add_item_pricing_provider_spec.rb b/spree/core/spec/workflows/spree/carts/add_item_pricing_provider_spec.rb
new file mode 100644
index 0000000000..4284e48451
--- /dev/null
+++ b/spree/core/spec/workflows/spree/carts/add_item_pricing_provider_spec.rb
@@ -0,0 +1,32 @@
+require 'spec_helper'
+RSpec.describe Spree::Carts::AddItem, 'with an external pricing provider' do
+ let(:store) { @default_store }
+ let(:cart) { create(:cart, store: store) }
+ let(:variant) { create(:variant, price: 20) }
+ let(:klass) do
+ Class.new(Spree::PricingProvider::Base) do
+ class << self; attr_accessor :calls; end
+ self.calls = 0
+ def self.key = 'contract'
+ def price_for(ctx)
+ self.class.calls += 1
+ Spree::Price.new(variant: ctx.variant, currency: ctx.currency, amount: 5)
+ end
+ end
+ end
+ before { Spree.pricing_providers << klass; stub_store_preferences(store, pricing_provider: 'contract') }
+ after { Spree.pricing_providers.delete(klass) }
+
+ # The second add increments an existing line; the quantity-change callback
+ # used to ask the provider again from inside the transaction.
+ it 'asks the provider once per add, even when incrementing an existing line' do
+ Spree::Carts::AddItem.call(cart: cart, variant: variant, quantity: 1)
+ klass.calls = 0
+
+ Spree::Carts::AddItem.call(cart: cart, variant: variant, quantity: 1)
+
+ expect(klass.calls).to eq(1)
+ expect(cart.line_items.reload.first.price).to eq(5)
+ expect(cart.line_items.first.quantity).to eq(2)
+ end
+end