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.1: Give stock movements a kind and stock levels an allocation
Łukasz Adamczyk66c7e3b2b9aa
diff --git a/spree/core/app/models/spree/stock_level.rb b/spree/core/app/models/spree/stock_level.rbindex 27fbaccc9d..b98bacb83f 100644--- a/spree/core/app/models/spree/stock_level.rb+++ b/spree/core/app/models/spree/stock_level.rb@@ -32,11 +32,16 @@ module Spreedelegate :name, to: :variant, prefix: truedelegate :product, to: :variant+ # Which movement kind is currently writing count_on_hand, set by+ # {Spree::StockMovement#apply_to_stock_level} so the non-negative guard+ # can key off the kind rather than off the variant's backorder settings.+ attr_accessor :applying_movement_kind+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_attributes = %w[count_on_hand allocated_count 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) }@@ -56,6 +61,11 @@ module SpreeSpree::InventoryUnit.backordered_for_stock_level(self)end+ # @api private+ # Physical stock changes through movements only — call a+ # {Spree::StockLocation} verb rather than this, so the change leaves an+ # audit row. Keeps the locked read-modify-write that+ # {#process_backorders} needs the delta for.def adjust_count_on_hand(value)with_lock doset_count_on_hand(count_on_hand + value)@@ -69,8 +79,10 @@ module Spreesave!end+ # Units that are physically here and not already promised to a placed+ # order — what a customer can still buy from this level.def in_stock?- count_on_hand > 0+ available_count.positive?end# Tells whether it's available to be included in a shipment@@ -78,22 +90,35 @@ module Spreein_stock? || backorderable?end- # Units already allocated to pending shipments at this stock item.+ # Promised units go up and down atomically: two fulfillments allocating+ # the same level concurrently must not read each other's value first, and+ # neither counter update needs the delta that count_on_hand's locked path+ # exists for.#- # 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.+ # @param value [Integer] signed change+ # @return [void]+ def adjust_allocated_count(value)+ value.negative? ? decrement!(:allocated_count, value.abs) : increment!(:allocated_count, value)+ end++ # Withdraws up to +units+ of promise. Only a promise that exists can be+ # withdrawn — stock that leaves without ever having been allocated (a+ # stock transfer, or a fulfillment created before typed movements) must+ # not drive the counter below zero, which would make the level look more+ # available than it is.#- # @return [Integer]- def allocated_count- 0+ # @param units [Integer]+ # @return [void]+ def release_allocated_count(units)+ withdrawn = [units.abs, allocated_count].min+ return if withdrawn.zero?++ adjust_allocated_count(-withdrawn)end- # Physical stock minus allocated units at this stock item. Distinct from+ # Physical stock minus allocated units at this stock level. Distinct from# {Spree::Stock::Quantifier#available_stock}, which sums this across all- # stock items belonging to a variant.+ # stock levels belonging to a variant.## @return [Integer]def available_count@@ -106,9 +131,14 @@ module Spreeprivate+ # A shelf can only be driven below zero by goods physically leaving, and+ # then it means Spree never saw those goods arrive — a receiving gap that+ # heals itself when the missing `received` movement lands. Every other+ # writer, a correction above all, is stopped: a hand-typed count below+ # zero is a typo, not a fact.def verify_count_on_hand?- count_on_hand_changed? && !backorderable? && !variant.preorder? &&- (count_on_hand < count_on_hand_was) && (count_on_hand < 0)+ count_on_hand_changed? && count_on_hand.negative? &&+ count_on_hand < count_on_hand_was && applying_movement_kind != 'shipped'end# Process backorders based on amount of stock receiveddiff --git a/spree/core/app/models/spree/stock_movement.rb b/spree/core/app/models/spree/stock_movement.rbindex 151a153479..895ef2db88 100644--- a/spree/core/app/models/spree/stock_movement.rb+++ b/spree/core/app/models/spree/stock_movement.rb@@ -2,6 +2,11 @@ module Spreeclass StockMovement < Spree.base_classhas_prefix_id :sm+ # What happened to stock. The kind carries the direction, so the three+ # order-driven kinds are written positive; `received` and `adjusted` keep+ # the signed meaning of quantity.+ KINDS = %w[received allocated shipped released adjusted].freeze+QUANTITY_LIMITS = {max: 2**31 - 1,min: -2**31@@ -12,29 +17,54 @@ module Spreepublishes_lifecycle_eventsbelongs_to :stock_level, class_name: 'Spree::StockLevel', inverse_of: :stock_movements- belongs_to :originator, polymorphic: true+ # @deprecated Replaced by the concrete cause keys below; dropped in 6.1.+ belongs_to :originator, polymorphic: true, optional: true++ # The cause. A fulfillment-driven row carries its order too, so "which+ # order was this for?" costs no join.+ belongs_to :order, class_name: 'Spree::Order', optional: true+ belongs_to :fulfillment, class_name: 'Spree::Fulfillment', optional: true+ belongs_to :return, class_name: 'Spree::Return', optional: true+ belongs_to :exchange, class_name: 'Spree::Exchange', optional: true+ belongs_to :stock_transfer, class_name: 'Spree::StockTransfer', optional: truealias_attribute :stock_item_id, :stock_level_id- after_create :update_stock_level_quantity+ after_create :apply_to_stock_level- with_options presence: true do- validates :stock_level- validates :quantity, numericality: {- greater_than_or_equal_to: :min_quantity,- less_than_or_equal_to: QUANTITY_LIMITS[:max],- only_integer: true- }- end+ validates :stock_level, :quantity, :kind, presence: true+ validates :kind, inclusion: { in: KINDS }, allow_blank: true+ validates :quantity, numericality: {+ other_than: 0,+ greater_than_or_equal_to: QUANTITY_LIMITS[:min],+ less_than_or_equal_to: QUANTITY_LIMITS[:max],+ only_integer: true+ }, allow_nil: true+ validates :reason, presence: true, if: :adjusted?scope :recent, -> { order(created_at: :desc) }+ KINDS.each do |movement_kind|+ scope movement_kind, -> { where(kind: movement_kind) }+ define_method("#{movement_kind}?") { kind == movement_kind }+ enddelegate :variant, :variant_id, to: :stock_level, allow_nil: truedelegate :product, to: :variant- self.whitelisted_ransackable_attributes = %w[quantity action created_at stock_level_id originator_type]+ self.whitelisted_ransackable_attributes = %w[quantity kind reason created_at stock_level_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. Deliberately+ # resolved in English: the column is read by every admin afterwards, not+ # only by whoever happened to type the correction.+ #+ # @return [String]+ def self.default_adjustment_reason+ Spree.t('stock_movement.reasons.manual_adjustment', locale: :en)+ end+def readonly?persisted?end@@ -53,16 +83,31 @@ module Spreeprivate- def update_stock_level_quantity- return unless stock_level.should_track_inventory?-- stock_level.adjust_count_on_hand quantity+ # The single place count_on_hand and allocated_count change.+ #+ # A correction applies even to a variant that stopped tracking inventory —+ # that is how turning tracking off writes its stock away, and a correction+ # is a deliberate statement about the shelf either way.+ def apply_to_stock_level+ return unless adjusted? || stock_level.should_track_inventory?++ case kind+ when 'received', 'adjusted' then stock_level.adjust_count_on_hand(quantity)+ when 'allocated' then stock_level.adjust_allocated_count(quantity.abs)+ when 'released' then stock_level.release_allocated_count(quantity.abs)+ when 'shipped' then apply_departure+ endend- def min_quantity- return QUANTITY_LIMITS[:min] if stock_level.nil? || stock_level.backorderable?-- -stock_level.count_on_hand+ # Departure is a physical fact, so it is allowed to leave the shelf+ # negative — see the plan's "shipping from an empty shelf". The stock+ # level needs to know that to relax its own non-negative guard.+ def apply_departure+ stock_level.applying_movement_kind = 'shipped'+ stock_level.adjust_count_on_hand(-quantity.abs)+ stock_level.release_allocated_count(quantity.abs)+ ensure+ stock_level.applying_movement_kind = nilendendenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex a03ad6a456..e8b6728c0a 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1554,6 +1554,9 @@ en:stock_levels: Stock Levelsstock_location: Stock Locationstock_locations: Stock Locations+ stock_movement:+ reasons:+ manual_adjustment: Manual adjustmentstock_movements: Stock Movementsstock_transfer:errors:diff --git a/spree/core/lib/spree/testing_support/factories/stock_movement_factory.rb b/spree/core/lib/spree/testing_support/factories/stock_movement_factory.rbindex f3ac9c1b34..29b6cbd730 100644--- a/spree/core/lib/spree/testing_support/factories/stock_movement_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/stock_movement_factory.rb@@ -1,11 +1,28 @@FactoryBot.define dofactory :stock_movement, class: Spree::StockMovement doquantity { 1 }- action { 'sold' }+ kind { 'received' }stock_levelendtrait :received do- action { 'received' }+ kind { 'received' }+ end++ trait :allocated do+ kind { 'allocated' }+ end++ trait :shipped do+ kind { 'shipped' }+ end++ trait :released do+ kind { 'released' }+ end++ trait :adjusted do+ kind { 'adjusted' }+ reason { 'Manual adjustment' }endenddiff --git a/spree/core/spec/models/spree/stock_level_spec.rb b/spree/core/spec/models/spree/stock_level_spec.rbindex e91a94105b..26a6e4bd04 100644--- a/spree/core/spec/models/spree/stock_level_spec.rb+++ b/spree/core/spec/models/spree/stock_level_spec.rb@@ -196,10 +196,12 @@ describe Spree::StockLevel, type: :model doexpect(subject.count_on_hand).to eq(-1)end- # Test for #3755+ # Test for #3755. Only a departure may drive the shelf further below+ # zero now, so this states the kind that is doing the writing.it 'does not process backorders when stock is adjusted negatively' doexpect(inventory_unit).not_to receive(:fill_backorder)expect(inventory_unit_2).not_to receive(:fill_backorder)+ subject.applying_movement_kind = 'shipped'subject.adjust_count_on_hand(-1)expect(subject.count_on_hand).to eq(-3)end@@ -236,7 +238,11 @@ describe Spree::StockLevel, type: :model dolet(:inventory_unit) { double('InventoryUnit') }let(:inventory_unit_2) { double('InventoryUnit2') }- before { subject.set_count_on_hand(-2) }+ before do+ subject.applying_movement_kind = 'shipped'+ subject.set_count_on_hand(-2)+ subject.applying_movement_kind = nil+ endit "doesn't process backorders" doexpect(subject).not_to receive(:backordered_inventory_units)@@ -358,182 +364,118 @@ describe Spree::StockLevel, type: :model dodescribe 'validations' dodescribe 'count_on_hand' do+ # How far below zero a level may go is decided by the movement kind+ # applying the change, not by the variant's backorder settings — an+ # oversell lives in allocated_count now, not in a negative shelf.shared_examples_for 'valid count_on_hand' do- before do- subject.save- end+ before { subject.save }- it 'has :no errors_on' do- expect(subject.errors).to be_empty+ it 'has no errors on count_on_hand' do+ expect(subject.errors[:count_on_hand]).to be_emptyendendshared_examples_for 'not valid count_on_hand' do+ before { subject.save }++ it 'has an error on count_on_hand' do+ expect(subject.errors[:count_on_hand]).to include 'must be greater than or equal to 0'+ end+ end++ context 'when count_on_hand did not change' do+ it_behaves_like 'valid count_on_hand'+ end++ context 'when count_on_hand stays at or above zero' dobefore do- subject.save+ subject.update_column(:count_on_hand, 3)+ subject.count_on_hand = 1end- it 'has 1 error on count_on_hand' do- expect(subject.errors).not_to be_empty- expect(subject.errors.messages[:count_on_hand]).to be_present+ it_behaves_like 'valid count_on_hand'+ end++ context 'when count_on_hand rises while still negative' do+ before do+ subject.update_column(:count_on_hand, -3)+ subject.count_on_hand = -1end- it { expect(subject.errors[:count_on_hand]).to include 'must be greater than or equal to 0' }++ it_behaves_like 'valid count_on_hand'end- context 'when count_on_hand not changed' do- context 'when not backorderable' do- before do- subject.backorderable = false- end+ context 'when count_on_hand is driven below zero' do+ before do+ subject.update_column(:count_on_hand, 3)+ subject.count_on_hand = -3+ end- it_behaves_like 'valid count_on_hand'+ it_behaves_like 'not valid count_on_hand'++ context 'and the variant is backorderable' do+ before { subject.backorderable = true }++ it_behaves_like 'not valid count_on_hand'+ end++ context 'and the variant is a pre-order' do+ before { allow(subject.variant).to receive(:preorder?).and_return(true) }++ it_behaves_like 'not valid count_on_hand'end- context 'when backorderable' do- before do- subject.backorderable = true- end+ context 'and a departure is what is writing it' do+ before { subject.applying_movement_kind = 'shipped' }it_behaves_like 'valid count_on_hand'endend+ end+ end- context 'when count_on_hand changed' do- context 'when backorderable' do- before do- subject.backorderable = true- end-- context 'when both count_on_hand and count_on_hand_was are positive' do- context 'when count_on_hand is greater than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, 3)- subject.send(:count_on_hand=, subject.count_on_hand + 3)- end-- it_behaves_like 'valid count_on_hand'- end-- context 'when count_on_hand is smaller than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, 3)- subject.send(:count_on_hand=, subject.count_on_hand - 2)- end-- it_behaves_like 'valid count_on_hand'- end- end-- context 'when both count_on_hand and count_on_hand_was are negative' do- context 'when count_on_hand is greater than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, -3)- subject.send(:count_on_hand=, subject.count_on_hand + 2)- end-- it_behaves_like 'valid count_on_hand'- end-- context 'when count_on_hand is smaller than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, 3)- subject.send(:count_on_hand=, subject.count_on_hand - 3)- end-- it_behaves_like 'valid count_on_hand'- end- end-- context 'when both count_on_hand is positive and count_on_hand_was is negative' do- context 'when count_on_hand is greater than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, -3)- subject.send(:count_on_hand=, subject.count_on_hand + 6)- end-- it_behaves_like 'valid count_on_hand'- end- end-- context 'when both count_on_hand is negative and count_on_hand_was is positive' do- context 'when count_on_hand is greater than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, 3)- subject.send(:count_on_hand=, subject.count_on_hand - 6)- end-- it_behaves_like 'valid count_on_hand'- end- end- end+ describe 'allocation counters' do+ subject { create(:stock_level, adjust_count_on_hand: false) }- context 'when not backorderable' do- before do- subject.backorderable = false- end-- context 'when both count_on_hand and count_on_hand_was are positive' do- context 'when count_on_hand is greater than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, 3)- subject.send(:count_on_hand=, subject.count_on_hand + 3)- end-- it_behaves_like 'valid count_on_hand'- end-- context 'when count_on_hand is smaller than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, 3)- subject.send(:count_on_hand=, subject.count_on_hand - 2)- end-- it_behaves_like 'valid count_on_hand'- end- end-- context 'when both count_on_hand and count_on_hand_was are negative' do- context 'when count_on_hand is greater than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, -3)- subject.send(:count_on_hand=, subject.count_on_hand + 2)- end-- it_behaves_like 'valid count_on_hand'- end-- context 'when count_on_hand is smaller than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, -3)- subject.send(:count_on_hand=, subject.count_on_hand - 3)- end-- it_behaves_like 'not valid count_on_hand'- end- end-- context 'when both count_on_hand is positive and count_on_hand_was is negative' do- context 'when count_on_hand is greater than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, -3)- subject.send(:count_on_hand=, subject.count_on_hand + 6)- end-- it_behaves_like 'valid count_on_hand'- end- end-- context 'when both count_on_hand is negative and count_on_hand_was is positive' do- context 'when count_on_hand is greater than count_on_hand_was' do- before do- subject.update_column(:count_on_hand, 3)- subject.send(:count_on_hand=, subject.count_on_hand - 6)- end-- it_behaves_like 'not valid count_on_hand'- end- end- end+ describe '#adjust_allocated_count' do+ it 'moves the promise in both directions' do+ subject.adjust_allocated_count(4)+ expect(subject.reload.allocated_count).to eq(4)++ subject.adjust_allocated_count(-3)+ expect(subject.reload.allocated_count).to eq(1)+ end+ end++ describe '#release_allocated_count' do+ it 'withdraws only what was promised' do+ subject.adjust_allocated_count(2)++ subject.release_allocated_count(5)++ expect(subject.reload.allocated_count).to eq(0)+ end+ end++ describe '#available_count' do+ it 'is the shelf minus the promise' do+ subject.update_columns(count_on_hand: 10, allocated_count: 4)++ expect(subject.available_count).to eq(6)+ end+ end++ describe '#in_stock?' do+ it 'is false once every unit is promised' do+ subject.update_columns(count_on_hand: 2, allocated_count: 2)++ expect(subject).not_to be_in_stock+ end++ it 'is true while unpromised units remain' do+ subject.update_columns(count_on_hand: 2, allocated_count: 1)++ expect(subject).to be_in_stockendendenddiff --git a/spree/core/spec/models/spree/stock_movement/custom_events_spec.rb b/spree/core/spec/models/spree/stock_movement/custom_events_spec.rbindex b981923c34..f900483d0c 100644--- a/spree/core/spec/models/spree/stock_movement/custom_events_spec.rb+++ b/spree/core/spec/models/spree/stock_movement/custom_events_spec.rb@@ -23,13 +23,13 @@ RSpec.describe Spree::StockMovement::CustomEvents doendit 'publishes product.out_of_stock when product goes out of stock' do- stock_level.stock_movements.create!(quantity: -10)+ stock_level.stock_movements.create!(quantity: -10, kind: 'received')expect(Spree::Events).to have_received(:publish).with('product.out_of_stock', anything, anything)endit 'does not publish when product still has stock' do- stock_level.stock_movements.create!(quantity: -5)+ stock_level.stock_movements.create!(quantity: -5, kind: 'received')expect(Spree::Events).not_to have_received(:publish).with('product.out_of_stock', anything, anything)end@@ -45,7 +45,7 @@ RSpec.describe Spree::StockMovement::CustomEvents doallow(Spree::Events).to receive(:publish)# Add some stock (this triggers back_in_stock, not out_of_stock)- stock_level.stock_movements.create!(quantity: 1)+ stock_level.stock_movements.create!(quantity: 1, kind: 'received')expect(Spree::Events).not_to have_received(:publish).with('product.out_of_stock', anything, anything)end@@ -57,7 +57,7 @@ RSpec.describe Spree::StockMovement::CustomEvents doendit 'publishes product.back_in_stock when product comes back in stock' do- stock_level.stock_movements.create!(quantity: 10)+ stock_level.stock_movements.create!(quantity: 10, kind: 'received')expect(Spree::Events).to have_received(:publish).with('product.back_in_stock', anything, anything)end@@ -65,7 +65,7 @@ RSpec.describe Spree::StockMovement::CustomEvents doit 'does not publish when product was already in stock' dostock_level.set_count_on_hand(5)- stock_level.stock_movements.create!(quantity: 10)+ stock_level.stock_movements.create!(quantity: 10, kind: 'received')expect(Spree::Events).not_to have_received(:publish).with('product.back_in_stock', anything, anything)end@@ -78,7 +78,7 @@ RSpec.describe Spree::StockMovement::CustomEvents doendit 'does not publish any events' do- stock_level.stock_movements.create!(quantity: -10)+ stock_level.stock_movements.create!(quantity: -10, kind: 'received')expect(Spree::Events).not_to have_received(:publish).with('product.out_of_stock', anything, anything)enddiff --git a/spree/core/spec/models/spree/stock_movement_spec.rb b/spree/core/spec/models/spree/stock_movement_spec.rbindex c7e8dc8f8f..6d6611a943 100644--- a/spree/core/spec/models/spree/stock_movement_spec.rb+++ b/spree/core/spec/models/spree/stock_movement_spec.rb@@ -15,6 +15,12 @@ describe Spree::StockMovement, type: :model doenddescribe 'Constants' do+ describe 'KINDS' do+ it 'names every movement kind' do+ expect(described_class::KINDS).to eq(%w[received allocated shipped released adjusted])+ end+ end+describe 'QUANTITY_LIMITS[:max]' doit 'return 2**31 - 1' doexpect(Spree::StockMovement::QUANTITY_LIMITS[:max]).to eq(2**31 - 1)@@ -29,19 +35,47 @@ describe Spree::StockMovement, type: :model doenddescribe 'validations' do- it "does not allow quantity that is less than the stock item's count on hand" do- stock_level = create(:stock_level, backorderable: false)- stock_movement = build(:stock_movement, quantity: -11, stock_level: stock_level)+ let(:stock_level) { create(:stock_level, backorderable: false) }++ it 'requires a kind' do+ movement = build(:stock_movement, kind: nil, stock_level: stock_level)- expect(stock_movement).to be_invalid- expect(stock_movement.errors[:quantity]).to include('must be greater than or equal to -10')+ expect(movement).to be_invalid+ expect(movement.errors[:kind]).to be_presentend- it 'allows the negative quantity for a backorderable stock item' do- stock_level = create(:stock_level, adjust_count_on_hand: false, backorderable: true)- stock_movement = build(:stock_movement, quantity: -1, stock_level: stock_level)+ it 'rejects an unknown kind' do+ movement = build(:stock_movement, kind: 'sold', stock_level: stock_level)++ expect(movement).to be_invalid+ expect(movement.errors[:kind]).to be_present+ end++ it 'rejects a zero quantity' do+ movement = build(:stock_movement, quantity: 0, stock_level: stock_level)++ expect(movement).to be_invalid+ expect(movement.errors[:quantity]).to be_present+ end++ it 'requires a reason for an adjustment' do+ movement = build(:stock_movement, kind: 'adjusted', reason: nil, stock_level: stock_level)++ expect(movement).to be_invalid+ expect(movement.errors[:reason]).to be_present++ movement.reason = 'Cycle count'+ expect(movement).to be_valid+ end++ it 'does not require a reason for any other kind' do+ expect(build(:stock_movement, kind: 'received', reason: nil, stock_level: stock_level)).to be_valid+ end- expect(stock_movement).to be_valid+ # The old min_quantity guard is gone: how far below zero a level may go is+ # decided by the kind applying the change, not by the movement's size.+ it 'allows a quantity larger than the count on hand' do+ expect(build(:stock_movement, quantity: -11, stock_level: stock_level)).to be_validendend@@ -52,11 +86,39 @@ describe Spree::StockMovement, type: :model doto eq Spree::StockMovement.unscoped.order(created_at: :desc).to_sqlendend++ describe 'kind scopes' do+ let(:stock_level) { create(:stock_level) }+ let!(:received) { create(:stock_movement, kind: 'received', quantity: 1, stock_level: stock_level) }+ let!(:allocated) { create(:stock_movement, kind: 'allocated', quantity: 1, stock_level: stock_level) }++ it 'filters by kind' do+ expect(described_class.received).to contain_exactly(received)+ expect(described_class.allocated).to contain_exactly(allocated)+ expect(described_class.shipped).to be_empty+ end++ it 'answers the matching predicate' do+ expect(received).to be_received+ expect(received).not_to be_allocated+ end+ endenddescribe 'whitelisted ransackable attributes' do- it 'returns amount attribute' do- expect(Spree::StockMovement.whitelisted_ransackable_attributes).to eq(%w[quantity action created_at stock_level_id originator_type])+ it 'exposes the kind and every cause key' do+ expect(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]+ )+ end+ end++ describe '.default_adjustment_reason' do+ it 'resolves in English whatever locale is active' do+ I18n.with_locale(:de) do+ expect(described_class.default_adjustment_reason).to eq('Manual adjustment')+ endendend@@ -81,7 +143,7 @@ describe Spree::StockMovement, type: :model doendend- describe '#update_stock_level_quantity' do+ describe '#apply_to_stock_level' docontext 'when track inventory levels is false' dobefore dostub_store_preferences(track_inventory_levels: false)@@ -115,7 +177,7 @@ describe Spree::StockMovement, type: :model dostock_level.reloadend- it 'decrements the stock item count on hand' do+ it 'decrements the stock level count on hand' doexpect(stock_level.count_on_hand).to eq(9)endend@@ -127,10 +189,82 @@ describe Spree::StockMovement, type: :model dostock_level.reloadend- it 'increments the stock item count on hand' do+ it 'increments the stock level count on hand' doexpect(stock_level.count_on_hand).to eq(11)endend++ context 'allocated' do+ it 'raises allocated_count and leaves count_on_hand alone' do+ create(:stock_movement, kind: 'allocated', quantity: 3, stock_level: stock_level)+ stock_level.reload++ expect(stock_level.count_on_hand).to eq(10)+ expect(stock_level.allocated_count).to eq(3)+ expect(stock_level.available_count).to eq(7)+ end+ end++ context 'released' do+ it 'gives the promise back' do+ create(:stock_movement, kind: 'allocated', quantity: 3, stock_level: stock_level)+ create(:stock_movement, kind: 'released', quantity: 2, stock_level: stock_level)+ stock_level.reload++ expect(stock_level.count_on_hand).to eq(10)+ expect(stock_level.allocated_count).to eq(1)+ end++ it 'never drives allocated_count below zero' do+ create(:stock_movement, kind: 'released', quantity: 5, stock_level: stock_level)++ expect(stock_level.reload.allocated_count).to eq(0)+ end+ end++ context 'shipped' do+ it 'takes the units off the shelf and retires their allocation' do+ create(:stock_movement, kind: 'allocated', quantity: 3, stock_level: stock_level)+ create(:stock_movement, kind: 'shipped', quantity: 3, stock_level: stock_level)+ stock_level.reload++ expect(stock_level.count_on_hand).to eq(7)+ expect(stock_level.allocated_count).to eq(0)+ end++ it 'ships unallocated stock without inventing a negative allocation' do+ create(:stock_movement, kind: 'shipped', quantity: 2, stock_level: stock_level)+ stock_level.reload++ expect(stock_level.count_on_hand).to eq(8)+ expect(stock_level.allocated_count).to eq(0)+ end++ it 'may leave the shelf negative' do+ stock_level.update_column(:count_on_hand, 0)++ create(:stock_movement, kind: 'shipped', quantity: 1, stock_level: stock_level)++ expect(stock_level.reload.count_on_hand).to eq(-1)+ end+ end++ context 'adjusted' do+ it 'applies even when the variant stopped tracking inventory' do+ stock_level.variant.update!(track_inventory: false)+ stock_level.reload.update_column(:count_on_hand, 10)++ create(:stock_movement, kind: 'adjusted', quantity: -4, reason: 'Cycle count', stock_level: stock_level)++ expect(stock_level.reload.count_on_hand).to eq(6)+ end++ it 'refuses to drive the shelf below zero' do+ expect do+ create(:stock_movement, kind: 'adjusted', quantity: -11, reason: 'Cycle count', stock_level: stock_level)+ end.to raise_error(ActiveRecord::RecordInvalid)+ end+ endendendend