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
Address review feedback on the stock level rename
Łukasz Adamczyk930963194e9f
diff --git a/.changeset/stock-item-renamed-to-stock-level.md b/.changeset/stock-item-renamed-to-stock-level.mdindex 0385e50032..5e06128aec 100644--- a/.changeset/stock-item-renamed-to-stock-level.md+++ b/.changeset/stock-item-renamed-to-stock-level.md@@ -1,6 +1,7 @@---'@spree/admin-sdk': major'@spree/dashboard': major+'@spree/dashboard-core': major---Renamed stock items to stock levels.@@ -9,7 +10,9 @@ Spree 6.0 renames `Spree::StockItem` to `Spree::StockLevel`, and the admin API a- `client.stockItems` is now `client.stockLevels`, and it calls `/stock_levels` instead of `/stock_items`.- The `StockItem` type is now `StockLevel`, and `StockItemUpdateParams` is now `StockLevelUpdateParams`.+- `StockLevelUpdateParams` also gains `reason`, which labels a count correction in the stock history.- A variant's `stock_items` array is now `stock_levels`, on both reads and writes.+- `Subject.StockItem` is now `Subject.StockLevel` in `@spree/dashboard-core`. The old name stays as a deprecated alias for one release.- Prefixed ids change from `si_…` to `sl_…`. Ids you stored earlier no longer resolve.Webhook endpoints keep working: Spree publishes both `stock_level.*` and the older `stock_item.*` events for one release, so existing subscriptions keep firing. The dashboard's event picker now offers the `stock_level` names, and shows any `stock_item` subscription you already have under its Custom section. Move your subscriptions over before Spree 6.1, when the old names stop being published.diff --git a/packages/dashboard-core/src/lib/permissions.ts b/packages/dashboard-core/src/lib/permissions.tsindex 91e0f7a02d..71d9c624aa 100644--- a/packages/dashboard-core/src/lib/permissions.ts+++ b/packages/dashboard-core/src/lib/permissions.ts@@ -45,6 +45,8 @@ export const Subject = {ShippingMethod: 'Spree::ShippingMethod',StockLocation: 'Spree::StockLocation',StockLevel: 'Spree::StockLevel',+ /** @deprecated Use Subject.StockLevel — removed in Spree 6.1. */+ StockItem: 'Spree::StockItem',StockTransfer: 'Spree::StockTransfer',PriceList: 'Spree::PriceList',PriceRule: 'Spree::PriceRule',diff --git a/spree/core/app/models/spree/stock_level.rb b/spree/core/app/models/spree/stock_level.rbindex 3e407dc747..7bac859432 100644--- a/spree/core/app/models/spree/stock_level.rb+++ b/spree/core/app/models/spree/stock_level.rb@@ -100,10 +100,17 @@ module Spree# neither counter update needs the delta that count_on_hand's locked path# exists for.#+ # Touched afterwards because the counter write is a bare SQL update: it+ # runs no callbacks, so without this a placement taking the last unit would+ # leave the variant's cache keys and the search index claiming it is still+ # for sale, and would publish no stock_level.updated. Under the old model+ # the same change went through `save`, and this is what restores it.+ ## @param value [Integer] signed change# @return [void]def adjust_allocated_count(value)value.negative? ? decrement!(:allocated_count, value.abs) : increment!(:allocated_count, value)+ touchend# Withdraws up to +units+ of promise. Only a promise that exists can bediff --git a/spree/core/app/models/spree/stock_movement.rb b/spree/core/app/models/spree/stock_movement.rbindex 46e569cdcb..d6450c0295 100644--- a/spree/core/app/models/spree/stock_movement.rb+++ b/spree/core/app/models/spree/stock_movement.rb@@ -73,9 +73,12 @@ module Spreedelegate :variant, :variant_id, to: :stock_level, allow_nil: truedelegate :product, to: :variant+ # `stock_item_id` rides along for one release beside the name that replaced+ # it: Ransack resolves attribute aliases, and dropping the old filter would+ # hand a client still sending it the whole collection rather than an error.self.whitelisted_ransackable_attributes = %w[quantity kind reason created_at stock_level_id- order_id fulfillment_id return_id exchange_id- stock_transfer_id]+ stock_item_id order_id fulfillment_id return_id+ exchange_id stock_transfer_id]self.whitelisted_ransackable_associations = %w[stock_level]# Stored audit text for a correction nobody labelled. Deliberatelydiff --git a/spree/core/app/models/spree/stock_reservation.rb b/spree/core/app/models/spree/stock_reservation.rbindex e5d19a0f19..a3a55d5bbb 100644--- a/spree/core/app/models/spree/stock_reservation.rb+++ b/spree/core/app/models/spree/stock_reservation.rb@@ -23,7 +23,10 @@ module Spreejoins(:order).where(spree_orders: { store_id: store.id })}- self.whitelisted_ransackable_attributes = %w[stock_level_id line_item_id order_id quantity expires_at]+ # `stock_item_id` rides along for one release beside the name that replaced+ # it — see the same allowlist on Spree::StockMovement.+ self.whitelisted_ransackable_attributes = %w[stock_level_id stock_item_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]diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex 9cf71ae414..f46d13fdda 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -82,6 +82,7 @@ module Spreebefore_validation :set_cost_currencybefore_validation :apply_pending_options, if: :pending_options?+ before_validation :apply_pending_stock_levels, if: :pending_stock_levels?validates :cost_price, numericality: { greater_than_or_equal_to: 0, allow_nil: true }# Uniqueness is scoped to the seller — see #validate_sku_uniqueness. Written@@ -635,12 +636,13 @@ module Spree# @return [void]def stock_levels=(stock_levels_params)return super if stock_levels_params.blank? || stock_levels_params.first.is_a?(Spree::StockLevel)+ return if defer_stock_levels(:stock_levels=, stock_levels_params)location_ids_in_payload = []stock_levels_params.each do |stock_data|stock_data = stock_data.to_h.with_indifferent_access- location = Spree::StockLocation.find_by_param(stock_data[:stock_location_id])+ location = stock_location_for_param(stock_data[:stock_location_id])# A stale or foreign location id is skipped rather than raising, which# is what #stock_levels_attributes= already does for the same payload.next if location.nil?@@ -676,12 +678,13 @@ module Spree# @return [void]def stock_levels_attributes=(rows)rows = rows.values if rows.respond_to?(:values) && !rows.is_a?(Array)+ return if defer_stock_levels(:stock_levels_attributes=, rows)Array.wrap(rows).each do |row|row = (row.respond_to?(:to_unsafe_h) ? row.to_unsafe_h : row.to_h).with_indifferent_accessnext if row[:stock_location_id].blank? || row[:count_on_hand].blank?- stock_location = Spree::StockLocation.find_by_param(row[:stock_location_id])+ stock_location = stock_location_for_param(row[:stock_location_id])next if stock_location.nil?set_stock(row[:count_on_hand], row[:backorderable], stock_location)@@ -911,6 +914,44 @@ module Spreeprivate+ # Resolved through the product's own store, because+ # +Spree::StockLocation.find_by_param+ is global: an id belonging to another+ # store would otherwise resolve and put this variant's stock in that store's+ # warehouse. There is no global fallback — a variant is only reachable+ # through a product, and a product belongs to a store.+ #+ # @param param [String, Integer, nil] prefixed or raw stock location id+ # @return [Spree::StockLocation, nil]+ def stock_location_for_param(param)+ return if param.blank?++ product&.store&.stock_locations&.find_by_param(param)+ end++ # +product.variants.create(stock_levels_attributes: …)+ assigns attributes+ # before Rails wires the owner, so the store these location ids have to be+ # scoped against is not known yet. The payload waits for the product rather+ # than resolving against every warehouse in the installation.+ #+ # @return [Boolean] true when the write was deferred+ def defer_stock_levels(writer, payload)+ return false if product.present?++ @pending_stock_levels = { writer: writer, payload: payload }+ true+ end++ def pending_stock_levels?+ @pending_stock_levels.present?+ end++ def apply_pending_stock_levels+ pending = @pending_stock_levels+ @pending_stock_levels = nil++ public_send(pending[:writer], pending[:payload])+ end+def pending_options?@pending_options.present?enddiff --git a/spree/core/db/migrate/20260814000001_rename_stock_items_to_stock_levels.rb b/spree/core/db/migrate/20260814000001_rename_stock_items_to_stock_levels.rbindex 8bc9bb3d2d..be8082ec18 100644--- a/spree/core/db/migrate/20260814000001_rename_stock_items_to_stock_levels.rb+++ b/spree/core/db/migrate/20260814000001_rename_stock_items_to_stock_levels.rb@@ -9,7 +9,13 @@ class RenameStockItemsToStockLevels < ActiveRecord::Migration[8.1]rename_column :spree_stock_movements, :stock_item_id, :stock_level_idrename_column :spree_stock_reservations, :stock_item_id, :stock_level_id- rename_index :spree_stock_levels, 'stock_item_by_loc_var_id_deleted_at', 'stock_level_by_loc_var_id_deleted_at'+ # Guarded, unlike its neighbours: 20240303174340 asks to remove this index+ # and only misses because it names two of the three columns, so a host that+ # dropped it by hand is a state worth renaming around rather than failing on.+ if index_name_exists?(:spree_stock_levels, 'stock_item_by_loc_var_id_deleted_at')+ rename_index :spree_stock_levels, 'stock_item_by_loc_var_id_deleted_at', 'stock_level_by_loc_var_id_deleted_at'+ end+rename_index :spree_stock_levels, 'stock_item_by_loc_and_var_id', 'stock_level_by_loc_and_var_id'rename_index :spree_stock_reservations, 'idx_stock_reservations_item_line_item', 'idx_stock_reservations_level_line_item'@@ -27,7 +33,10 @@ class RenameStockItemsToStockLevels < ActiveRecord::Migration[8.1]rename_index :spree_stock_reservations, 'idx_stock_reservations_level_line_item', 'idx_stock_reservations_item_line_item'rename_index :spree_stock_levels, 'stock_level_by_loc_and_var_id', 'stock_item_by_loc_and_var_id'- rename_index :spree_stock_levels, 'stock_level_by_loc_var_id_deleted_at', 'stock_item_by_loc_var_id_deleted_at'++ if index_name_exists?(:spree_stock_levels, 'stock_level_by_loc_var_id_deleted_at')+ rename_index :spree_stock_levels, 'stock_level_by_loc_var_id_deleted_at', 'stock_item_by_loc_var_id_deleted_at'+ endrename_column :spree_stock_reservations, :stock_level_id, :stock_item_idrename_column :spree_stock_movements, :stock_level_id, :stock_item_id@@ -39,10 +48,17 @@ class RenameStockItemsToStockLevels < ActiveRecord::Migration[8.1]# rename_index rebuilds the index from its columns on adapters without a# native rename, which silently drops the partial condition. This one is a# uniqueness index over live rows only, so it is recreated explicitly.+ #+ # The branch asks the adapter what it supports rather than matching on its+ # name: MySQL answers to more than one adapter name, and a `where:` clause it+ # cannot honour is dropped without complaint, leaving a unique index over the+ # wrong set of rows.def rename_partial_uniqueness_index(from:, to:)remove_index :spree_stock_levels, name: from- if connection.adapter_name.downcase.start_with?('mysql')+ if connection.supports_partial_index?+ add_index :spree_stock_levels, %w[variant_id stock_location_id], name: to, unique: true, where: 'deleted_at IS NULL'+ elseexecute <<~SQLCREATE UNIQUE INDEX #{to}ON spree_stock_levels(@@ -51,8 +67,6 @@ class RenameStockItemsToStockLevels < ActiveRecord::Migration[8.1](COALESCE(deleted_at, CAST('1970-01-01' AS DATETIME))));SQL- else- add_index :spree_stock_levels, %w[variant_id stock_location_id], name: to, unique: true, where: 'deleted_at IS NULL'endendenddiff --git a/spree/core/spec/models/spree/stock_level_spec.rb b/spree/core/spec/models/spree/stock_level_spec.rbindex f328e8c768..4f76e441ee 100644--- a/spree/core/spec/models/spree/stock_level_spec.rb+++ b/spree/core/spec/models/spree/stock_level_spec.rb@@ -460,6 +460,15 @@ describe Spree::StockLevel, type: :model dosubject.adjust_allocated_count(-3)expect(subject.reload.allocated_count).to eq(1)end++ # The counter write is bare SQL and runs no callbacks, so without a touch+ # a placement taking the last unit leaves the variant's cache keys and the+ # search index still advertising it.+ it 'touches the variant so its caches and search index follow' do+ subject.variant.update_column(:updated_at, 1.day.ago)++ expect { subject.adjust_allocated_count(1) }.to change { subject.variant.reload.updated_at }+ endenddescribe '#release_allocated_count' dodiff --git a/spree/core/spec/models/spree/stock_movement_spec.rb b/spree/core/spec/models/spree/stock_movement_spec.rbindex 0eb7a53621..5d7a7e7142 100644--- a/spree/core/spec/models/spree/stock_movement_spec.rb+++ b/spree/core/spec/models/spree/stock_movement_spec.rb@@ -143,10 +143,23 @@ describe Spree::StockMovement, type: :model dodescribe 'whitelisted ransackable attributes' doit 'exposes the kind and every cause key' doexpect(Spree::StockMovement.whitelisted_ransackable_attributes).to eq(- %w[quantity kind reason created_at stock_level_id order_id fulfillment_id return_id- exchange_id stock_transfer_id]+ %w[quantity kind reason created_at stock_level_id stock_item_id order_id fulfillment_id+ return_id exchange_id stock_transfer_id])end++ # Dropping the pre-rename filter would hand a client still sending it the+ # whole collection rather than an error.+ it 'still filters on the pre-rename stock_item_id name' do+ stock_level = create(:stock_level)+ movement = create(:stock_movement, kind: 'received', quantity: 3, stock_level: stock_level)+ elsewhere = create(:stock_movement, kind: 'received', quantity: 3, stock_level: create(:stock_level))++ results = Spree::StockMovement.ransack(stock_item_id_eq: stock_level.id).result++ expect(results).to include(movement)+ expect(results).not_to include(elsewhere)+ endenddescribe '.default_adjustment_reason' dodiff --git a/spree/core/spec/models/spree/variant_spec.rb b/spree/core/spec/models/spree/variant_spec.rbindex 37cdbcf089..69622ffcc6 100644--- a/spree/core/spec/models/spree/variant_spec.rb+++ b/spree/core/spec/models/spree/variant_spec.rb@@ -1608,7 +1608,28 @@ describe Spree::Variant, type: :model dovariant.stock_levels = [{ stock_location_id: 'sloc_DoesNotExist', count_on_hand: 4 }]}.not_to raise_errorend++ # The id resolves globally, so without scoping to the product's own store+ # this write sets stock in another store's warehouse.+ it 'does not write stock into a stock location belonging to another store' do+ foreign_location = create(:stock_location, store: create(:store), name: 'Foreign warehouse')++ variant.stock_levels = [{ stock_location_id: foreign_location.prefixed_id, count_on_hand: 7 }]++ level = Spree::StockLevel.unscoped.find_by(variant: variant, stock_location: foreign_location)+ expect(level&.count_on_hand).not_to eq(7)+ end++ it 'does not write it through stock_levels_attributes= either' do+ foreign_location = create(:stock_location, store: create(:store), name: 'Foreign warehouse')++ variant.stock_levels_attributes = [{ stock_location_id: foreign_location.prefixed_id, count_on_hand: 7 }]++ level = Spree::StockLevel.unscoped.find_by(variant: variant, stock_location: foreign_location)+ expect(level&.count_on_hand).not_to eq(7)+ endend+describe '#options=' doit 'sets option values via set_option_value' doproduct = create(:product)