Class: Promotion

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/promotion.rb

Constant Summary collapse

MATCH_POLICIES =
%w(all any)

Instance Method Summary collapse

Instance Method Details

#create_discount(order) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/models/promotion.rb', line 48

def create_discount(order)
  return if order.promotion_credit_exists?(self)
  if eligible?(order) and amount = calculator.compute(order)
    amount = order.item_total if amount > order.item_total
    order.promotion_credits.reload.clear unless combine? and order.promotion_credits.all? { |credit| credit.source.combine? }
    order.update!
    PromotionCredit.create!({
        :label => "#{I18n.t(:coupon)} (#{code})",
        :source => self,
        :amount => -amount.abs,
        :order => order
      })
  end
end

#credits_countObject



35
36
37
# File 'app/models/promotion.rb', line 35

def credits_count
  credits.with_order.count
end

#eligible?(order) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
# File 'app/models/promotion.rb', line 25

def eligible?(order)
  !expired? && rules_are_eligible?(order)
end

#expired?Boolean

Returns:

  • (Boolean)


29
30
31
32
33
# File 'app/models/promotion.rb', line 29

def expired?
  starts_at && Time.now < starts_at ||
  expires_at && Time.now > expires_at ||
  usage_limit && credits_count >= usage_limit
end

#productsObject

Products assigned to all product rules



66
67
68
# File 'app/models/promotion.rb', line 66

def products
  @products ||= rules.of_type("Promotion::Rules::Product").map(&:products).flatten.uniq
end

#rules_are_eligible?(order) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
43
44
45
46
# File 'app/models/promotion.rb', line 39

def rules_are_eligible?(order)
  return true if rules.none?
  if match_policy == 'all'
    rules.all?{|r| r.eligible?(order)}
  else
    rules.any?{|r| r.eligible?(order)}
  end
end

#saveObject



14
15
16
17
18
# File 'app/models/promotion.rb', line 14

def save(*)
  if super
    promotion_rules.each { |p| p.save }
  end
end