diff --git a/core/app/models/spree/promotion.rb b/core/app/models/spree/promotion.rb index c3edc53a596..507e792d4b6 100644 --- a/core/app/models/spree/promotion.rb +++ b/core/app/models/spree/promotion.rb @@ -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 diff --git a/core/spec/models/spree/promotion_spec.rb b/core/spec/models/spree/promotion_spec.rb index 91a8a8742d9..9c16ef0168c 100644 --- a/core/spec/models/spree/promotion_spec.rb +++ b/core/spec/models/spree/promotion_spec.rb @@ -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