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.

Phase P0.2: Introduce Spree::StockLevel with rename bridges

Łukasz Adamczyk21afc09668a6
diff --git a/docs/plans/6.0-typed-stock-movements.md b/docs/plans/6.0-typed-stock-movements.md
index dd2f36aeb1..3969a91ab0 100644
--- a/docs/plans/6.0-typed-stock-movements.md
+++ b/docs/plans/6.0-typed-stock-movements.md
@@ -362,7 +362,7 @@ Ruby side:
- `Spree::StockLevel` with `has_prefix_id :sl`. `Spree::StockItem = Spree::StockLevel` survives as a **deprecated** constant alias in its own file, the same shape `spree/core/app/models/spree/shipment.rb` already uses for `Spree::Shipment = Fulfillment`, with a comment naming 6.1 as its removal. Phase 5 deletes it.
- Associations renamed with deprecated aliases for one release: `Variant#stock_levels`, `StockLocation#stock_levels`, `Store#stock_levels`, `StockMovement#stock_level`, `StockReservation#stock_level`, plus `StockLocation#stock_level_or_create` and `#set_up_stock_level`.
- `alias_attribute :stock_item_id, :stock_level_id` on movements and reservations, so an integration still writing the old key keeps working through 6.0.
-- `publishes_lifecycle_events` learns a `legacy_event_prefix:` option, and StockLevel declares `stock_item` — the three lifecycle events dual-emit under both names, mirroring how `Fulfillment::CustomEvents` dual-emits `shipment.*`. A declarative option rather than three hand-written twins, because the next rename needs the same thing.
+- `Spree::StockLevel::CustomEvents` wraps `publish_event` so the three lifecycle events dual-emit under both names, exactly as `Fulfillment::CustomEvents` already dual-emits `shipment.*` (decision revised 2026-08-17). The earlier draft put a `legacy_event_prefix:` option on `publishes_lifecycle_events`; that is generic machinery on a concern every Spree model includes, bought for a single rename, so it was reverted. The twins do not live in the `Spree::StockItem` alias file either, tempting as that is for keeping the bridges together: `app/` is autoloaded lazily, so with `eager_load = false` the file would go untouched and the legacy events would fire in production and silently not in development. Wrapping `publish_event` rather than the three callbacks keeps Publishable's touch-only guard authoritative — the legacy twin follows whatever the real name did.
- The Ransack allowlists, the `:stock` permission subject list, the factory (`:stock_level`, with `:stock_item` kept as an alias for external specs), and the `activerecord.models` and admin-label i18n keys.
API and TypeScript side:
@@ -462,13 +462,13 @@ Held to 6.1 for the reason every other 6.0 cleanup is: the columns are the data
| Bridge | Removal |
|---|---|
| `Spree::StockItem = Spree::StockLevel` constant alias | Delete `spree/core/app/models/spree/stock_item.rb`. Host apps and extensions still naming the old constant break at boot, which is the point — a `NameError` at boot beats a silent reference to a class that no longer describes the data. |
-| Dual-emitted `stock_item.created` / `.updated` / `.deleted` | Drop `legacy_event_prefix:` from `StockLevel`'s `publishes_lifecycle_events` call. Endpoints still subscribed to the legacy names stop receiving deliveries, so the 6.1 upgrade guide has to say so plainly and the 6.0 guide has to have said it a release earlier. |
+| Dual-emitted `stock_item.created` / `.updated` / `.deleted` | Delete `spree/core/app/models/spree/stock_level/custom_events.rb` and its `include`. Endpoints still subscribed to the legacy names stop receiving deliveries, so the 6.1 upgrade guide has to say so plainly and the 6.0 guide has to have said it a release earlier. |
| `stock_items` / `stock_item` association aliases, `stock_item_or_create`, `set_up_stock_item` | Delete the aliases and their deprecation warnings. |
| `alias_attribute :stock_item_id, :stock_level_id` on movements and reservations | Delete. Writes using the old key start raising instead of resolving. |
| `stock_item_serializer` / `admin_stock_item_serializer` registry keys | Drop from the legacy-key map. |
| `:stock_item` factory alias | Delete — external specs move to `:stock_level`. |
-The `legacy_event_prefix:` option itself stays. It is generic machinery for the next rename, not scaffolding for this one, and removing the declaration is what stops the twins.
+Nothing generic survives this bridge: the twins are three lines in a model-owned concern, so deleting that file is the whole removal. A future rename writes its own, the way `Fulfillment::CustomEvents` did before it — one rename is not enough evidence to design an abstraction every Spree model carries.
Two things that are **not** bridges and therefore have nothing to remove here: the `si_` → `sl_` prefix and the `/stock_items` endpoint both broke cleanly in Phase 0.
diff --git a/spree/core/app/models/spree/stock_item.rb b/spree/core/app/models/spree/stock_item.rb
index 5e38e7914e..f624670832 100644
--- a/spree/core/app/models/spree/stock_item.rb
+++ b/spree/core/app/models/spree/stock_item.rb
@@ -1,148 +1,5 @@
module Spree
- class StockItem < Spree.base_class
- has_prefix_id :si
-
- acts_as_paranoid
-
- include Spree::HasCustomFields
- include Spree::Metadata
-
- publishes_lifecycle_events
-
- with_options inverse_of: :stock_items do
- belongs_to :stock_location, class_name: 'Spree::StockLocation'
- belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'
- end
- has_many :stock_movements, inverse_of: :stock_item
- has_many :stock_reservations, class_name: 'Spree::StockReservation', inverse_of: :stock_item, dependent: :destroy
- has_many :active_stock_reservations, -> { active }, class_name: 'Spree::StockReservation', inverse_of: :stock_item
-
- validates :stock_location, :variant, presence: true
- validates :variant_id, uniqueness: { scope: :stock_location_id }, unless: :deleted_at
-
- validates :count_on_hand, numericality: {
- greater_than_or_equal_to: 0,
- less_than_or_equal_to: 2**31 - 1,
- only_integer: true
- }, if: :verify_count_on_hand?
-
- delegate :weight, :should_track_inventory?, to: :variant
- delegate :name, to: :variant, prefix: true
- delegate :product, to: :variant
-
- after_save :conditional_variant_touch, if: :saved_changes?
- after_touch { variant.touch }
- after_destroy { variant.touch }
-
- self.whitelisted_ransackable_attributes = %w[count_on_hand stock_location_id variant_id]
- self.whitelisted_ransackable_associations = %w[variant stock_location]
-
- scope :with_active_stock_location, -> { joins(:stock_location).merge(Spree::StockLocation.active) }
-
- # Stock items for products assigned to `store`. Walks
- # `variant → product → stores`, dedups via `distinct` so a product
- # in multiple stores doesn't double-count its stock items.
- #
- # Used by the admin API as the base scope (`StockItem.for_store`)
- # so the controller can filter directly by stock_location/variant
- # without inheriting `Spree::Store#stock_items`'s extra joins or
- # the variant default ordering.
- scope :for_store, ->(store) {
- joins(variant: :product).where(spree_products: { store_id: store.id })
- }
-
- def backordered_inventory_units
- Spree::InventoryUnit.backordered_for_stock_item(self)
- end
-
- def adjust_count_on_hand(value)
- with_lock do
- set_count_on_hand(count_on_hand + value)
- end
- end
-
- def set_count_on_hand(value)
- self.count_on_hand = value
- process_backorders(count_on_hand - count_on_hand_was)
-
- save!
- end
-
- def in_stock?
- count_on_hand > 0
- end
-
- # Tells whether it's available to be included in a shipment
- def available?
- in_stock? || backorderable?
- end
-
- # Units already allocated to pending shipments at this stock item.
- #
- # Always returns 0 in Spree 5.5. The 6.0 Typed Stock Movements plan
- # (see docs/plans/6.0-typed-stock-movements.md) adds an indexed
- # `allocated_count` column updated by typed movements (`allocated`,
- # `released`, `shipped`); the Rails column accessor then takes
- # precedence over this method automatically.
- #
- # @return [Integer]
- def allocated_count
- 0
- end
-
- # Physical stock minus allocated units at this stock item. Distinct from
- # {Spree::Stock::Quantifier#available_stock}, which sums this across all
- # stock items belonging to a variant.
- #
- # @return [Integer]
- def available_count
- count_on_hand - allocated_count
- end
-
- def reduce_count_on_hand_to_zero
- set_count_on_hand(0) if count_on_hand > 0
- end
-
- private
-
- def verify_count_on_hand?
- count_on_hand_changed? && !backorderable? && !variant.preorder? &&
- (count_on_hand < count_on_hand_was) && (count_on_hand < 0)
- end
-
- # Process backorders based on amount of stock received
- # If stock was -20 and is now -15 (increase of 5 units), then we can process atmost 5 inventory orders.
- # If stock was -20 but then was -25 (decrease of 5 units), do nothing.
- def process_backorders(number)
- return unless number.positive?
-
- units = backordered_inventory_units.first(number) # We can process atmost n backorders
-
- units.each do |unit|
- break unless number.positive?
-
- if unit.quantity > number
- # if required quantity is greater than available
- # split off and fulfill that
- split = unit.split_inventory!(number)
- split.fill_backorder
- else
- unit.fill_backorder
- end
- number -= unit.quantity
- end
- end
-
- def conditional_variant_touch
- variant.touch if !Spree::Config.binary_inventory_cache || stock_changed?
- end
-
- def stock_changed?
- # the variant_id changes from nil when a new stock location is added
- (
- saved_change_to_count_on_hand? &&
- saved_change_to_count_on_hand.any?(&:zero?)
- ) || saved_change_to_variant_id?
- end
- end
+ # Constant alias for the legacy Spree::StockItem, renamed to
+ # Spree::StockLevel in 6.0. Remove in 6.1.
+ StockItem = StockLevel
end
diff --git a/spree/core/app/models/spree/stock_level.rb b/spree/core/app/models/spree/stock_level.rb
new file mode 100644
index 0000000000..9d1ff86254
--- /dev/null
+++ b/spree/core/app/models/spree/stock_level.rb
@@ -0,0 +1,149 @@
+module Spree
+ class StockLevel < Spree.base_class
+ has_prefix_id :sl
+
+ acts_as_paranoid
+
+ include Spree::HasCustomFields
+ include Spree::Metadata
+ # Dual-emits the pre-rename `stock_item.*` names for one release.
+ include Spree::StockLevel::CustomEvents
+
+ publishes_lifecycle_events
+
+ with_options inverse_of: :stock_items do
+ belongs_to :stock_location, class_name: 'Spree::StockLocation'
+ belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'
+ end
+ has_many :stock_movements, inverse_of: :stock_level
+ has_many :stock_reservations, class_name: 'Spree::StockReservation', inverse_of: :stock_level, dependent: :destroy
+ has_many :active_stock_reservations, -> { active }, class_name: 'Spree::StockReservation', inverse_of: :stock_level
+
+ validates :stock_location, :variant, presence: true
+ validates :variant_id, uniqueness: { scope: :stock_location_id }, unless: :deleted_at
+
+ validates :count_on_hand, numericality: {
+ greater_than_or_equal_to: 0,
+ less_than_or_equal_to: 2**31 - 1,
+ only_integer: true
+ }, if: :verify_count_on_hand?
+
+ delegate :weight, :should_track_inventory?, to: :variant
+ delegate :name, to: :variant, prefix: true
+ delegate :product, to: :variant
+
+ after_save :conditional_variant_touch, if: :saved_changes?
+ after_touch { variant.touch }
+ after_destroy { variant.touch }
+
+ self.whitelisted_ransackable_attributes = %w[count_on_hand stock_location_id variant_id]
+ self.whitelisted_ransackable_associations = %w[variant stock_location]
+
+ scope :with_active_stock_location, -> { joins(:stock_location).merge(Spree::StockLocation.active) }
+
+ # Stock levels for products assigned to `store`, walking
+ # `variant → product → store`.
+ #
+ # Used by the admin API as the base scope so the controller can filter
+ # directly by stock_location/variant without inheriting
+ # `Spree::Store#stock_levels`'s extra joins or the variant default
+ # ordering.
+ scope :for_store, ->(store) {
+ joins(variant: :product).where(spree_products: { store_id: store.id })
+ }
+
+ def backordered_inventory_units
+ Spree::InventoryUnit.backordered_for_stock_item(self)
+ end
+
+ def adjust_count_on_hand(value)
+ with_lock do
+ set_count_on_hand(count_on_hand + value)
+ end
+ end
+
+ def set_count_on_hand(value)
+ self.count_on_hand = value
+ process_backorders(count_on_hand - count_on_hand_was)
+
+ save!
+ end
+
+ def in_stock?
+ count_on_hand > 0
+ end
+
+ # Tells whether it's available to be included in a shipment
+ def available?
+ in_stock? || backorderable?
+ end
+
+ # Units already allocated to pending shipments at this stock item.
+ #
+ # Always returns 0 in Spree 5.5. The 6.0 Typed Stock Movements plan
+ # (see docs/plans/6.0-typed-stock-movements.md) adds an indexed
+ # `allocated_count` column updated by typed movements (`allocated`,
+ # `released`, `shipped`); the Rails column accessor then takes
+ # precedence over this method automatically.
+ #
+ # @return [Integer]
+ def allocated_count
+ 0
+ end
+
+ # Physical stock minus allocated units at this stock item. Distinct from
+ # {Spree::Stock::Quantifier#available_stock}, which sums this across all
+ # stock items belonging to a variant.
+ #
+ # @return [Integer]
+ def available_count
+ count_on_hand - allocated_count
+ end
+
+ def reduce_count_on_hand_to_zero
+ set_count_on_hand(0) if count_on_hand > 0
+ end
+
+ private
+
+ def verify_count_on_hand?
+ count_on_hand_changed? && !backorderable? && !variant.preorder? &&
+ (count_on_hand < count_on_hand_was) && (count_on_hand < 0)
+ end
+
+ # Process backorders based on amount of stock received
+ # If stock was -20 and is now -15 (increase of 5 units), then we can process atmost 5 inventory orders.
+ # If stock was -20 but then was -25 (decrease of 5 units), do nothing.
+ def process_backorders(number)
+ return unless number.positive?
+
+ units = backordered_inventory_units.first(number) # We can process atmost n backorders
+
+ units.each do |unit|
+ break unless number.positive?
+
+ if unit.quantity > number
+ # if required quantity is greater than available
+ # split off and fulfill that
+ split = unit.split_inventory!(number)
+ split.fill_backorder
+ else
+ unit.fill_backorder
+ end
+ number -= unit.quantity
+ end
+ end
+
+ def conditional_variant_touch
+ variant.touch if !Spree::Config.binary_inventory_cache || stock_changed?
+ end
+
+ def stock_changed?
+ # the variant_id changes from nil when a new stock location is added
+ (
+ saved_change_to_count_on_hand? &&
+ saved_change_to_count_on_hand.any?(&:zero?)
+ ) || saved_change_to_variant_id?
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/stock_level/custom_events.rb b/spree/core/app/models/spree/stock_level/custom_events.rb
new file mode 100644
index 0000000000..ce9d64334e
--- /dev/null
+++ b/spree/core/app/models/spree/stock_level/custom_events.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module Spree
+ class StockLevel < Spree.base_class
+ # Dual-emits the pre-6.0 `stock_item.*` lifecycle events beside the
+ # `stock_level.*` ones, so a webhook endpoint a merchant configured against
+ # the old names keeps receiving deliveries for one release. Removed in 6.1,
+ # the same way {Spree::Fulfillment::CustomEvents} carries `shipment.*`.
+ #
+ # The twins are written here rather than as an option on
+ # {Spree::Publishable} because one rename does not need generic machinery
+ # on a concern every Spree model includes — and rather than in the
+ # `Spree::StockItem` alias file because that is autoloaded lazily, which
+ # would leave the events firing in production and silently not in
+ # development.
+ module CustomEvents
+ LEGACY_EVENT_PREFIX = 'stock_item'
+ LEGACY_EVENT_SUFFIXES = %w[created updated deleted].freeze
+
+ # Wraps publishing rather than the three callbacks that call it, so the
+ # decisions Publishable makes — whether events are enabled at all,
+ # whether a touch-only update is worth announcing — are made once and the
+ # legacy twin simply follows whatever the new name did.
+ def publish_event(event_name, payload = nil, metadata = {})
+ published = super
+
+ legacy_name = legacy_event_name(event_name)
+ return published if legacy_name.nil?
+
+ super(legacy_name, payload, metadata)
+
+ published
+ end
+
+ private
+
+ # @return [String, nil] the pre-6.0 name for a lifecycle event, or nil
+ # for anything else this model publishes
+ def legacy_event_name(event_name)
+ prefix, _, suffix = event_name.to_s.rpartition('.')
+ return unless prefix == event_prefix
+ return unless LEGACY_EVENT_SUFFIXES.include?(suffix)
+
+ "#{LEGACY_EVENT_PREFIX}.#{suffix}"
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/stock_location.rb b/spree/core/app/models/spree/stock_location.rb
index 99ee503ce6..a6faf5cb10 100644
--- a/spree/core/app/models/spree/stock_location.rb
+++ b/spree/core/app/models/spree/stock_location.rb
@@ -21,7 +21,7 @@ module Spree
has_many :fulfillments, class_name: 'Spree::Fulfillment'
has_many :shipments, class_name: 'Spree::Fulfillment', foreign_key: :stock_location_id, deprecated: true
- has_many :stock_items, dependent: :delete_all, inverse_of: :stock_location
+ has_many :stock_items, class_name: 'Spree::StockLevel', dependent: :delete_all, inverse_of: :stock_location
has_many :variants, through: :stock_items
has_many :stock_movements, through: :stock_items
diff --git a/spree/core/app/models/spree/stock_movement.rb b/spree/core/app/models/spree/stock_movement.rb
index 92e302f67e..151a153479 100644
--- a/spree/core/app/models/spree/stock_movement.rb
+++ b/spree/core/app/models/spree/stock_movement.rb
@@ -11,13 +11,15 @@ module Spree
publishes_lifecycle_events
- belongs_to :stock_item, class_name: 'Spree::StockItem', inverse_of: :stock_movements
+ belongs_to :stock_level, class_name: 'Spree::StockLevel', inverse_of: :stock_movements
belongs_to :originator, polymorphic: true
- after_create :update_stock_item_quantity
+ alias_attribute :stock_item_id, :stock_level_id
+
+ after_create :update_stock_level_quantity
with_options presence: true do
- validates :stock_item
+ validates :stock_level
validates :quantity, numericality: {
greater_than_or_equal_to: :min_quantity,
less_than_or_equal_to: QUANTITY_LIMITS[:max],
@@ -27,28 +29,40 @@ module Spree
scope :recent, -> { order(created_at: :desc) }
- delegate :variant, :variant_id, to: :stock_item, allow_nil: true
+ delegate :variant, :variant_id, to: :stock_level, allow_nil: true
delegate :product, to: :variant
- self.whitelisted_ransackable_attributes = %w[quantity action created_at stock_item_id originator_type]
- self.whitelisted_ransackable_associations = %w[stock_item]
+ self.whitelisted_ransackable_attributes = %w[quantity action created_at stock_level_id originator_type]
+ self.whitelisted_ransackable_associations = %w[stock_level]
def readonly?
persisted?
end
+ # @deprecated Use {#stock_level}; removed in 6.1.
+ def stock_item
+ Spree::Deprecation.warn('Spree::StockMovement#stock_item is deprecated and will be removed in Spree 6.1. Use #stock_level instead.')
+ stock_level
+ end
+
+ # @deprecated Use {#stock_level=}; removed in 6.1.
+ def stock_item=(record)
+ Spree::Deprecation.warn('Spree::StockMovement#stock_item= is deprecated and will be removed in Spree 6.1. Use #stock_level= instead.')
+ self.stock_level = record
+ end
+
private
- def update_stock_item_quantity
- return unless stock_item.should_track_inventory?
+ def update_stock_level_quantity
+ return unless stock_level.should_track_inventory?
- stock_item.adjust_count_on_hand quantity
+ stock_level.adjust_count_on_hand quantity
end
def min_quantity
- return QUANTITY_LIMITS[:min] if stock_item.nil? || stock_item.backorderable?
+ return QUANTITY_LIMITS[:min] if stock_level.nil? || stock_level.backorderable?
- -stock_item.count_on_hand
+ -stock_level.count_on_hand
end
end
end
diff --git a/spree/core/app/models/spree/stock_movement/custom_events.rb b/spree/core/app/models/spree/stock_movement/custom_events.rb
index e7decfd267..9afc1bfbf2 100644
--- a/spree/core/app/models/spree/stock_movement/custom_events.rb
+++ b/spree/core/app/models/spree/stock_movement/custom_events.rb
@@ -37,7 +37,7 @@ module Spree
end
def product
- stock_item.variant.product
+ stock_level.variant.product
end
end
end
diff --git a/spree/core/app/models/spree/stock_reservation.rb b/spree/core/app/models/spree/stock_reservation.rb
index c2c3f85536..e5d19a0f19 100644
--- a/spree/core/app/models/spree/stock_reservation.rb
+++ b/spree/core/app/models/spree/stock_reservation.rb
@@ -4,15 +4,17 @@ module Spree
publishes_lifecycle_events
- belongs_to :stock_item, class_name: 'Spree::StockItem', inverse_of: :stock_reservations
+ belongs_to :stock_level, class_name: 'Spree::StockLevel', inverse_of: :stock_reservations
belongs_to :line_item, class_name: 'Spree::LineItem', inverse_of: :stock_reservations
belongs_to :order, class_name: 'Spree::Order', inverse_of: :stock_reservations, optional: true
belongs_to :cart, class_name: 'Spree::Cart', inverse_of: :stock_reservations, optional: true
- validates :stock_item, :line_item, :quantity, :expires_at, presence: true
+ alias_attribute :stock_item_id, :stock_level_id
+
+ validates :stock_level, :line_item, :quantity, :expires_at, presence: true
validate :exactly_one_owner
validates :quantity, numericality: { greater_than: 0, only_integer: true }, presence: true
- validates :line_item_id, uniqueness: { scope: :stock_item_id }, presence: true
+ validates :line_item_id, uniqueness: { scope: :stock_level_id }, presence: true
scope :active, -> { where('spree_stock_reservations.expires_at > ?', Time.current) }
scope :expired, -> { where('spree_stock_reservations.expires_at <= ?', Time.current) }
@@ -21,14 +23,26 @@ module Spree
joins(:order).where(spree_orders: { store_id: store.id })
}
- self.whitelisted_ransackable_attributes = %w[stock_item_id line_item_id order_id quantity expires_at]
- self.whitelisted_ransackable_associations = %w[stock_item line_item order]
+ self.whitelisted_ransackable_attributes = %w[stock_level_id line_item_id order_id quantity expires_at]
+ self.whitelisted_ransackable_associations = %w[stock_level line_item order]
# @return [Spree::Cart, Spree::Order, nil]
def owner
order || cart
end
+ # @deprecated Use {#stock_level}; removed in 6.1.
+ def stock_item
+ Spree::Deprecation.warn('Spree::StockReservation#stock_item is deprecated and will be removed in Spree 6.1. Use #stock_level instead.')
+ stock_level
+ end
+
+ # @deprecated Use {#stock_level=}; removed in 6.1.
+ def stock_item=(record)
+ Spree::Deprecation.warn('Spree::StockReservation#stock_item= is deprecated and will be removed in Spree 6.1. Use #stock_level= instead.')
+ self.stock_level = record
+ end
+
# Bridge for legacy callers assigning +current_order+ (now a Spree::Cart)
# to the order association — routes carts to the cart FK instead.
def order=(record)
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 27af1ef920..917c748119 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -133,7 +133,7 @@ module Spree
has_many :products, class_name: 'Spree::Product', dependent: :nullify
has_many :product_publications, through: :channels, source: :publications, class_name: 'Spree::ProductPublication'
has_many :variants, through: :products, class_name: 'Spree::Variant', source: :variants
- has_many :stock_items, through: :variants, class_name: 'Spree::StockItem'
+ has_many :stock_items, through: :variants, class_name: 'Spree::StockLevel'
has_many :prices, through: :variants, class_name: 'Spree::Price'
has_many :price_lists, class_name: 'Spree::PriceList', inverse_of: :store
has_many :fulfillment_items, through: :variants, class_name: 'Spree::FulfillmentItem'
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index 334d2756b5..fa6d5e974b 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -36,7 +36,7 @@ module Spree
with_options inverse_of: :variant do
has_many :fulfillment_items, class_name: 'Spree::FulfillmentItem'
has_many :line_items
- has_many :stock_items, dependent: :destroy, autosave: true
+ has_many :stock_items, class_name: 'Spree::StockLevel', dependent: :destroy, autosave: true
end
has_many :inventory_units, class_name: 'Spree::FulfillmentItem', inverse_of: :variant, deprecated: true
@@ -100,8 +100,8 @@ module Spree
after_create :increment_product_variant_count
after_destroy :decrement_product_variant_count
- scope :in_stock, -> { left_joins(:stock_items).where("#{Spree::Variant.table_name}.track_inventory = ? OR #{Spree::StockItem.table_name}.count_on_hand > ?", false, 0) }
- scope :backorderable, -> { left_joins(:stock_items).where(spree_stock_items: { backorderable: true }) }
+ scope :in_stock, -> { left_joins(:stock_items).where("#{Spree::Variant.table_name}.track_inventory = ? OR #{Spree::StockLevel.table_name}.count_on_hand > ?", false, 0) }
+ scope :backorderable, -> { left_joins(:stock_items).where(Spree::StockLevel.table_name => { backorderable: true }) }
scope :in_stock_or_backorderable, -> { in_stock.or(backorderable) }
scope :eligible, -> { all }
diff --git a/spree/core/lib/spree/testing_support/factories/stock_item_factory.rb b/spree/core/lib/spree/testing_support/factories/stock_level_factory.rb
similarity index 53%
rename from spree/core/lib/spree/testing_support/factories/stock_item_factory.rb
rename to spree/core/lib/spree/testing_support/factories/stock_level_factory.rb
index 06111be818..5d27e34337 100644
--- a/spree/core/lib/spree/testing_support/factories/stock_item_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/stock_level_factory.rb
@@ -1,15 +1,17 @@
FactoryBot.define do
- factory :stock_item, class: Spree::StockItem do
+ # :stock_item is the pre-6.0 name, kept for one release so host-app factories
+ # and specs written against it keep working.
+ factory :stock_level, class: Spree::StockLevel, aliases: [:stock_item] do
backorderable { true }
stock_location
variant
- before(:create) do |stock_item|
+ before(:create) do |stock_level|
# Use really_destroy! (hard delete) to avoid unique index conflicts
# with deleted_at timestamps in MySQL when tests run quickly
- Spree::StockItem.where(
- variant_id: stock_item.variant_id,
- stock_location_id: stock_item.stock_location_id
+ Spree::StockLevel.where(
+ variant_id: stock_level.variant_id,
+ stock_location_id: stock_level.stock_location_id
).delete_all
end
diff --git a/spree/core/spec/models/spree/stock_item_spec.rb b/spree/core/spec/models/spree/stock_level_spec.rb
similarity index 84%
rename from spree/core/spec/models/spree/stock_item_spec.rb
rename to spree/core/spec/models/spree/stock_level_spec.rb
index 8f6e43097d..94cdc6aee6 100644
--- a/spree/core/spec/models/spree/stock_item_spec.rb
+++ b/spree/core/spec/models/spree/stock_level_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::StockItem, type: :model do
+describe Spree::StockLevel, type: :model do
subject { stock_location.stock_items.order(:id).first }
let(:stock_location) { create(:stock_location_with_items) }
@@ -8,6 +8,84 @@ describe Spree::StockItem, type: :model do
it_behaves_like 'metadata'
it_behaves_like 'lifecycle events'
+ # The rename would otherwise silently unsubscribe every webhook endpoint a
+ # merchant had pointed at stock_item.*. Both names ship for one release.
+ describe 'legacy stock_item events', events: true do
+ let!(:stock_level) { create(:stock_level) }
+
+ before do
+ Spree::Events.reset!
+ allow(Spree::Events).to receive(:enabled?).and_return(true)
+ end
+
+ after { Spree::Events.reset! }
+
+ # One subscription set per example: calling this twice would count every
+ # event twice over.
+ def names_published
+ received = []
+ %w[stock_level stock_item].each do |prefix|
+ %w[created updated deleted].each do |suffix|
+ Spree::Events.subscribe("#{prefix}.#{suffix}", async: false) { |event| received << event.name }
+ end
+ end
+ Spree::Events.activate!
+ yield
+ received
+ end
+
+ # Creating a level propagates more of them across the store's locations,
+ # so what matters is that the two names come out in step.
+ it 'publishes created under both names' do
+ names = names_published { create(:stock_level) }
+
+ expect(names).to include('stock_level.created', 'stock_item.created')
+ expect(names.count('stock_item.created')).to eq(names.count('stock_level.created'))
+ end
+
+ it 'publishes updated under both names' do
+ names = names_published { stock_level.update!(backorderable: !stock_level.backorderable) }
+
+ expect(names).to contain_exactly('stock_level.updated', 'stock_item.updated')
+ end
+
+ it 'publishes deleted under both names' do
+ names = names_published { stock_level.destroy! }
+
+ expect(names).to contain_exactly('stock_level.deleted', 'stock_item.deleted')
+ end
+
+ it 'carries the same payload on both' do
+ payloads = {}
+ %w[stock_level.created stock_item.created].each do |name|
+ Spree::Events.subscribe(name, async: false) { |event| payloads[name] = event.payload }
+ end
+ Spree::Events.activate!
+
+ create(:stock_level)
+
+ expect(payloads['stock_item.created']).to eq(payloads['stock_level.created'])
+ end
+
+ # The legacy twin follows whatever the real name did, so the touch-only
+ # guard in Publishable is not defeated by publishing around it.
+ it 'stays silent on a touch-only save' do
+ names = names_published { stock_level.touch }
+
+ expect(names).to be_empty
+ end
+
+ it 'leaves events this model does not own alone' do
+ received = []
+ Spree::Events.subscribe('stock_item.custom', async: false) { |event| received << event.name }
+ Spree::Events.activate!
+
+ stock_level.publish_event('stock_level.custom')
+
+ expect(received).to be_empty
+ end
+ end
+
it 'maintains the count on hand for a variant' do
expect(subject.count_on_hand).to eq 10
end
@@ -62,7 +140,7 @@ describe Spree::StockItem, type: :model do
let!(:current_on_hand) { subject.count_on_hand }
it 'is updated pessimistically' do
- copy = Spree::StockItem.find(subject.id)
+ copy = Spree::StockLevel.find(subject.id)
subject.adjust_count_on_hand(5)
expect(subject.count_on_hand).to eq(current_on_hand + 5)
@@ -144,7 +222,7 @@ describe Spree::StockItem, type: :model do
let!(:current_on_hand) { subject.count_on_hand }
it 'is updated pessimistically' do
- copy = Spree::StockItem.find(subject.id)
+ copy = Spree::StockLevel.find(subject.id)
subject.set_count_on_hand(5)
expect(subject.count_on_hand).to eq(5)
@@ -183,7 +261,7 @@ describe Spree::StockItem, type: :model do
end
context 'with stock movements' do
- before { Spree::StockMovement.create(stock_item: subject, quantity: 1) }
+ before { Spree::StockMovement.create(stock_level: subject, quantity: 1) }
it 'doesnt raise ReadOnlyRecord error' do
expect { subject.destroy }.not_to raise_error
@@ -462,7 +540,7 @@ describe Spree::StockItem, type: :model do
describe 'scopes' do
context '.with_active_stock_location' do
- let(:stock_items_with_active_location) { Spree::StockItem.with_active_stock_location }
+ let(:stock_items_with_active_location) { Spree::StockLevel.with_active_stock_location }
context 'when stock location is active' do
before { stock_location.update_column(:active, true) }
diff --git a/spree/core/spec/models/spree/stock_movement_spec.rb b/spree/core/spec/models/spree/stock_movement_spec.rb
index d06949a4a5..019630c3ee 100644
--- a/spree/core/spec/models/spree/stock_movement_spec.rb
+++ b/spree/core/spec/models/spree/stock_movement_spec.rb
@@ -56,7 +56,7 @@ describe Spree::StockMovement, type: :model do
describe 'whitelisted ransackable attributes' do
it 'returns amount attribute' do
- expect(Spree::StockMovement.whitelisted_ransackable_attributes).to eq(%w[quantity action created_at stock_item_id originator_type])
+ expect(Spree::StockMovement.whitelisted_ransackable_attributes).to eq(%w[quantity action created_at stock_level_id originator_type])
end
end
@@ -81,7 +81,7 @@ describe Spree::StockMovement, type: :model do
end
end
- describe '#update_stock_item_quantity' do
+ describe '#update_stock_level_quantity' do
context 'when track inventory levels is false' do
before do
stub_store_preferences(track_inventory_levels: false)
diff --git a/spree/core/spec/models/spree/stock_reservation_spec.rb b/spree/core/spec/models/spree/stock_reservation_spec.rb
index f9b842a80f..7a82303780 100644
--- a/spree/core/spec/models/spree/stock_reservation_spec.rb
+++ b/spree/core/spec/models/spree/stock_reservation_spec.rb
@@ -2,7 +2,7 @@ require 'spec_helper'
describe Spree::StockReservation, type: :model do
describe 'associations' do
- it { is_expected.to belong_to(:stock_item).class_name('Spree::StockItem').without_validating_presence }
+ it { is_expected.to belong_to(:stock_level).class_name('Spree::StockLevel').without_validating_presence }
it { is_expected.to belong_to(:line_item).class_name('Spree::LineItem').without_validating_presence }
it { is_expected.to belong_to(:order).class_name('Spree::Order').without_validating_presence }
end
@@ -25,11 +25,11 @@ describe Spree::StockReservation, type: :model do
expect(reservation).to be_valid
end
- it 'enforces uniqueness of line_item per stock_item' do
+ it 'enforces uniqueness of line_item per stock_level' do
reservation.save!
duplicate = build(
:stock_reservation,
- stock_item: reservation.stock_item,
+ stock_level: reservation.stock_level,
line_item: reservation.line_item,
order: reservation.order
)
@@ -105,7 +105,7 @@ describe Spree::StockReservation, type: :model do
it 'is destroyed when its stock item is destroyed' do
reservation
- expect { reservation.stock_item.destroy }.to change(Spree::StockReservation, :count).by(-1)
+ expect { reservation.stock_level.destroy }.to change(Spree::StockReservation, :count).by(-1)
end
end
end