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.

Added `LineItem#shipments` and `LineItem#shipping_cost`

Damian Legawiec23a20a2cbf29
diff --git a/core/app/models/spree/line_item.rb b/core/app/models/spree/line_item.rb
index 98ec3cd58a..00a1a122cd 100644
--- a/core/app/models/spree/line_item.rb
+++ b/core/app/models/spree/line_item.rb
@@ -19,6 +19,7 @@ module Spree
has_many :adjustments, as: :adjustable, dependent: :destroy
has_many :inventory_units, inverse_of: :line_item
+ has_many :shipments, through: :inventory_units, source: :shipment
has_many :digital_links, dependent: :destroy
before_validation :copy_price
@@ -136,6 +137,27 @@ module Spree
inventory_units.all?(&:shipped?)
end
+ # Returns the shipping cost for the line item
+ #
+ # @return [BigDecimal]
+ def shipping_cost
+ shipments.sum do |shipment|
+ # Skip cancelled shipments
+ next if shipment.canceled?
+
+ # Get all inventory units in this shipment for this line item
+ line_item_units = shipment.inventory_units.where(line_item_id: id).count
+
+ # Get total inventory units in this shipment
+ total_units = shipment.inventory_units.count
+
+ # Calculate proportional shipping cost
+ next BigDecimal('0') if total_units.zero?
+ shipment.cost * (line_item_units.to_d / total_units)
+ end
+ end
+
+
def options=(options = {})
return unless options.present?
diff --git a/core/spec/models/spree/line_item_spec.rb b/core/spec/models/spree/line_item_spec.rb
index 01f8765bca..d81e803067 100644
--- a/core/spec/models/spree/line_item_spec.rb
+++ b/core/spec/models/spree/line_item_spec.rb
@@ -441,4 +441,24 @@ describe Spree::LineItem, type: :model do
end
end
end
+
+ describe '#shipments' do
+ let(:line_item) { create(:line_item) }
+ let(:inventory_unit) { create(:inventory_unit, line_item: line_item) }
+ let!(:shipment) { create(:shipment, inventory_units: [inventory_unit]) }
+
+ it 'returns the shipments for the line item' do
+ expect(line_item.shipments).to eq([shipment])
+ end
+ end
+
+ describe '#shipping_cost' do
+ let(:line_item) { create(:line_item) }
+ let(:inventory_unit) { create(:inventory_unit, line_item: line_item) }
+ let!(:shipment) { create(:shipment, inventory_units: [inventory_unit], cost: 10) }
+
+ it 'returns the shipping cost for the line item' do
+ expect(line_item.shipping_cost).to eq(10)
+ end
+ end
end