Skip to content

Commit

Permalink
Add Spree::Promotion#discounted_orders
Browse files Browse the repository at this point in the history
  • Loading branch information
mamhoff committed Mar 18, 2022
1 parent 2c59874 commit 9ee9235
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
8 changes: 8 additions & 0 deletions core/app/models/spree/promotion.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ def self.with_coupon_code(val)
).first
end

def discounted_orders
Spree::Order.where.not(spree_line_item_discounts: { id: nil }).
where(spree_line_item_discounts: { promotion_action_id: actions.map(&:id) }).or(
Spree::Order.where.not(spree_shipment_discounts: { id: nil }).
where(spree_shipment_discounts: { promotion_action_id: actions.map(&:id) })
).left_outer_joins(line_items: :discounts, shipments: :discounts).distinct
end

def as_json(options = {})
options[:except] ||= :code
super
Expand Down
40 changes: 40 additions & 0 deletions core/spec/models/spree/promotion_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1144,4 +1144,44 @@
expect(order.adjustment_total).to eq(-10)
end
end

describe "#discounted_orders" do
let(:promotion) { create(:promotion, :with_action) }
let(:other_promotion) { create(:promotion, :with_action) }
let(:other_action) { other_promotion.actions.first }
let(:action) { promotion.actions.first }

let!(:order_with_line_item_discount) do
create(:order_with_line_items).tap do |order|
order.line_items.first.discounts << build(:line_item_discount, line_item: nil, promotion_action: action)
end
end

let!(:order_with_shipment_discount) do
create(:order_with_line_items).tap do |order|
order.shipments.first.discounts << build(:shipment_discount, shipment: nil, promotion_action: action)
end
end

let!(:order_with_line_item_and_shipment_discount) do
create(:order_with_line_items).tap do |order|
order.shipments.first.discounts << build(:shipment_discount, shipment: nil, promotion_action: action)
order.line_items.first.discounts << build(:line_item_discount, line_item: nil, promotion_action: action)
end
end

let!(:order_without_discount) { create(:order_with_line_items) }

let!(:order_with_other_discount) do
create(:order_with_line_items).tap do |order|
order.shipments.first.discounts << build(:shipment_discount, shipment: nil, promotion_action: other_action)
end
end

subject { promotion.discounted_orders }

it { is_expected.to be_a(ActiveRecord::Relation) }

it { is_expected.to match_array([order_with_line_item_and_shipment_discount, order_with_shipment_discount, order_with_line_item_discount]) }
end
end

0 comments on commit 9ee9235

Please sign in to comment.