Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
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.rbindex 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 Spreescope.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: statusend+ # 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 ratherdiff --git a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rbindex 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::ExternalReferencesscoped_resource :categories# PATCH /api/v3/admin/categories/:id/repositiondiff --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.rbindex 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::ExternalReferencesinclude Spree::Api::V3::Admin::Concerns::CompanyLocationParamsbefore_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.rbindex 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::ExternalReferencesscoped_resource :customersprotecteddiff --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.rbindex 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::ExternalReferencesinclude Spree::Api::V3::Admin::Concerns::CompanyLocationParamsscoped_resource :customersdiff --git a/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/media_controller.rbindex 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 Spreemodule V3module Adminclass MediaController < ResourceController- include Spree::Api::V3::Admin::Concerns::ExternalReferencesscoped_resource :productsdef creatediff --git a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rbindex 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 Spreemodule V3module Adminclass OrdersController < ResourceController- include Spree::Api::V3::Admin::Concerns::ExternalReferencesinclude Spree::Api::V3::OrderLockscoped_resource :ordersdiff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rbindex 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 Spreemodule V3module Adminclass ProductsController < ResourceController- include Spree::Api::V3::Admin::Concerns::ExternalReferencesinclude Spree::Api::V3::BulkOperationsinclude Spree::Api::V3::Admin::ProductListingdiff --git a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rbindex 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 Spreeinclude Spree::Api::V3::Admin::StoreContextinclude Spree::Api::V3::AdminAuthenticationinclude 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::ExternalReferencesprotecteddiff --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.rbindex 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 Spreedef bulk_upsertauthorize! :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) }enddef store_variantsdiff --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.rbindex 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 Spreemodule V3module Adminclass StockLocationsController < ResourceController- include Spree::Api::V3::Admin::Concerns::ExternalReferencesscoped_resource :stockprotecteddiff --git a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rbindex 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 Spreemodule V3module Adminclass VariantsController < ResourceController- include Spree::Api::V3::Admin::Concerns::ExternalReferencesscoped_resource :productsprotecteddiff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rbindex 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 Spreeendend- # 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_cartend# POST /api/v3/store/carts@@ -101,7 +101,8 @@ module Spreeif result.success?# Signing in hands back a cart built earlier, possibly long ago.- render_cart(sweep: true)+ sweep_unbuyable_lines!+ render_cartelserender_service_error(result.error.to_s)enddiff --git a/spree/core/app/jobs/spree/images/save_from_url_job.rb b/spree/core/app/jobs/spree/images/save_from_url_job.rbindex 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 Spreeimage_scope(viewable).with_external_url(external_url).first || viewable_assets(viewable).newend- # 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 }endend++ Spree::ExternalReference.normalize_references(entries.compact)enddef 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.rbindex 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 Spreescope :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 bydef 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 removeddef 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).firstif external_id.to_s.strip.blank?@@ -54,7 +54,9 @@ module Spreereference.external_id = external_idreference.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.resetdiff --git a/spree/core/app/models/concerns/spree/integration_backed_provider.rb b/spree/core/app/models/concerns/spree/integration_backed_provider.rbindex 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 Spreeextend ActiveSupport::Concernclass_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 Spreeend# 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)endendenddiff --git a/spree/core/app/models/spree/external_reference.rb b/spree/core/app/models/spree/external_reference.rbindex 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 Spreebelongs_to :store, class_name: 'Spree::Store', inverse_of: :external_referencesbelongs_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 Spreeself.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)) }endenddiff --git a/spree/core/app/models/spree/inventory_provider/base.rb b/spree/core/app/models/spree/inventory_provider/base.rbindex 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 Spreeraise 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- endendendenddiff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rbindex 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 Spreeprice_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)enddef 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_quantityself.quantity = 0 if quantity.nil? || quantity < 0enddiff --git a/spree/core/app/models/spree/pricing_provider/base.rb b/spree/core/app/models/spree/pricing_provider/base.rbindex 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 Spreenilend- # 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- endendendenddiff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rbindex 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_priceendprivate- # 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_listsdiff --git a/spree/core/app/services/spree/carts/check_availability.rb b/spree/core/app/services/spree/carts/check_availability.rbindex 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 Spreeendreturn 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 Spreeprivate- 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)enddiff --git a/spree/core/app/services/spree/carts/price_items.rb b/spree/core/app/services/spree/carts/price_items.rbindex 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 Spreeitems = 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]endsuccess(resolutions)@@ -45,10 +42,25 @@ module Spreefailure(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 Spreeowner = resolutions.first.first.ownervat_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 Spreeline_item.price_resolved = true unless persistnext 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.rbindex 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.firstend- # 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 Spreedef apply_resolved_pricereturn 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 anddiff --git a/spree/core/app/workflows/spree/carts/upsert_items.rb b/spree/core/app/workflows/spree/carts/upsert_items.rbindex 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 Spreedef resolve_pricesreturn 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)endresult = 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 }enddef additions@@ -142,8 +139,8 @@ module Spreeresolution = 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)enddef resolved_prices