Sha256: e310a107c9a20c4c308dcb4e25e58fe097645c1251ff6f27fbf2765f9f471054

Contents?: true

Size: 1.35 KB

Versions: 43

Compression:

Stored size: 1.35 KB

Contents

module Spree
  class Promotion
    module Rules
      class NthOrder < PromotionRule
        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 promotion is applicable to orders only.
        def applicable?(promotable)
          promotable.is_a?(Spree::Order)
        end

        # 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]
        # @option options
        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
end

Version data entries

43 entries across 43 versions & 1 rubygems

Version Path
solidus_core-2.5.2 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.5.1 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.5.0 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.5.0.rc1 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.5.0.beta2 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.5.0.beta1 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.4.2 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.3.1 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.4.1 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.2.2 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.1.1 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.0.3 app/models/spree/promotion/rules/nth_order.rb
solidus_core-1.4.2 app/models/spree/promotion/rules/nth_order.rb
solidus_core-1.3.2 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.4.0 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.4.0.rc1 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.4.0.beta1 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.3.0 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.3.0.rc3 app/models/spree/promotion/rules/nth_order.rb
solidus_core-2.3.0.rc2 app/models/spree/promotion/rules/nth_order.rb