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.

Say each pricing and reference rule once more

Damian Legawieca90f78519d31
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
index 6577494ce4..033bb5cd8d 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
@@ -39,20 +39,24 @@ module Spree
scope.find_by_prefix_id!(cart_id)
end
- # Render the cart as JSON using the cart serializer.
- #
- # +sweep+ drops lines the customer can no longer buy — a discontinued
- # product, or stock that ran out while the cart sat idle. It belongs to
- # reads of a cart the customer is returning to, not to the write that
- # just happened: an add that a stock check already approved must not be
- # second-guessed by a sweep in the same request, and an external
- # inventory provider makes that contradiction routine, since the
- # provider answers the write while the sweep reads Spree's own rows.
- def render_cart(status: :ok, sweep: false)
- @cart = @cart.remove_out_of_stock_items! if sweep
+ # Render the cart as JSON using the cart serializer. Rendering never
+ # mutates: an action that wants unbuyable lines swept calls
+ # +sweep_unbuyable_lines!+ itself first.
+ def render_cart(status: :ok)
render json: Spree.api.cart_serializer.new(@cart, params: serializer_params).to_h, status: status
end
+ # Drops lines the customer can no longer buy — a discontinued product,
+ # or stock that ran out while the cart sat idle. For reads of a cart
+ # the customer is returning to, never for the write that just
+ # happened: an add a stock check already approved must not be
+ # second-guessed in the same request, and an external inventory
+ # provider makes that contradiction routine, since the provider
+ # answers the write while the sweep reads Spree's own rows.
+ def sweep_unbuyable_lines!
+ @cart = @cart.remove_out_of_stock_items!
+ end
+
# Render what the checkout produced (for the complete action).
#
# A checkout spanning several sellers produced a group of orders rather
diff --git a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
index 8764ee5d68..5736b6d2b4 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
@@ -9,7 +9,6 @@ module Spree
# collection-bound attributes (automatic, sort_order, rules) are
# readable or writable here.
class CategoriesController < ResourceController
- include Spree::Api::V3::Admin::Concerns::ExternalReferences
scoped_resource :categories
# PATCH /api/v3/admin/categories/:id/reposition
diff --git a/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rb
index 79e0742764..75f22e0034 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rb
@@ -7,7 +7,6 @@ module Spree
# deleting a branch are addressed directly, since a caller holding a
# branch id shouldn't have to know its company.
class LocationsController < BaseController
- include Spree::Api::V3::Admin::Concerns::ExternalReferences
include Spree::Api::V3::Admin::Concerns::CompanyLocationParams
before_action :authorize_parent_access!
diff --git a/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb
index 4d81f308e0..c23a734d4d 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb
@@ -5,7 +5,6 @@ module Spree
# Business customers. A company is a customer record, so it answers to
# the customer scopes rather than earning one of its own.
class CompaniesController < ResourceController
- include Spree::Api::V3::Admin::Concerns::ExternalReferences
scoped_resource :customers
protected
diff --git a/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rb
index 6bac71d2d1..239d42d769 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rb
@@ -5,7 +5,6 @@ module Spree
# A branch addressed directly. Reached through the store's companies so a
# branch of another tenant's company is a 404.
class CompanyLocationsController < ResourceController
- include Spree::Api::V3::Admin::Concerns::ExternalReferences
include Spree::Api::V3::Admin::Concerns::CompanyLocationParams
scoped_resource :customers
diff --git a/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb
index dad32457b0..273ba73083 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb
@@ -3,7 +3,6 @@ module Spree
module V3
module Admin
class MediaController < ResourceController
- include Spree::Api::V3::Admin::Concerns::ExternalReferences
scoped_resource :products
def create
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
index a77da59cdb..5d5abed993 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
@@ -3,7 +3,6 @@ module Spree
module V3
module Admin
class OrdersController < ResourceController
- include Spree::Api::V3::Admin::Concerns::ExternalReferences
include Spree::Api::V3::OrderLock
scoped_resource :orders
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
index d4f4dcb9ff..5cefff99e6 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -3,7 +3,6 @@ module Spree
module V3
module Admin
class ProductsController < ResourceController
- include Spree::Api::V3::Admin::Concerns::ExternalReferences
include Spree::Api::V3::BulkOperations
include Spree::Api::V3::Admin::ProductListing
diff --git a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
index f3a21b1ca2..17de99367d 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
@@ -9,6 +9,13 @@ module Spree
include Spree::Api::V3::Admin::StoreContext
include Spree::Api::V3::AdminAuthentication
include Spree::Api::V3::ScopedAuthorization
+ # External-identity addressing for every admin resource whose model
+ # opts in via Spree::HasExternalReferences — the concern's guards
+ # no-op for everything else. Sitting here rather than per controller
+ # means a newly synced resource cannot ship the half-supported state
+ # (readable references, unaddressable member paths) by forgetting an
+ # include.
+ include Spree::Api::V3::Admin::Concerns::ExternalReferences
protected
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
index bb67c18ac9..f0f2c3d72a 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
@@ -13,7 +13,11 @@ module Spree
def bulk_upsert
authorize! :update, Spree::StockLevel
- rows = Array(params[:stock_levels]).map { |row| decode_stock_row(row) }
+ raw_rows = Array(params[:stock_levels]).map do |row|
+ row = row.respond_to?(:to_unsafe_h) ? row.to_unsafe_h : row.to_h
+ row.with_indifferent_access
+ end
+ rows = decode_stock_rows(raw_rows)
invalid = rows.each_with_index.filter_map do |row, index|
missing = %i[variant_id stock_location_id].reject { |key| row[key].present? }
@@ -140,17 +144,32 @@ module Spree
# rather than quietly written to. Rows name records by Spree's own
# ids alone — this endpoint upserts stock levels, nothing more; a
# connector resolves its keys through the member paths first.
- def decode_stock_row(row)
- row = row.respond_to?(:to_unsafe_h) ? row.to_unsafe_h : row.to_h
- row = row.with_indifferent_access
-
- {
- variant_id: store_variants.find_by_prefix_id(row[:variant_id])&.id,
- stock_location_id: store_stock_locations.find_by_prefix_id(row[:stock_location_id])&.id,
- count_on_hand: row[:count_on_hand],
- adjustment: row[:adjustment],
- backorderable: row[:backorderable]
- }.compact
+ #
+ # Resolved as a batch: decoding a prefixed id is pure Ruby, so a
+ # thousand-row feed costs two SELECTs here, not two per row — and a
+ # feed repeats its stock location on nearly every row.
+ def decode_stock_rows(raw_rows)
+ variant_ids = resolve_ids(store_variants, Spree::Variant, raw_rows.map { |row| row[:variant_id] })
+ location_ids = resolve_ids(store_stock_locations, Spree::StockLocation, raw_rows.map { |row| row[:stock_location_id] })
+
+ raw_rows.map do |row|
+ {
+ variant_id: variant_ids[row[:variant_id]],
+ stock_location_id: location_ids[row[:stock_location_id]],
+ count_on_hand: row[:count_on_hand],
+ adjustment: row[:adjustment],
+ backorderable: row[:backorderable]
+ }.compact
+ end
+ end
+
+ # @return [Hash{String=>Integer}] prefixed id => id, for the ids the
+ # scope can actually see; unknown or foreign ids resolve to nothing
+ def resolve_ids(scope, model, prefixed_ids)
+ decoded = prefixed_ids.uniq.index_with { |value| model.decode_own_prefixed_id(value) }
+ found = scope.where(id: decoded.values.compact).pluck(:id).to_set
+
+ decoded.transform_values { |id| id if id && found.include?(id) }
end
def store_variants
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
index 8f8d73a0f7..72d902ddb6 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
@@ -3,7 +3,6 @@ module Spree
module V3
module Admin
class StockLocationsController < ResourceController
- include Spree::Api::V3::Admin::Concerns::ExternalReferences
scoped_resource :stock
protected
diff --git a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
index 9e5495468c..e1fb8a2269 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
@@ -3,7 +3,6 @@ module Spree
module V3
module Admin
class VariantsController < ResourceController
- include Spree::Api::V3::Admin::Concerns::ExternalReferences
scoped_resource :products
protected
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
index 99474b0059..7e94e4296f 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
@@ -25,9 +25,9 @@ module Spree
end
end
- # The customer is returning to a cart that may have sat for days,
- # so this is where anything they can no longer buy is dropped.
- render_cart(sweep: true)
+ # The customer is returning to a cart that may have sat for days.
+ sweep_unbuyable_lines!
+ render_cart
end
# POST /api/v3/store/carts
@@ -101,7 +101,8 @@ module Spree
if result.success?
# Signing in hands back a cart built earlier, possibly long ago.
- render_cart(sweep: true)
+ sweep_unbuyable_lines!
+ render_cart
else
render_service_error(result.error.to_s)
end
diff --git a/spree/core/app/jobs/spree/images/save_from_url_job.rb b/spree/core/app/jobs/spree/images/save_from_url_job.rb
index 76a1b91bc9..85263863c5 100644
--- a/spree/core/app/jobs/spree/images/save_from_url_job.rb
+++ b/spree/core/app/jobs/spree/images/save_from_url_job.rb
@@ -128,22 +128,23 @@ module Spree
image_scope(viewable).with_external_url(external_url).first || viewable_assets(viewable).new
end
- # Normalises the caller's external ids — a bare string, a
- # `{ system:, external_id: }` hash, or a list of either — into one shape.
+ # Normalises the caller's external ids into the shared entry shape.
+ # This job's own additions over {Spree::ExternalReference.normalize_references}
+ # are the legacy bare-string form and a default system for entries that
+ # name none — everything else parses identically to the API.
def external_references_from(external_id)
return [] if external_id.blank?
- entries = external_id.is_a?(Array) ? external_id : [external_id]
- entries.filter_map do |entry|
+ entries = (external_id.is_a?(Array) ? external_id : [external_id]).map do |entry|
if entry.is_a?(Hash)
hash = entry.to_h.symbolize_keys
- next if hash[:external_id].blank?
-
- { system: hash[:system].presence || DEFAULT_EXTERNAL_SYSTEM, external_id: hash[:external_id].to_s.strip }
+ hash[:system].present? ? hash : hash.merge(system: DEFAULT_EXTERNAL_SYSTEM)
elsif entry.present?
- { system: DEFAULT_EXTERNAL_SYSTEM, external_id: entry.to_s.strip }
+ { system: DEFAULT_EXTERNAL_SYSTEM, external_id: entry.to_s }
end
end
+
+ Spree::ExternalReference.normalize_references(entries.compact)
end
def record_external_references(image, references)
diff --git a/spree/core/app/models/concerns/spree/has_external_references.rb b/spree/core/app/models/concerns/spree/has_external_references.rb
index fa182e5f72..18f3d9f251 100644
--- a/spree/core/app/models/concerns/spree/has_external_references.rb
+++ b/spree/core/app/models/concerns/spree/has_external_references.rb
@@ -15,7 +15,7 @@ module Spree
scope :with_external_id, lambda { |system, external_id|
joins(:external_references).where(
spree_external_references: {
- system: system.to_s.strip.downcase,
+ system: Spree::ExternalReference.normalize_system(system),
external_id: external_id.to_s.strip
}
)
@@ -25,7 +25,7 @@ module Spree
# @param system [String, Symbol] the external system's key
# @return [String, nil] the identifier that system knows this record by
def external_id_for(system)
- key = system.to_s.strip.downcase
+ key = Spree::ExternalReference.normalize_system(system)
if external_references.loaded?
external_references.detect { |reference| reference.system == key }&.external_id
@@ -41,7 +41,7 @@ module Spree
# @param metadata [Hash, nil] connector bookkeeping (version, etag, synced at)
# @return [Spree::ExternalReference, nil] nil when the reference was removed
def set_external_id(system, external_id, metadata: nil)
- key = system.to_s.strip.downcase
+ key = Spree::ExternalReference.normalize_system(system)
reference = external_references.for_system(key).first
if external_id.to_s.strip.blank?
@@ -54,7 +54,9 @@ module Spree
reference.external_id = external_id
reference.metadata = metadata if metadata.present?
reference.store ||= external_reference_store
- reference.save!
+ # A connector re-sending what it read is the steady state; an unchanged
+ # reference must not pay the two uniqueness SELECTs a save costs.
+ reference.save! if reference.new_record? || reference.changed?
# Reset rather than reload: the next reader refetches, and a batch of
# writes pays for one SELECT at the end instead of one per system.
external_references.reset
diff --git a/spree/core/app/models/concerns/spree/integration_backed_provider.rb b/spree/core/app/models/concerns/spree/integration_backed_provider.rb
index 14f2cc8dfe..c89e4be2c4 100644
--- a/spree/core/app/models/concerns/spree/integration_backed_provider.rb
+++ b/spree/core/app/models/concerns/spree/integration_backed_provider.rb
@@ -11,6 +11,15 @@ module Spree
extend ActiveSupport::Concern
class_methods do
+ # The registry key a merchant's store preference stores (and, for
+ # pricing, the value written to +spree_line_items.price_source+).
+ # Gems override it to name their system: 'acme_erp', not 'pricing_provider'.
+ #
+ # @return [String]
+ def key
+ name.demodulize.underscore
+ end
+
# The Spree::Integration subclass holding this provider's credentials,
# as a class name string. Internal providers need none.
#
@@ -53,18 +62,18 @@ module Spree
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.
+ #
+ # No memoization: provider instances are built fresh per resolution, so an
+ # instance-level cache never gets a second hit. A provider consulting this
+ # on the catalog read path should do so inside +price_for+ (whose answers
+ # {Spree::Pricing::PriceResolution} caches by +cache_ttl+), not +handles?+.
#
# @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)
+ store&.integrations&.active&.find_by(type: self.class.integration_class)
end
end
end
diff --git a/spree/core/app/models/spree/external_reference.rb b/spree/core/app/models/spree/external_reference.rb
index 41074df7aa..e60c5d09c8 100644
--- a/spree/core/app/models/spree/external_reference.rb
+++ b/spree/core/app/models/spree/external_reference.rb
@@ -19,7 +19,7 @@ module Spree
belongs_to :store, class_name: 'Spree::Store', inverse_of: :external_references
belongs_to :resource, polymorphic: true
- normalizes :system, with: ->(value) { value.to_s.strip.downcase }
+ normalizes :system, with: ->(value) { normalize_system(value) }
normalizes :external_id, with: ->(value) { value.to_s.strip }
# Turns either shape a caller may hold — the `{ system => external_id }`
@@ -32,6 +32,15 @@ module Spree
#
# @param references [Hash, Array<Hash>, nil]
# @return [Array<Hash>] entries with :system, :external_id and optional :metadata
+ # The one statement of what a system key looks like: every lookup and
+ # write normalizes through here, or a writer's key and a reader's key
+ # could disagree about the same row.
+ #
+ # @return [String]
+ def self.normalize_system(value)
+ value.to_s.strip.downcase
+ end
+
def self.normalize_references(references)
return [] if references.blank?
@@ -63,6 +72,6 @@ module Spree
self.whitelisted_ransackable_attributes = %w[system external_id resource_type]
- scope :for_system, ->(system) { where(system: system.to_s.strip.downcase) }
+ scope :for_system, ->(system) { where(system: normalize_system(system)) }
end
end
diff --git a/spree/core/app/models/spree/inventory_provider/base.rb b/spree/core/app/models/spree/inventory_provider/base.rb
index feac71becd..2a0f974dea 100644
--- a/spree/core/app/models/spree/inventory_provider/base.rb
+++ b/spree/core/app/models/spree/inventory_provider/base.rb
@@ -25,20 +25,6 @@ module Spree
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/line_item.rb b/spree/core/app/models/spree/line_item.rb
index a592a41713..dbb26b785c 100644
--- a/spree/core/app/models/spree/line_item.rb
+++ b/spree/core/app/models/spree/line_item.rb
@@ -152,13 +152,10 @@ module Spree
# 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.
+ # persist: false — runs mid-build and from callers that save the record
+ # themselves.
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?
+ reprice(persist: false)
end
# Assigns the price the local catalog gives for this line, with no pricing
@@ -172,13 +169,9 @@ module Spree
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
+ # Through the same writer every resolved price goes through, so the
+ # tax-inclusive restatement inputs are stated once.
+ Spree::Carts::PriceItems.apply([[self, price_record]], persist: false)
end
def copy_tax_category
@@ -383,14 +376,18 @@ module Spree
#
# @return [void]
def recalculate_price
+ reprice(persist: true)
+ end
+
+ private
+
+ def reprice(persist:)
return if owner.blank?
result = Spree::Carts::PriceItems.new.call(cart: owner, line_items: [self])
- Spree::Carts::PriceItems.apply(result.value) if result.success?
+ Spree::Carts::PriceItems.apply(result.value, persist: persist) if result.success?
end
- private
-
def ensure_valid_quantity
self.quantity = 0 if quantity.nil? || quantity < 0
end
diff --git a/spree/core/app/models/spree/pricing_provider/base.rb b/spree/core/app/models/spree/pricing_provider/base.rb
index 6562589695..48ada58ec1 100644
--- a/spree/core/app/models/spree/pricing_provider/base.rb
+++ b/spree/core/app/models/spree/pricing_provider/base.rb
@@ -46,14 +46,6 @@ module Spree
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
index 58043135f7..cf7a98fea7 100644
--- a/spree/core/app/models/spree/pricing_provider/internal.rb
+++ b/spree/core/app/models/spree/pricing_provider/internal.rb
@@ -32,23 +32,13 @@ module Spree
# Returns the best price for the variant
# @return [Spree::Price]
+ # A price-list match wins; the base price (no price_list_id) backstops.
def resolve
- find_best_price
+ find_price_from_lists || find_base_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
diff --git a/spree/core/app/services/spree/carts/check_availability.rb b/spree/core/app/services/spree/carts/check_availability.rb
index 84e055ec2f..2bb20732b3 100644
--- a/spree/core/app/services/spree/carts/check_availability.rb
+++ b/spree/core/app/services/spree/carts/check_availability.rb
@@ -27,15 +27,13 @@ module Spree
end
return success([]) if entries.empty?
+ @cart = cart
@provider = cart&.store&.inventory_provider_instance
- provider = @provider
- return success([]) if provider.blank?
+ return success([]) if @provider.blank?
- internal = provider.is_a?(Spree::InventoryProvider::Internal)
+ @internal = @provider.is_a?(Spree::InventoryProvider::Internal)
- unsupplyable = entries.reject do |variant, quantity|
- supplyable?(variant, quantity, cart: cart, provider: provider, internal: internal)
- end
+ unsupplyable = entries.reject { |variant, quantity| supplyable?(variant, quantity) }
success(unsupplyable)
rescue StandardError => e
@@ -44,10 +42,10 @@ module Spree
private
- def supplyable?(variant, quantity, cart:, provider:, internal:)
- stock_levels = internal ? nil : provider.stock_levels_for(variant)
+ def supplyable?(variant, quantity)
+ stock_levels = @internal ? nil : @provider.stock_levels_for(variant)
- Spree::Stock::Quantifier.new(variant, excluded_order: cart, stock_levels: stock_levels).
+ Spree::Stock::Quantifier.new(variant, excluded_order: @cart, stock_levels: stock_levels).
can_supply?(quantity)
end
diff --git a/spree/core/app/services/spree/carts/price_items.rb b/spree/core/app/services/spree/carts/price_items.rb
index 52b64165fd..9ca23aceb6 100644
--- a/spree/core/app/services/spree/carts/price_items.rb
+++ b/spree/core/app/services/spree/carts/price_items.rb
@@ -28,14 +28,11 @@ module Spree
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]
+ [line_item, price]
end
success(resolutions)
@@ -45,10 +42,25 @@ module Spree
failure(cart, e.message)
end
+ # A stand-in line item for pricing a line that does not exist yet.
+ #
+ # 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 quantity to a row that was never meant to exist. The
+ # cart still rides along (as the association target only) so the
+ # resolution can read the owner without loading anything.
+ #
+ # @return [Spree::LineItem] unsaved, not on the cart's association
+ def self.probe(cart:, variant:, quantity:)
+ Spree::LineItem.new(variant: variant, quantity: quantity, currency: cart.currency).tap do |probe|
+ probe.association(:cart).target = cart
+ end
+ end
+
# Writes resolved prices. Safe inside a transaction — no provider is
# consulted here.
#
- # @param resolutions [Array<Array>] triples from {#call}
+ # @param resolutions [Array<Array>] +[line_item, price]+ pairs from {#call}
# @param persist [Boolean] false assigns without saving, for callers
# that save the record themselves
# @return [void]
@@ -62,7 +74,7 @@ module Spree
owner = resolutions.first.first.owner
vat_inputs = { address: owner&.tax_address, country: owner&.tax_country, market: owner&.market }
- resolutions.each do |line_item, price, source|
+ resolutions.each do |line_item, price|
amount = price.price_including_vat_for(**vat_inputs)
# Marked before the blank guard: the provider has already answered,
# so a restatement that comes back blank must still not send the
@@ -72,7 +84,10 @@ module Spree
line_item.price_resolved = true unless persist
next if amount.blank?
- line_item.assign_attributes(price: amount, price_list_id: price.price_list_id, price_source: source)
+ # 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.
+ line_item.assign_attributes(price: amount, price_list_id: price.price_list_id, price_source: price.price_source)
next unless persist && line_item.persisted? && line_item.changed?
line_item.update_columns(line_item.changes.transform_values(&:last).merge(updated_at: Time.current))
diff --git a/spree/core/app/workflows/spree/carts/add_item.rb b/spree/core/app/workflows/spree/carts/add_item.rb
index ca1a81fe27..c93e5662e5 100644
--- a/spree/core/app/workflows/spree/carts/add_item.rb
+++ b/spree/core/app/workflows/spree/carts/add_item.rb
@@ -124,19 +124,11 @@ module Spree
@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.
+ # 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.
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
+ Spree::Carts::PriceItems.probe(cart: cart, variant: variant, quantity: resulting_quantity)
end
# The amount the pricing step actually resolved, or nil when nothing
@@ -148,8 +140,8 @@ module Spree
def apply_resolved_price
return if @resolved_price.blank?
- _probe, price, source = @resolved_price
- Spree::Carts::PriceItems.apply([[@line_item, price, source]], persist: false)
+ _probe, price = @resolved_price
+ Spree::Carts::PriceItems.apply([[@line_item, price]], persist: false)
end
# What the line will hold once this add is applied. Volume pricing and
diff --git a/spree/core/app/workflows/spree/carts/upsert_items.rb b/spree/core/app/workflows/spree/carts/upsert_items.rb
index a6b7430ba8..297c78bba9 100644
--- a/spree/core/app/workflows/spree/carts/upsert_items.rb
+++ b/spree/core/app/workflows/spree/carts/upsert_items.rb
@@ -121,17 +121,14 @@ module Spree
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)
+ Spree::Carts::PriceItems.probe(cart: cart, variant: item.variant, quantity: item.quantity)
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 }
+ @resolved_prices = Array(result.value).index_by { |probe, _price| probe.variant_id }
end
def additions
@@ -142,8 +139,8 @@ module Spree
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)
+ _probe, price = resolution
+ Spree::Carts::PriceItems.apply([[line_item, price]], persist: false)
end
def resolved_prices