Class: Spree::Promotion::Rules::MinimumQuantity

Inherits:
Spree::PromotionRule show all
Defined in:
app/models/spree/promotion/rules/minimum_quantity.rb

Overview

Promotion rule for ensuring an order contains a minimum quantity of actionable items.

This promotion rule is only compatible with the “all” match policy. It doesn’t make a lot of sense to use it without that policy as it reduces it to a simple quantity check across the entire order which would be better served by an item total rule.

Instance Method Summary collapse

Methods inherited from Spree::PromotionRule

#actionable?, #eligibility_errors, #preload_relations, #to_partial_path

Methods inherited from Base

display_includes

Methods included from Core::Permalinks

#generate_permalink, #save_permalink

Instance Method Details

#applicable?(promotable) ⇒ Boolean

What type of objects we should run our eligiblity checks against. In this case, our rule only applies to an entire order.

Parameters:

Returns:

  • (Boolean)

    true if promotable is a Spree::Order, false otherwise



24
25
26
# File 'app/models/spree/promotion/rules/minimum_quantity.rb', line 24

def applicable?(promotable)
  promotable.is_a?(Spree::Order)
end

#eligible?(order, _options = {}) ⇒ Boolean

Will look at all of the “actionable” line items in the order and determine if the sum of their quantity is greater than the minimum.

“Actionable” items are ones where they pass the “actionable?” check of all rules on the promotion. (e.g.: Match product/taxon when one of those rules is present.)

When false is returned, the reason will be included in the ‘eligibility_errors` object.

Parameters:

  • order (Spree::Order)

    the order we want to check eligibility on

  • _options (Hash) (defaults to: {})

    ignored

Returns:

  • (Boolean)

    true if promotion is eligible, false otherwise



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/models/spree/promotion/rules/minimum_quantity.rb', line 41

def eligible?(order, _options = {})
  actionable_line_items = order.line_items.select do |line_item|
    promotion.rules.all? { _1.actionable?(line_item) }
  end

  if actionable_line_items.sum(&:quantity) < preferred_minimum_quantity
    eligibility_errors.add(
      :base,
      eligibility_error_message(:quantity_less_than_minimum, count: preferred_minimum_quantity),
      error_code: :quantity_less_than_minimum
    )
  end

  eligibility_errors.empty?
end