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
Phase P2.6: Record manual stock corrections in the ledger
Łukasz Adamczyk5773c4797c23
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.rbindex 700be94b8c..f4a75de9f5 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@@ -8,8 +8,38 @@ module Spreeclass StockLevelsController < ResourceControllerscoped_resource :stock+ # PATCH /api/v3/admin/stock_levels/:id+ #+ # A count edit is a correction, so it is written as an `adjusted`+ # movement rather than straight onto the column — that is what puts+ # it in the stock history beside every other change. The rest of the+ # payload updates normally.+ def update+ attributes = permitted_params.to_h+ new_count = attributes.delete('count_on_hand')+ reason = attributes.delete('reason').presence || Spree::StockMovement.default_adjustment_reason++ ActiveRecord::Base.transaction do+ @resource.update!(attributes) if attributes.any?+ adjust_count_on_hand(new_count, reason) unless new_count.nil?+ end++ render json: serialize_resource(@resource.reload)+ rescue ActiveRecord::RecordInvalid => e+ render_errors(e.record.errors)+ end+protected+ # The movement carries the delta, not the new count — it records what+ # changed, and the column follows from it.+ def adjust_count_on_hand(new_count, reason)+ delta = new_count.to_i - @resource.count_on_hand+ return if delta.zero?++ @resource.stock_location.adjust(@resource.variant, delta, reason: reason)+ end+def model_classSpree::StockLevelenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_controller_spec.rbindex 4f3f22622e..b3649ee957 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_controller_spec.rb@@ -39,6 +39,31 @@ RSpec.describe Spree::Api::V3::Admin::StockLevelsController, type: :controller dexpect(stock_level.reload.count_on_hand).to eq(42)end+ # The correction goes in the stock history like every other change, and+ # what it records is the delta — the column follows from it.+ it 'records the edit as an adjustment carrying the delta' do+ count_before = stock_level.count_on_hand++ patch :update, params: { id: stock_level.prefixed_id, count_on_hand: 42 }, as: :json++ movement = stock_level.stock_movements.adjusted.last+ expect(movement.kind).to eq('adjusted')+ expect(movement.quantity).to eq(42 - count_before)+ end++ it 'labels an unlabelled correction in English' do+ patch :update, params: { id: stock_level.prefixed_id, count_on_hand: 42 }, as: :json++ expect(stock_level.stock_movements.adjusted.last.reason).to eq('Manual adjustment')+ end++ it 'rejects a negative count' do+ patch :update, params: { id: stock_level.prefixed_id, count_on_hand: -1 }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(stock_level.reload.count_on_hand).not_to eq(-1)+ end+it 'toggles backorderable' dopatch :update, params: { id: stock_level.prefixed_id, backorderable: true }, as: :jsondiff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex cb94efa81b..01e9cc95d4 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -612,12 +612,31 @@ module Spree# @param backorderable [Boolean] the backorderable flag# @param stock_location [Spree::StockLocation] the stock location (defaults to store default)# @return [void]+ # Sets the count at a location. The correction goes through an `adjusted`+ # movement so it shows up in the stock history like every other change.+ #+ # @param count_on_hand [Integer] the count the level should end up at+ # @param backorderable [Boolean, nil]+ # @param stock_location [Spree::StockLocation, nil] defaults to the store's+ # @return [void]def set_stock(count_on_hand, backorderable = nil, stock_location = nil)stock_location ||= default_stock_locationstock_level = stock_levels.find_or_initialize_by(stock_location: stock_location)- stock_level.count_on_hand = count_on_handstock_level.backorderable = backorderable if backorderable.present?- stock_level.save! if persisted?++ # Nothing is saved yet, so the count rides on the in-memory record and+ # the autosave association persists it with the variant.+ unless persisted?+ stock_level.count_on_hand = count_on_hand+ return+ end++ stock_level.save! if stock_level.changed?++ delta = count_on_hand.to_i - stock_level.count_on_hand.to_i+ return if delta.zero?++ stock_location.adjust(self, delta, reason: Spree::StockMovement.default_adjustment_reason)enddef default_stock_location@@ -805,11 +824,20 @@ module SpreeSpree::Store.current.default_stock_location.set_up_stock_level(self)end+ # Turning tracking off writes the remaining stock away. That is a stock+ # decision, so it goes in the log like any other correction rather than+ # disappearing through update_all.def handle_track_inventory_changereturn unless track_inventory_previously_changed?return if track_inventory- stock_levels.update_all(count_on_hand: 0, updated_at: Time.current)+ stock_levels.reload.each do |stock_level|+ next if stock_level.count_on_hand.zero?++ stock_level.stock_location.adjust(+ self, -stock_level.count_on_hand, reason: Spree::StockMovement.default_adjustment_reason+ )+ endenddef increment_product_variant_countdiff --git a/spree/core/spec/models/spree/variant_spec.rb b/spree/core/spec/models/spree/variant_spec.rbindex ec39bd4ac2..f1da10ea10 100644--- a/spree/core/spec/models/spree/variant_spec.rb+++ b/spree/core/spec/models/spree/variant_spec.rb@@ -188,6 +188,31 @@ describe Spree::Variant, type: :model doendend+ describe '#set_stock' do+ let!(:variant) { create(:variant) }+ let(:stock_location) { variant.stock_levels.first.stock_location }+ let(:stock_level) { variant.stock_levels.first }++ it 'writes the difference as an adjustment with the default reason' do+ count_before = stock_level.count_on_hand++ expect { variant.set_stock(25, nil, stock_location) }.+ to change { stock_level.reload.count_on_hand }.to(25)++ movement = stock_level.stock_movements.adjusted.last+ expect(movement).to have_attributes(kind: 'adjusted', quantity: 25 - count_before, reason: 'Manual adjustment')+ end++ it 'writes nothing when the count is unchanged' do+ expect { variant.set_stock(stock_level.count_on_hand, nil, stock_location) }.+ not_to change { stock_level.stock_movements.count }+ end++ it 'refuses a negative count' do+ expect { variant.set_stock(-1, nil, stock_location) }.to raise_error(ActiveRecord::RecordInvalid)+ end+ end+describe 'after_update_commit :handle_track_inventory_change' dolet!(:product) { create(:product) }@@ -197,9 +222,18 @@ describe Spree::Variant, type: :model dolet!(:variant) { create(:variant, product: product, track_inventory: true) }let!(:stock_level) { create(:stock_level, variant: variant, count_on_hand: 100) }- it 'updates stock item count on hand to 0' do+ it 'updates stock level count on hand to 0' doexpect { subject }.to change { stock_level.reload.count_on_hand }.from(110).to(0)end++ # Writing the stock away is a stock decision, so it belongs in the log+ # rather than disappearing through a bulk column update.+ it 'records the write-off as an adjustment' do+ subject++ movement = stock_level.stock_movements.adjusted.last+ expect(movement).to have_attributes(quantity: -110, reason: 'Manual adjustment')+ endendcontext 'when tracking inventory' do