Class: Spree::PromotionHandler::Cart

Inherits:
Object
  • Object
show all
Defined in:
app/models/spree/promotion_handler/cart.rb

Overview

Decides which promotion should be activated given the current order context

By activated it doesn't necessarily mean that the order will have a discount for every activated promotion. It means that the discount will be created and might eventually become eligible. The intention here is to reduce overhead. e.g. a promotion that requires item A to be eligible shouldn't be eligible unless item A is added to the order.

It can be used as a wrapper for custom handlers as well. Different applications might have completely different requirements to make the promotions system accurate and performant. Here they can plug custom handler to activate promos as they wish once an item is added to cart

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(order, line_item = nil, excluded_promotion_ids: []) ⇒ Cart

Returns a new instance of Cart.

Parameters:

  • order (Spree::Cart, Spree::Order)
  • line_item (Spree::LineItem, nil) (defaults to: nil)
  • excluded_promotion_ids (Array<String, Integer>) (defaults to: []) —

    promotions to leave alone, e.g. one that is being removed



22
23
24
25
26
27
# File 'app/models/spree/promotion_handler/cart.rb', line 22

def initialize(order, line_item = nil, excluded_promotion_ids: [])
  @order = order
  @line_item = line_item
  @store = order.store
  @excluded_promotion_ids = Array(excluded_promotion_ids).map(&:to_s)
end

Instance Attribute Details

#error ⇒ Object

Returns the value of attribute error.



17
18
19
# File 'app/models/spree/promotion_handler/cart.rb', line 17

def error
  @error
end

#line_item ⇒ Object (readonly)

Returns the value of attribute line_item.



16
17
18
# File 'app/models/spree/promotion_handler/cart.rb', line 16

def line_item
  @line_item
end

#order ⇒ Object (readonly)

Returns the value of attribute order.



16
17
18
# File 'app/models/spree/promotion_handler/cart.rb', line 16

def order
  @order
end

#store ⇒ Object (readonly)

Returns the value of attribute store.



16
17
18
# File 'app/models/spree/promotion_handler/cart.rb', line 16

def store
  @store
end

#success ⇒ Object

Returns the value of attribute success.



17
18
19
# File 'app/models/spree/promotion_handler/cart.rb', line 17

def success
  @success
end

Instance Method Details

#activate ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'app/models/spree/promotion_handler/cart.rb', line 29

def activate
  promotions.each do |promotion|
    next if @excluded_promotion_ids.include?(promotion.id.to_s)

    if (line_item && promotion.eligible?(line_item)) || promotion.eligible?(order)
      promotion.activate(line_item: line_item, order: order)
    else
      promotion.deactivate(line_item: line_item, order: order)
    end
  end
end