Sha256: 7558b0f689b19903f454ee7cc902f9447c55d99d827f3bb080a1cf11d9359da4

Contents?: true

Size: 1.18 KB

Versions: 5

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true

module SolidusFriendlyPromotions
  module Rules
    class NthOrder < PromotionRule
      include OrderLevelRule

      preference :nth_order, :integer, default: 2
      # It does not make sense to have this apply to the first order using preferred_nth_order == 1
      # Instead we could use the first_order rule
      validates :preferred_nth_order, numericality: {only_integer: true, greater_than: 1}

      # This is never eligible if the order does not have a user, and that user does not have any previous completed orders.
      #
      # Use the first order rule if you want a promotion to be applied to the first order for a user.
      # @param order [Spree::Order]
      def eligible?(order, _options = {})
        return false unless order.user

        nth_order?(order)
      end

      private

      def completed_order_count(order)
        order
          .user
          .orders
          .complete
          .where(Spree::Order.arel_table[:completed_at].lt(order.completed_at || Time.current))
          .count
      end

      def nth_order?(order)
        count = completed_order_count(order) + 1
        count == preferred_nth_order
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
solidus_friendly_promotions-1.0.0 app/models/solidus_friendly_promotions/rules/nth_order.rb
solidus_friendly_promotions-1.0.0.rc.3 app/models/solidus_friendly_promotions/rules/nth_order.rb
solidus_friendly_promotions-1.0.0.rc.2 app/models/solidus_friendly_promotions/rules/nth_order.rb
solidus_friendly_promotions-1.0.0.rc.1 app/models/solidus_friendly_promotions/rules/nth_order.rb
solidus_friendly_promotions-1.0.0.pre app/models/solidus_friendly_promotions/rules/nth_order.rb