Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Fix orphaned inventory units when destroying line items on completed … (#13999)

Damian Legawiec44a4b240ebdd
diff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rb
index 2dcb607e92..639292ab57 100644
--- a/spree/core/app/models/spree/line_item.rb
+++ b/spree/core/app/models/spree/line_item.rb
@@ -293,7 +293,7 @@ module Spree
end
def verify_order_inventory_before_destroy
- Spree::OrderInventory.new(order, self).verify(target_shipment)
+ Spree::OrderInventory.new(order, self).verify(target_shipment, removing: true)
end
def update_adjustments
diff --git a/spree/core/app/models/spree/order_inventory.rb b/spree/core/app/models/spree/order_inventory.rb
index 167fec77ca..600e26e549 100644
--- a/spree/core/app/models/spree/order_inventory.rb
+++ b/spree/core/app/models/spree/order_inventory.rb
@@ -17,13 +17,23 @@ module Spree
# In case shipment is passed the stock location should only unstock or
# restock items if the order is completed. That is so because stock items
# are always unstocked when the order is completed through +shipment.finalize+
- def verify(shipment = nil, is_updated: false)
+ def verify(shipment = nil, is_updated: false, removing: false)
return unless order.completed? || shipment.present?
units_count = inventory_units.reload.sum(&:quantity)
line_item_changed = is_updated ? !line_item.saved_changes? : !line_item.changed?
- if units_count < line_item.quantity
+ if removing
+ # When the line item is being destroyed, only remove existing inventory.
+ # Adding here would create units that the LineItem `dependent: :destroy`
+ # cascade can't see (set_up_inventory writes through shipment.inventory_units,
+ # leaving line_item.inventory_units stale), producing an orphaned unit.
+ #
+ # Bypass `remove` because it routes through `set_quantity_to_remove` which
+ # assumes a quantity-change scenario; here we want to drain everything tied
+ # to this line item regardless of `line_item.quantity`.
+ remove_all_units(units_count, shipment) if units_count.positive?
+ elsif units_count < line_item.quantity
quantity = line_item.quantity - units_count
shipment ||= determine_target_shipment
@@ -49,6 +59,18 @@ module Spree
end
end
+ def remove_all_units(quantity, target_shipment = nil)
+ if target_shipment.present?
+ remove_from_shipment(target_shipment, quantity)
+ else
+ order.shipments.each do |shipment|
+ break if quantity.zero?
+
+ quantity -= remove_from_shipment(shipment, quantity)
+ end
+ end
+ end
+
def set_quantity_to_remove(units_count)
if (units_count - line_item.quantity).zero?
line_item.quantity
diff --git a/spree/core/app/models/spree/shipment.rb b/spree/core/app/models/spree/shipment.rb
index 2d1556154f..6f24e6f2c1 100644
--- a/spree/core/app/models/spree/shipment.rb
+++ b/spree/core/app/models/spree/shipment.rb
@@ -272,16 +272,22 @@ module Spree
def manifest
# Grouping by the ID means that we don't have to call out to the association accessor
# This makes the grouping by faster because it results in less SQL cache hits.
- inventory_units.group_by(&:variant_id).map do |_variant_id, units|
- units.group_by(&:line_item_id).map do |_line_item_id, units|
+ inventory_units.group_by(&:variant_id).flat_map do |_variant_id, units|
+ units.group_by(&:line_item_id).filter_map do |_line_item_id, units|
+ line_item = units.first.line_item
+ # Defensively skip orphaned inventory units (line item destroyed
+ # without cascading) so a single bad row doesn't crash callers that
+ # rely on line_item being present (item_cost, item_weight, the admin
+ # shipment manifest view, etc.).
+ next if line_item.nil?
+
states = {}
units.group_by(&:state).each { |state, iu| states[state] = iu.sum(&:quantity) }
- line_item = units.first.line_item
variant = units.first.variant
ManifestItem.new(line_item, variant, units.sum(&:quantity), states)
end
- end.flatten
+ end
end
def process_order_payments
diff --git a/spree/core/spec/models/spree/line_item_spec.rb b/spree/core/spec/models/spree/line_item_spec.rb
index 1744b14399..c23a0aafa6 100644
--- a/spree/core/spec/models/spree/line_item_spec.rb
+++ b/spree/core/spec/models/spree/line_item_spec.rb
@@ -103,6 +103,50 @@ describe Spree::LineItem, type: :model do
it 'deletes inventory units' do
expect { line_item.destroy }.to change { line_item.inventory_units.count }.from(1).to(0)
end
+
+ # Regression test for: destroying a line item on a completed order whose
+ # inventory units had already been cleared was leaving an orphan inventory
+ # unit on the shipment with `line_item_id` pointing to the just-destroyed
+ # line item. Cause: `before_destroy :verify_order_inventory_before_destroy`
+ # ran `OrderInventory#verify` which saw `units_count (0) < line_item.quantity (1)`
+ # and called `add_to_shipment` -> `set_up_inventory`, creating a new IU via
+ # `shipment.inventory_units.create(...)`. The line_item's `inventory_units`
+ # association was already loaded (and empty), so AR's `dependent: :destroy`
+ # cascade had nothing to iterate and the new IU survived. The fix passes
+ # `removing: true` so verify only ever removes when called from before_destroy.
+ context 'on a completed order whose inventory units were already cleared' do
+ let(:order) { create(:completed_order_with_totals) }
+ let(:line_item) { order.line_items.first }
+ let(:shipment) { order.shipments.first }
+ let(:other_line_item) do
+ create(:line_item, order: order, variant: create(:variant), quantity: 1).tap do |li|
+ shipment.set_up_inventory('on_hand', li.variant, order, li, 1)
+ end
+ end
+
+ before do
+ other_line_item
+ # Simulate the production state: the line item we are about to destroy
+ # has zero inventory units left on its shipments (e.g. removed by a
+ # prior partial action), but other line items on the same shipment do.
+ shipment.inventory_units.where(line_item_id: line_item.id).delete_all
+ shipment.inventory_units.reload
+ end
+
+ it 'does not leave an orphaned inventory unit on the shipment' do
+ line_item_id = line_item.id
+ line_item.destroy
+
+ # The destroyed line item's id must not be referenced by any inventory
+ # unit on the shipment afterwards.
+ orphaned = shipment.inventory_units.where(line_item_id: line_item_id)
+ expect(orphaned).to be_empty
+ end
+
+ it 'does not create a new inventory unit during destroy' do
+ expect { line_item.destroy }.not_to change { shipment.inventory_units.count }
+ end
+ end
end
context '#save' do
diff --git a/spree/core/spec/models/spree/order_inventory_spec.rb b/spree/core/spec/models/spree/order_inventory_spec.rb
index b15a0c5314..28906065e1 100644
--- a/spree/core/spec/models/spree/order_inventory_spec.rb
+++ b/spree/core/spec/models/spree/order_inventory_spec.rb
@@ -239,4 +239,22 @@ describe Spree::OrderInventory, type: :model do
end
end
end
+
+ context '#verify with removing: true' do
+ let(:shipment) { order.shipments.first }
+
+ context 'when the line item has no inventory units yet' do
+ before { shipment.inventory_units.where(line_item_id: line_item.id).delete_all }
+
+ it 'does not create new inventory units (which would be orphaned by the destroy cascade)' do
+ expect { subject.verify(nil, removing: true) }.not_to change { shipment.inventory_units.count }
+ end
+ end
+
+ context 'when the line item has existing inventory units' do
+ it 'removes the existing inventory units' do
+ expect { subject.verify(nil, removing: true) }.to change { shipment.inventory_units_for_item(line_item).sum(:quantity) }.to(0)
+ end
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/shipment_spec.rb b/spree/core/spec/models/spree/shipment_spec.rb
index ad861044be..430b110925 100644
--- a/spree/core/spec/models/spree/shipment_spec.rb
+++ b/spree/core/spec/models/spree/shipment_spec.rb
@@ -376,6 +376,34 @@ describe Spree::Shipment, type: :model do
expect(shipment.manifest.first.variant).to eq variant
end
end
+
+ context 'when an inventory unit has no associated line item' do
+ let(:other_variant) { create(:variant) }
+
+ before do
+ # Simulate an orphaned inventory unit (e.g. line item deleted directly
+ # in the DB or via an out-of-band script). Bypass validations so the
+ # spec stays valid even if InventoryUnit gains a presence validation
+ # on line_item later.
+ orphan = shipment.inventory_units.build(
+ state: 'on_hand',
+ variant: other_variant,
+ order: order,
+ line_item: nil,
+ quantity: 1
+ )
+ orphan.save(validate: false)
+ end
+
+ it 'skips the orphaned inventory unit instead of raising' do
+ expect { shipment.manifest }.not_to raise_error
+
+ manifest = shipment.manifest
+ expect(manifest.length).to eq(1)
+ expect(manifest.first.variant).to eq(variant)
+ expect(manifest.first.line_item).to eq(line_item)
+ end
+ end
end
describe '#can_get_rates?' do