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.

State each provider rule once

Damian Legawiec9d97921736e8
diff --git a/spree/api/app/controllers/spree/api/v3/admin/concerns/external_references.rb b/spree/api/app/controllers/spree/api/v3/admin/concerns/external_references.rb
index 416b5388e1..2b92c82a5e 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/concerns/external_references.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/concerns/external_references.rb
@@ -96,22 +96,8 @@ module Spree
return @external_reference_params if defined?(@external_reference_params)
raw = params[:external_references]
- return @external_reference_params = [] if raw.blank?
-
raw = raw.to_unsafe_h if raw.respond_to?(:to_unsafe_h)
- entries =
- if raw.is_a?(Hash) && !raw.key?(:system) && !raw.key?('system')
- raw.map { |system, external_id| { system: system, external_id: external_id } }
- else
- Array(raw).map { |entry| entry.respond_to?(:to_unsafe_h) ? entry.to_unsafe_h : entry.to_h }
- end
-
- @external_reference_params = entries.filter_map do |entry|
- entry = entry.to_h.symbolize_keys.slice(:system, :external_id)
- next if entry[:system].blank?
-
- entry
- end
+ @external_reference_params = Spree::ExternalReference.normalize_references(raw)
end
# A member path may address the record by an external identity
@@ -162,8 +148,9 @@ module Spree
return unless resource.respond_to?(:assign_external_references)
return unless resource.persisted?
+ # No reload needed: set_external_id resets the association, so
+ # the serializer's read fetches the fresh rows.
resource.assign_external_references(external_reference_params)
- resource.external_references.reload
rescue ActiveRecord::RecordInvalid => e
# The key already names a different record in this store. The
# resource itself is written by now, so this reports what could
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 6d5b41608e..b4d6e2dd66 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
@@ -125,10 +125,6 @@ module Spree
private
- def bulk_record_count_key
- :stock_level_count
- end
-
def require_stock_levels!
return if params.key?(:stock_levels)
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 9926bbdedf..fa182e5f72 100644
--- a/spree/core/app/models/concerns/spree/has_external_references.rb
+++ b/spree/core/app/models/concerns/spree/has_external_references.rb
@@ -46,7 +46,7 @@ module Spree
if external_id.to_s.strip.blank?
reference&.destroy
- external_references.reload if external_references.loaded?
+ external_references.reset
return nil
end
@@ -55,7 +55,9 @@ module Spree
reference.metadata = metadata if metadata.present?
reference.store ||= external_reference_store
reference.save!
- external_references.reload if external_references.loaded?
+ # 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
reference
end
@@ -67,17 +69,7 @@ module Spree
# @param references [Hash{String,Symbol=>String}, Array<Hash>]
# @return [void]
def assign_external_references(references)
- entries =
- if references.is_a?(Hash) && !references.key?(:system) && !references.key?('system')
- references.map { |system, external_id| { system: system, external_id: external_id } }
- else
- Array(references)
- end
-
- entries.each do |reference|
- reference = reference.to_h.symbolize_keys
- next if reference[:system].blank?
-
+ Spree::ExternalReference.normalize_references(references).each do |reference|
set_external_id(reference[:system], reference[:external_id], metadata: reference[:metadata])
end
end
@@ -86,15 +78,16 @@ module Spree
# A reference belongs to the same store as the record it identifies.
#
- # Store-owning models answer directly (and CompanyLocation delegates).
- # Variants and stock items carry no store of their own and reach it
- # through the product; anything else falls back to the request's store the
- # way {Spree::SingleStoreResource} does.
+ # Store-owning models answer directly (and CompanyLocation delegates);
+ # variants and stock levels carry no store of their own and reach it
+ # through the product. Anything else is left nil here — the reference
+ # includes {Spree::SingleStoreResource}, whose ensure_store callback
+ # falls back to the request's store, and stating that fallback twice
+ # would let the two quietly diverge.
def external_reference_store
return store if respond_to?(:store) && store.present?
- return product.store if respond_to?(:product) && product&.store.present?
- Spree::Current.store
+ product.store if respond_to?(:product) && product&.store.present?
end
end
end
diff --git a/spree/core/app/models/spree/delivery_rate_provider/base.rb b/spree/core/app/models/spree/delivery_rate_provider/base.rb
index 369657c368..081b375552 100644
--- a/spree/core/app/models/spree/delivery_rate_provider/base.rb
+++ b/spree/core/app/models/spree/delivery_rate_provider/base.rb
@@ -12,29 +12,11 @@ module Spree
# External providers resolve credentials through the delivery method's
# store integration — they never store credentials themselves.
class Base
+ include Spree::IntegrationBackedProvider
+
attr_reader :delivery_method
class << self
- # Human-readable name for admin UIs. Provider gems follow the
- # `SpreeEasyPost::DeliveryRateProvider` convention, where demodulizing
- # yields the useless class name ("Delivery Rate Provider") — so 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
-
- # Fulfillment types this provider can quote, so admin UIs narrow the
# Whether this provider quotes real shipments to an address — true
# for carriers, which therefore can only price methods whose
# fulfillment provider ships. The Internal (calculator) provider
@@ -55,27 +37,6 @@ module Spree
false
end
- # 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 UIs hide
- # providers whose integration isn't connected, and DeliveryMethod
- # validates the choice on save. Derived from +integration_class+ so
- # carrier providers get the right answer by declaring only that.
- #
- # @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 carrier services this store can offer, for the admin service
# picker. Fetch them live from the carrier wherever the API allows —
# a hardcoded list shows services the merchant has not enabled and
diff --git a/spree/core/app/models/spree/external_reference.rb b/spree/core/app/models/spree/external_reference.rb
index 606f7a5395..41074df7aa 100644
--- a/spree/core/app/models/spree/external_reference.rb
+++ b/spree/core/app/models/spree/external_reference.rb
@@ -22,6 +22,32 @@ module Spree
normalizes :system, with: ->(value) { value.to_s.strip.downcase }
normalizes :external_id, with: ->(value) { value.to_s.strip }
+ # Turns either shape a caller may hold — the `{ system => external_id }`
+ # map the admin serializers render, or a `[{ system:, external_id: }]`
+ # list — into symbolized entries, dropping any that name no system.
+ #
+ # The single definition of the accepted shapes: the write path
+ # ({Spree::HasExternalReferences#assign_external_references}) and the API
+ # concern's upsert lookup both parse payloads through here.
+ #
+ # @param references [Hash, Array<Hash>, nil]
+ # @return [Array<Hash>] entries with :system, :external_id and optional :metadata
+ def self.normalize_references(references)
+ return [] if references.blank?
+
+ entries =
+ if references.is_a?(Hash) && !references.key?(:system) && !references.key?('system')
+ references.map { |system, external_id| { system: system, external_id: external_id } }
+ else
+ Array(references).map { |entry| entry.respond_to?(:to_unsafe_h) ? entry.to_unsafe_h : entry }
+ end
+
+ entries.filter_map do |entry|
+ entry = entry.to_h.symbolize_keys.slice(:system, :external_id, :metadata)
+ entry[:system].blank? ? nil : entry
+ end
+ end
+
validates :system, :external_id, presence: true
validates :system,
format: { with: /\A[a-z0-9_]+\z/, message: :invalid_system_key },
diff --git a/spree/core/app/models/spree/fulfillment_provider/base.rb b/spree/core/app/models/spree/fulfillment_provider/base.rb
index 3aa9b4b218..759065dd5a 100644
--- a/spree/core/app/models/spree/fulfillment_provider/base.rb
+++ b/spree/core/app/models/spree/fulfillment_provider/base.rb
@@ -5,6 +5,8 @@ module Spree
# time; registered via Spree.fulfillment_providers. Replaces the legacy
# ShipmentHandler name-constantize mechanism.
class Base
+ include Spree::IntegrationBackedProvider
+
class << self
# Behavior predicates — the class hierarchy IS the vocabulary.
# Subclasses override the one that describes their mechanics; admin
@@ -27,47 +29,6 @@ module Spree
false
end
- # Human-readable name for admin UIs. Provider gems follow the
- # `SpreeEasyPost::DeliveryRateProvider` convention, where demodulizing
- # yields the useless class name ("Delivery Rate Provider") — so 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
-
- # The Spree::Integration subclass holding this provider's credentials,
- # as a class name string — same contract as
- # {Spree::DeliveryRateProvider::Base.integration_class}. Providers
- # without external credentials leave it nil.
- #
- # @return [String, nil]
- def integration_class
- nil
- end
-
- # Whether the store can use this provider — false while a carrier
- # provider's integration is unconnected. Admin UIs surface it as a
- # connect prompt rather than hiding the provider, so the merchant can
- # see what a connection would unlock.
- #
- # @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
end
# @return [Boolean] whether the fulfillment may transition to fulfilled
diff --git a/spree/core/app/services/spree/carts/check_availability.rb b/spree/core/app/services/spree/carts/check_availability.rb
index 3c1a0a69de..84e055ec2f 100644
--- a/spree/core/app/services/spree/carts/check_availability.rb
+++ b/spree/core/app/services/spree/carts/check_availability.rb
@@ -27,7 +27,8 @@ module Spree
end
return success([]) if entries.empty?
- provider = cart&.store&.inventory_provider_instance
+ @provider = cart&.store&.inventory_provider_instance
+ provider = @provider
return success([]) if provider.blank?
internal = provider.is_a?(Spree::InventoryProvider::Internal)
@@ -56,7 +57,7 @@ module Spree
store = cart&.store
policy = store&.inventory_failure_policy
Spree::ProviderFailurePolicy.report_fallback(
- kind: 'inventory', provider: store&.inventory_provider_instance&.class&.key,
+ kind: 'inventory', provider: @provider&.class&.key,
store: store, error: error,
policy: policy || Spree::ProviderFailurePolicy::DEFAULT_INVENTORY_POLICY
)
diff --git a/spree/core/app/services/spree/carts/price_items.rb b/spree/core/app/services/spree/carts/price_items.rb
index ba21d86d40..52b64165fd 100644
--- a/spree/core/app/services/spree/carts/price_items.rb
+++ b/spree/core/app/services/spree/carts/price_items.rb
@@ -53,11 +53,17 @@ module Spree
# 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
- )
+ resolutions = Array(resolutions)
+ return if resolutions.empty?
+
+ # One derivation for the batch: every line in a resolution set belongs
+ # to the same cart, and tax_address / tax_country walk associations and
+ # a store preference that would otherwise be re-read per line.
+ 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|
+ 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
# after_save callback back to the provider from inside the caller's
diff --git a/spree/core/app/services/spree/stock_levels/bulk_upsert.rb b/spree/core/app/services/spree/stock_levels/bulk_upsert.rb
index 166aa02cd0..2cae610f9a 100644
--- a/spree/core/app/services/spree/stock_levels/bulk_upsert.rb
+++ b/spree/core/app/services/spree/stock_levels/bulk_upsert.rb
@@ -39,33 +39,6 @@ module Spree
success(stock_level_count: count)
end
- # How much a feed's row moves the shelf, stated once for both the bulk
- # endpoint and the CSV import: a feed reports either the absolute level
- # its system holds, or a relative movement.
- #
- # @param row [Hash] with +adjustment+ or +count_on_hand+
- # @param current [Integer] what Spree holds now
- # @return [Integer, nil] nil when the row states neither
- def self.delta_for(row, current)
- row = row.with_indifferent_access
- return integer!('adjustment', row[:adjustment]) if row[:adjustment].present?
- return nil if row[:count_on_hand].blank?
-
- integer!('count_on_hand', row[:count_on_hand]) - current.to_i
- end
-
- # `to_i` turns "abc" into 0 and "1O" into 1, so a typo in a feed would
- # zero a shelf or set it to a number nobody sent, with no error to notice.
- # A feed must say what it means.
- #
- # @return [Integer]
- # @raise [ArgumentError] when the value is not a whole number
- def self.integer!(column, value)
- Integer(value.to_s.strip, 10)
- rescue ArgumentError, TypeError
- raise ArgumentError, "#{column} must be a whole number, got #{value.inspect}"
- end
-
private
def apply_row(row)
@@ -93,8 +66,27 @@ module Spree
moved
end
+ # How much a feed's row moves the shelf: a feed reports either the
+ # absolute level its system holds, or a relative movement.
+ #
+ # @return [Integer, nil] nil when the row states neither
def delta_for(row, stock_level)
- self.class.delta_for(row, stock_level.count_on_hand)
+ current = stock_level.count_on_hand
+ return integer!('adjustment', row[:adjustment]) if row[:adjustment].present?
+ return nil if row[:count_on_hand].blank?
+
+ integer!('count_on_hand', row[:count_on_hand]) - current.to_i
+ end
+
+ # `to_i` turns "abc" into 0 and "1O" into 1, so a typo in a feed would
+ # zero a shelf or set it to a number nobody sent, with no error to
+ # notice. A feed must say what it means.
+ #
+ # @raise [ArgumentError] when the value is not a whole number
+ def integer!(column, value)
+ Integer(value.to_s.strip, 10)
+ rescue ArgumentError, TypeError
+ raise ArgumentError, "#{column} must be a whole number, got #{value.inspect}"
end
end
end
diff --git a/spree/core/app/workflows/spree/carts/upsert_items.rb b/spree/core/app/workflows/spree/carts/upsert_items.rb
index 7275f84cc7..a6b7430ba8 100644
--- a/spree/core/app/workflows/spree/carts/upsert_items.rb
+++ b/spree/core/app/workflows/spree/carts/upsert_items.rb
@@ -103,6 +103,7 @@ module Spree
# checked by the line item's availability validator on save, and two
# answers that can disagree is worse than one.
def check_availability
+ @unsupplyable_variant_ids = Set.new
return if cart.store.nil? || cart.store.internal_inventory?
return if additions.empty?
@@ -150,7 +151,6 @@ module Spree
end
def unsupplyable?(item)
- @unsupplyable_variant_ids ||= Set.new
@unsupplyable_variant_ids.include?(item.variant.id)
end
diff --git a/spree/core/lib/spree/core/pricing/price_resolution.rb b/spree/core/lib/spree/core/pricing/price_resolution.rb
index 5c6887426c..66d1cdf4cc 100644
--- a/spree/core/lib/spree/core/pricing/price_resolution.rb
+++ b/spree/core/lib/spree/core/pricing/price_resolution.rb
@@ -46,8 +46,6 @@ module Spree
return internal_price unless external_provider?
provider_price
- rescue ProviderUnavailable
- raise
rescue StandardError => e
handle_failure(e)
end