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.2: Give stock locations the five stock verbs
Łukasz Adamczykfecaa5b3dcc2
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rbindex e629d321df..646f8225e6 100644--- a/spree/core/app/models/spree/fulfillment.rb+++ b/spree/core/app/models/spree/fulfillment.rb@@ -749,18 +749,17 @@ module Spreeowner.ship_address&.valid?end+ # Cancelling withdraws the promise made at placement — nothing physical+ # comes back, so on-hand and backordered units go back the same way and+ # the old backordered special case is gone.def manifest_restock(item)- if item.states['on_hand'].to_i.positive?- stock_location.restock item.variant, item.states['on_hand'], self- end+ return unless item.quantity.positive?- if item.states['backordered'].to_i.positive?- stock_location.restock_backordered item.variant, item.states['backordered']- end+ stock_location.release(item.variant, item.quantity, self)enddef manifest_unstock(item)- stock_location.unstock(item.variant, item.quantity, self) if item.variant.track_inventory?+ stock_location.allocate(item.variant, item.quantity, self) if item.variant.track_inventory?enddef set_cost_zero_when_nildiff --git a/spree/core/app/models/spree/order_inventory.rb b/spree/core/app/models/spree/order_inventory.rbindex ddc31371f6..c38559fb01 100644--- a/spree/core/app/models/spree/order_inventory.rb+++ b/spree/core/app/models/spree/order_inventory.rb@@ -111,9 +111,10 @@ module Spreeshipment.set_up_inventory('on_hand', variant, order, line_item, quantity)end- # adding to this shipment, and removing from stock_location+ # Editing a placed order changes what is promised, not what is on the+ # shelf — the goods only leave when the fulfillment ships.if order.completed? && variant.should_track_inventory?- shipment.stock_location.unstock(variant, quantity, shipment)+ shipment.stock_location.allocate(variant, quantity, shipment)endquantity@@ -144,17 +145,11 @@ module Spreeshipment.destroy if shipment.fulfillment_items.sum(:quantity).zero?- # removing this from shipment, and adding to stock_location- if order.completed?- current_on_hand = shipment.stock_location.count_on_hand(variant)-- if current_on_hand&.negative? && current_on_hand.abs < removed_backordered- shipment.stock_location.restock_backordered variant, current_on_hand.abs, shipment- else- shipment.stock_location.restock_backordered variant, removed_backordered, shipment- end-- shipment.stock_location.restock variant, removed_quantity - removed_backordered, shipment+ # Removing units from a placed order withdraws their promise. On-hand+ # and backordered units go back the same way now — nothing physical+ # moved either way.+ if order.completed? && removed_quantity.positive? && variant.should_track_inventory?+ shipment.stock_location.release(variant, removed_quantity, shipment)endremoved_quantitydiff --git a/spree/core/app/models/spree/stock_location.rb b/spree/core/app/models/spree/stock_location.rbindex 8b29862fc1..6529e578e9 100644--- a/spree/core/app/models/spree/stock_location.rb+++ b/spree/core/app/models/spree/stock_location.rb@@ -130,29 +130,66 @@ module Spreestock_level(variant).try(:backorderable?)end- def restock(variant, quantity, originator = nil, persist: true)- move(variant, quantity, originator, persist: persist)+ # The five stock verbs are the public surface — extensions call these+ # rather than creating movements themselves, so every row comes out typed+ # and carrying its cause.++ # Goods arrived: a purchase order, a transfer receipt, a return.+ #+ # @param variant [Spree::Variant]+ # @param quantity [Integer]+ # @param cause [ApplicationRecord, nil] the record this is happening for+ # @return [Spree::StockMovement]+ def restock(variant, quantity, cause = nil, persist: true)+ move(variant, quantity, kind: 'received', cause: cause, persist: persist)end- def restock_backordered(variant, quantity, _originator = nil)- item = stock_level_or_create(variant)- item.update_columns(- count_on_hand: item.count_on_hand + quantity,- updated_at: Time.current- )+ # Goods left. Departure is a physical fact, so this is allowed to take the+ # shelf below zero.+ #+ # @return [Spree::StockMovement]+ def unstock(variant, quantity, cause = nil, persist: true)+ move(variant, quantity, kind: 'shipped', cause: cause, persist: persist)+ end++ # Promises stock to a placed order. The cause is the fulfillment, never+ # the order: it owns the origin location and the unit split, and the order+ # comes along with it.+ #+ # @param fulfillment [Spree::Fulfillment]+ # @return [Spree::StockMovement]+ def allocate(variant, quantity, fulfillment)+ move(variant, quantity, kind: 'allocated', cause: fulfillment)end- def unstock(variant, quantity, originator = nil, persist: true)- move(variant, -quantity, originator, persist: persist)+ # Withdraws a promise — a canceled, relocated or shrunk fulfillment.+ # Nothing physical moves.+ #+ # @param fulfillment [Spree::Fulfillment]+ # @return [Spree::StockMovement]+ def release(variant, quantity, fulfillment)+ move(variant, quantity, kind: 'released', cause: fulfillment)+ end++ # A manual correction — an inventory count, shrinkage, damage. Signed, so+ # a negative quantity writes stock off.+ #+ # @param reason [String] audit text, required+ # @return [Spree::StockMovement]+ def adjust(variant, quantity, reason:)+ move(variant, quantity, kind: 'adjusted', reason: reason)end- def move(variant, quantity, originator = nil, persist: true)+ def move(variant, quantity, kind:, cause: nil, reason: nil, persist: true)stock_level = stock_level_or_create(variant)+ attributes = { quantity: quantity, kind: kind, reason: reason, **cause_attributes(cause) }if persist- stock_level.stock_movements.create!(quantity: quantity, originator: originator)+ stock_level.stock_movements.create!(attributes)else- originator.stock_movements << stock_level.stock_movements.build(quantity: quantity)+ # StockTransfer builds its movements before it is saved, so they ride+ # along on its own association rather than being created here.+ cause.stock_movements << stock_level.stock_movements.build(attributes)endend@@ -214,6 +251,21 @@ module Spreeprivate+ # One cause in, the foreign keys it implies out. A fulfillment brings its+ # order with it because "which order was this for?" must not cost a join.+ # The set is closed and core-owned — extensions register causes by adding+ # a branch here, never by inventing a movement column.+ def cause_attributes(cause)+ case cause+ when Spree::Fulfillment then { fulfillment: cause, order: cause.order }+ when Spree::Return then { return: cause, order: cause.order }+ when Spree::Exchange then { exchange: cause, order: cause.order }+ when Spree::StockTransfer then { stock_transfer: cause }+ when Spree::Order then { order: cause }+ else {}+ end+ end+def create_stock_levelsSpree::StockLocations::StockLevels::CreateJob.perform_later(self)enddiff --git a/spree/core/app/models/spree/stock_transfer.rb b/spree/core/app/models/spree/stock_transfer.rbindex 6b5a8daee7..c65beac257 100644--- a/spree/core/app/models/spree/stock_transfer.rb+++ b/spree/core/app/models/spree/stock_transfer.rb@@ -9,7 +9,7 @@ module Spreepublishes_lifecycle_events- has_many :stock_movements, as: :originator+ has_many :stock_movements, class_name: 'Spree::StockMovement', inverse_of: :stock_transfer, dependent: :nullifyaccepts_nested_attributes_for :stock_movements, reject_if: proc { |attributes|attributes[:quantity] = attributes[:quantity].to_iattributes[:quantity].blank? || attributes[:quantity].zero? || attributes[:stock_level_id].blank?@@ -92,7 +92,8 @@ module Spreedef variants_available_in_source_location?(source_location, variants)return true if source_location.nil?- source_location.stock_levels.where(variant: variants.keys).where(Spree::StockLevel.arel_table[:count_on_hand].gt(0)).size == variants.keys.size+ available = Spree::StockLevel.arel_table[:count_on_hand] - Spree::StockLevel.arel_table[:allocated_count]+ source_location.stock_levels.where(variant: variants.keys).where(available.gt(0)).size == variants.keys.sizeendendenddiff --git a/spree/core/app/workflows/spree/fulfillments/cancel.rb b/spree/core/app/workflows/spree/fulfillments/cancel.rbindex 6771ae8e43..9bbc4ed72d 100644--- a/spree/core/app/workflows/spree/fulfillments/cancel.rb+++ b/spree/core/app/workflows/spree/fulfillments/cancel.rb@@ -1,14 +1,14 @@module Spreemodule Fulfillments- # Cancels a fulfillment: the goods are not going out, so their units go- # back on the shelf and the carrier is told to stand down.+ # Cancels a fulfillment: the goods are not going out, so the promise made+ # against their units is withdrawn and the carrier is told to stand down.## In the workflow tier because cancelling talks to the outside world. The# provider call refunds a purchased label or cancels a 3PL pick — network# I/O that must not sit inside the database transaction holding the stock# movements, since a slow carrier would hold row locks open and a failed- # call would roll back a restock that already happened at the warehouse.- # Restocking commits first; the provider is told afterwards.+ # call would roll back a release that already happened at the warehouse.+ # The release commits first; the provider is told afterwards.class Cancel < Spree::Workflowhooks :validate, :after_cancel@@ -30,7 +30,7 @@ module Spreestep :ensure_cancelableApplicationRecord.transaction do- step :restock_units+ step :release_unitsstep :mark_canceledend@@ -48,17 +48,16 @@ module Spreefailure(fulfillment, Spree.t('fulfillments.errors.cannot_cancel'))end- # Puts every unit back on the shelf. On-hand and backordered units go- # back by different routes: an on-hand unit returns real stock, while a- # backordered one only cancels the promise made against stock that never- # arrived, so restocking it as on-hand would invent inventory.- def restock_units+ # Withdraws the promise this fulfillment held. Nothing physical comes+ # back — the goods never left the shelf — so on-hand and backordered+ # units release the same way and the old backordered special case is+ # gone with the negative-on-hand representation it served.+ def release_unitsfulfillment.manifest.each do |item|- on_hand = item.states['on_hand'].to_i- backordered = item.states['backordered'].to_i+ next unless item.variant.track_inventory?+ next unless item.quantity.positive?- stock_location.restock(item.variant, on_hand, fulfillment) if on_hand.positive?- stock_location.restock_backordered(item.variant, backordered) if backordered.positive?+ stock_location.release(item.variant, item.quantity, fulfillment)endenddiff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rbindex 6189789e26..0aa1486407 100644--- a/spree/core/lib/spree/permitted_attributes.rb+++ b/spree/core/lib/spree/permitted_attributes.rb@@ -238,11 +238,12 @@ module Spree]@@stock_movement_attributes = [- :quantity, :stock_level, :stock_level_id, :originator, :action+ :quantity, :kind, :reason, :stock_level, :stock_level_id,+ :order_id, :fulfillment_id, :return_id, :exchange_id, :stock_transfer_id]@@stock_transfer_attributes = [:source_location_id, :destination_location_id, :reference,- stock_movements_attributes: [:variant_id, :quantity, :originator_id, :stock_level_id]]+ stock_movements_attributes: [:variant_id, :quantity, :kind, :stock_level_id]]@@store_attributes = [:name, :url, :seo_title, :code, :meta_keywords,:meta_description, :default_currency, :default_country_code, :mail_from_address,diff --git a/spree/core/spec/models/spree/stock_location_spec.rb b/spree/core/spec/models/spree/stock_location_spec.rbindex b40b70cc52..9c488f6a5f 100644--- a/spree/core/spec/models/spree/stock_location_spec.rb+++ b/spree/core/spec/models/spree/stock_location_spec.rb@@ -170,24 +170,66 @@ module Spreeexpect(subject.backorderable?(variant)).to be trueend- it 'restocks a variant with a positive stock movement' do- originator = double- expect(subject).to receive(:move).with(variant, 5, originator, persist: true)- subject.restock(variant, 5, originator)+ it 'restocks a variant with a received movement' do+ cause = double+ expect(subject).to receive(:move).with(variant, 5, kind: 'received', cause: cause, persist: true)+ subject.restock(variant, 5, cause)end- it 'unstocks a variant with a negative stock movement' do- originator = double- expect(subject).to receive(:move).with(variant, -5, originator, persist: true)- subject.unstock(variant, 5, originator)+ # The sign no longer carries the direction — the kind does — so a+ # departure is written positive like every other order-driven kind.+ it 'unstocks a variant with a shipped movement' do+ cause = double+ expect(subject).to receive(:move).with(variant, 5, kind: 'shipped', cause: cause, persist: true)+ subject.unstock(variant, 5, cause)+ end++ it 'allocates a variant to a fulfillment' do+ fulfillment = double+ expect(subject).to receive(:move).with(variant, 2, kind: 'allocated', cause: fulfillment)+ subject.allocate(variant, 2, fulfillment)+ end++ it 'releases a variant from a fulfillment' do+ fulfillment = double+ expect(subject).to receive(:move).with(variant, 2, kind: 'released', cause: fulfillment)+ subject.release(variant, 2, fulfillment)+ end++ it 'adjusts a variant with a reason' do+ expect(subject).to receive(:move).with(variant, -2, kind: 'adjusted', reason: 'Damaged')+ subject.adjust(variant, -2, reason: 'Damaged')endit 'creates a stock_movement' doexpect do- subject.move variant, 5+ subject.move variant, 5, kind: 'received'end.to change { subject.stock_movements.where(stock_level_id: stock_level).count }.by(1)end+ describe 'cause keys' do+ let(:order) { create(:order) }+ let(:fulfillment) { create(:fulfillment, order: order, stock_location: subject) }++ it 'carries the fulfillment and its order onto an allocation' do+ subject.allocate(variant, 1, fulfillment)+ movement = subject.stock_movements.last++ expect(movement.kind).to eq('allocated')+ expect(movement.fulfillment).to eq(fulfillment)+ expect(movement.order).to eq(order)+ end++ it 'leaves the cause keys empty for a plain adjustment' do+ subject.adjust(variant, 1, reason: 'Cycle count')+ movement = subject.stock_movements.last++ expect(movement.reason).to eq('Cycle count')+ expect(movement.fulfillment_id).to be_nil+ expect(movement.order_id).to be_nil+ end+ end+it 'can be deactivated' docreate(:stock_location, active: true)create(:stock_location, active: false)diff --git a/spree/core/spec/models/spree/stock_transfer_spec.rb b/spree/core/spec/models/spree/stock_transfer_spec.rbindex c11e86e5a1..d050784e9e 100644--- a/spree/core/spec/models/spree/stock_transfer_spec.rb+++ b/spree/core/spec/models/spree/stock_transfer_spec.rb@@ -49,8 +49,11 @@ module Spreeexpect(stock_transfer.source_location).to eq source_locationexpect(stock_transfer.destination_location).to eq destination_location- expect(stock_transfer.source_movements.first.quantity).to eq(-5)- expect(stock_transfer.destination_movements.first.quantity).to eq 5+ # Quantities are positive on both sides now; the kind says which way+ # the goods went.+ expect(stock_transfer.source_movements.first).to have_attributes(quantity: 5, kind: 'shipped')+ expect(stock_transfer.destination_movements.first).to have_attributes(quantity: 5, kind: 'received')+ expect(stock_transfer.source_movements.first.stock_transfer).to eq(stock_transfer)endcontext 'when variants are not available in the source location' do