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.4: Move stock off the shelf at dispatch instead of placement
Łukasz Adamczyk380353b926d4
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rbindex 646f8225e6..c2583c5fbb 100644--- a/spree/core/app/models/spree/fulfillment.rb+++ b/spree/core/app/models/spree/fulfillment.rb@@ -335,9 +335,43 @@ module Spreediscounts.promotion.exists?end+ # Placement no longer moves physical stock — the units are promised in+ # Spree::Orders::Complete and only leave the shelf when the parcel does.def finalize!fulfillment_items.finalize_units!- after_resume+ end++ # Units this fulfillment still holds a promise for, keyed by variant id:+ # what was allocated to it, less anything since released or shipped+ # against it. A fulfillment has one origin, so a variant maps to exactly+ # one stock level here.+ #+ # @return [Hash{Integer => Integer}]+ def allocated_quantities+ return {} unless persisted?++ totals = Hash.new(0)++ Spree::StockMovement.+ where(fulfillment_id: id).+ joins(:stock_level).+ group("#{Spree::StockLevel.table_name}.variant_id", :kind).+ sum(:quantity).+ each do |(variant_id, kind), quantity|+ case kind+ when 'allocated' then totals[variant_id] += quantity.abs+ when 'released', 'shipped' then totals[variant_id] -= quantity.abs+ end+ end++ totals.select { |_, quantity| quantity.positive? }+ end++ # Total units still promised to this fulfillment.+ #+ # @return [Integer]+ def allocated_quantity+ allocated_quantities.values.sumenddef include?(variant)diff --git a/spree/core/app/workflows/spree/fulfillments/fulfill.rb b/spree/core/app/workflows/spree/fulfillments/fulfill.rbindex 3fe9392bc2..1ba8220992 100644--- a/spree/core/app/workflows/spree/fulfillments/fulfill.rb+++ b/spree/core/app/workflows/spree/fulfillments/fulfill.rb@@ -73,7 +73,8 @@ module Spreeexternal_step :tell_provider_it_shippedApplicationRecord.transaction do- step :unstock_if_resuming_from_canceled+ step :reallocate_if_resuming_from_canceled+ step :ship_allocated_unitsstep :mark_fulfilledstep :capture_payment_if_configuredend@@ -196,16 +197,35 @@ module Spreeheld.all? { |line_item_id, quantity| requested[line_item_id].to_i >= quantity }end- # A canceled fulfillment already put its units back on the shelf, so- # shipping it directly has to take them off again — canceled -> fulfilled- # is allowed precisely so goods that went out anyway can be recorded.- def unstock_if_resuming_from_canceled+ # A canceled fulfillment gave its promise back, so shipping it directly+ # has to make that promise again before the units can leave — canceled ->+ # fulfilled is allowed precisely so goods that went out anyway can be+ # recorded. Ordering matters: the ledger should read as a re-promise+ # followed by a departure, which is what happened.+ def reallocate_if_resuming_from_canceledreturn unless @source.canceled?@fulfillment.manifest.each do |item|next unless item.variant.track_inventory?+ next unless item.quantity.positive?- @fulfillment.stock_location.unstock(item.variant, item.quantity, @fulfillment)+ @fulfillment.stock_location.allocate(item.variant, item.quantity, @fulfillment)+ end+ end++ # The shelf empties when the parcel leaves, for the units this+ # fulfillment actually holds a promise for. A fulfillment created before+ # typed movements holds none — its stock left at placement under the old+ # model — so it ships without a movement and is not decremented twice.+ def ship_allocated_units+ allocated = @fulfillment.allocated_quantities+ return if allocated.empty?++ @fulfillment.manifest.each do |item|+ quantity = [allocated[item.variant.id].to_i, item.quantity].min+ next unless quantity.positive?++ @fulfillment.stock_location.unstock(item.variant, quantity, @fulfillment)endenddiff --git a/spree/core/app/workflows/spree/orders/complete.rb b/spree/core/app/workflows/spree/orders/complete.rbindex ebaf4d84fd..c0e24002d8 100644--- a/spree/core/app/workflows/spree/orders/complete.rb+++ b/spree/core/app/workflows/spree/orders/complete.rb@@ -57,8 +57,25 @@ module Spree# Typed adjustment rows are frozen once completed — the totals# recalculation only re-sums them, never regenerates (see# Spree::Carts::RecalculateTotals) — so no per-row locking is needed.+ #+ # Placement promises stock rather than moving it: an `allocated`+ # movement per fulfillment raises the level's allocated count and leaves+ # the shelf alone until the parcel actually leaves. Draft orders enter+ # here directly, which is why the write lives in this workflow.def finalize_fulfillments- order.fulfillments.each(&:finalize!)+ order.fulfillments.each do |fulfillment|+ fulfillment.finalize!+ allocate_fulfillment_stock(fulfillment)+ end+ end++ def allocate_fulfillment_stock(fulfillment)+ fulfillment.manifest.each do |item|+ next unless item.variant.track_inventory?+ next unless item.quantity.positive?++ fulfillment.stock_location.allocate(item.variant, item.quantity, fulfillment)+ endenddef place_orderdiff --git a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rbindex 38a97f8655..5207838c26 100644--- a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb+++ b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb@@ -174,6 +174,44 @@ module Spreeendend+ describe 'stock' do+ let(:variant) { fulfillment.fulfillment_items.first.variant }+ let(:quantity) { fulfillment.fulfillment_items.where(variant_id: variant.id).sum(:quantity) }+ let(:stock_level) { fulfillment.stock_location.stock_level(variant) }++ it 'ships only the units the fulfillment holds a promise for' do+ fulfillment.stock_location.allocate(variant, quantity, fulfillment)++ expect { subject.call(fulfillment: fulfillment) }.+ to change { stock_level.reload.count_on_hand }.by(-quantity).+ and change { stock_level.reload.allocated_count }.by(-quantity)+ end++ # A fulfillment created before typed movements holds no allocation — its+ # stock left the shelf at placement under the old model — so shipping it+ # must not decrement a second time.+ it 'writes nothing for an unallocated fulfillment' do+ expect { subject.call(fulfillment: fulfillment) }.+ not_to change { stock_level.reload.count_on_hand }+ end++ # Departure is a physical fact: a forced dispatch records the parcel even+ # when the shelf says the goods were never there. Availability is+ # untouched on the way through — the promise had already been subtracted.+ it 'leaves the shelf negative on a forced dispatch from an empty shelf' do+ stock_level.update_column(:count_on_hand, 0)+ fulfillment.stock_location.allocate(variant, quantity, fulfillment)+ available_before = stock_level.reload.available_count++ result = subject.call(fulfillment: fulfillment, force: true)++ expect(result.success?).to eq(true)+ expect(stock_level.reload.count_on_hand).to eq(-quantity)+ expect(stock_level.allocated_count).to eq(0)+ expect(stock_level.available_count).to eq(available_before)+ end+ end+describe 'tracking' doit 'stores the tracking number on the fulfillment that ships' dosubject.call(fulfillment: fulfillment, tracking: '1Z999')diff --git a/spree/core/spec/workflows/spree/orders/cancel_spec.rb b/spree/core/spec/workflows/spree/orders/cancel_spec.rbindex 905c714b2c..3e0ae74f46 100644--- a/spree/core/spec/workflows/spree/orders/cancel_spec.rb+++ b/spree/core/spec/workflows/spree/orders/cancel_spec.rb@@ -28,15 +28,21 @@ module Spreeexpect(order.fulfillments.reload).to all(be_canceled)end- it 'puts the units back on the shelf' do+ # The goods never left the shelf — placement only promised them — so+ # cancelling withdraws the promise and leaves the physical count alone.+ it 'withdraws the promise made at placement' dofulfillment = order.fulfillments.firstvariant = fulfillment.fulfillment_items.first.variant+ quantity = fulfillment.fulfillment_items.where(variant_id: variant.id).sum(:quantity)stock_level = fulfillment.stock_location.stock_level(variant)+ fulfillment.stock_location.allocate(variant, quantity, fulfillment)++ count_on_hand_before = stock_level.reload.count_on_handexpect { subject.call(order: order, canceler: user) }.- to change { stock_level.reload.count_on_hand }.by(- fulfillment.fulfillment_items.where(variant_id: variant.id).sum(:quantity)- )+ to change { stock_level.reload.allocated_count }.by(-quantity)++ expect(stock_level.reload.count_on_hand).to eq(count_on_hand_before)end# The carrier calls are batched after the order transaction commits, sodiff --git a/spree/core/spec/workflows/spree/orders/complete_spec.rb b/spree/core/spec/workflows/spree/orders/complete_spec.rbindex 437f2fd672..ca290a43f9 100644--- a/spree/core/spec/workflows/spree/orders/complete_spec.rb+++ b/spree/core/spec/workflows/spree/orders/complete_spec.rb@@ -18,6 +18,35 @@ module Spreeexpect(draft.reload.status).to eq('placed')end+ describe 'stock' do+ let(:draft) { create(:order_ready_to_ship, store: store, line_items_count: 1) }+ let(:fulfillment) { draft.fulfillments.first }+ let(:variant) { fulfillment.fulfillment_items.first.variant }+ let(:stock_level) { fulfillment.stock_location.stock_level(variant) }+ let(:quantity) { fulfillment.fulfillment_items.where(variant_id: variant.id).sum(:quantity) }++ before { draft.update_columns(status: 'draft', completed_at: nil) }++ # Placement promises stock; the shelf only empties when the parcel does.+ it 'allocates each fulfillment without touching the shelf' do+ count_on_hand_before = stock_level.reload.count_on_hand++ expect { described_class.call(order: draft, payment_pending: true) }.+ to change { stock_level.reload.allocated_count }.by(quantity)++ expect(stock_level.reload.count_on_hand).to eq(count_on_hand_before)+ end++ it 'records the fulfillment and its order on the movement' do+ described_class.call(order: draft, payment_pending: true)++ movement = stock_level.stock_movements.allocated.last+ expect(movement.fulfillment).to eq(fulfillment)+ expect(movement.order).to eq(draft)+ expect(movement.quantity).to eq(quantity)+ end+ end+it 'is idempotent — an already placed order halts successfully with no side effects' doorder.update_columns(completed_at: Time.current, status: 'placed')