Sha256: 02690b2fdab38bc1aa5547d48f188b0a2cb710c6974559a6e588b22ba6f978cf

Contents?: true

Size: 1.53 KB

Versions: 5

Compression:

Stored size: 1.53 KB

Contents

class Promotion < ActiveRecord::Base
  has_many  :promotion_credits,    :as => :source
  calculated_adjustments
  alias credits promotion_credits

  has_many :promotion_rules
  accepts_nested_attributes_for :promotion_rules
  alias_method :rules, :promotion_rules

  validates :name, :code, :presence => true

  MATCH_POLICIES = %w(all any)

  scope :automatic, where("code IS NULL OR code = ''")

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

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

  def credits_count
    credits.with_order.count
  end

  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

  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.promotion_credits.create({
          :label => "#{I18n.t(:coupon)} (#{code})",
          :source => self,
          :amount => -amount.abs
        })
      order.update!
    end
  end



  # Products assigned to all product rules
  def products
    @products ||= rules.of_type("Promotion::Rules::Product").map(&:products).flatten.uniq
  end

end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
spree_promo-0.40.4 app/models/promotion.rb
spree_promo-0.40.3 app/models/promotion.rb
spree_promo-0.40.2 app/models/promotion.rb
spree_promo-0.40.1 app/models/promotion.rb
spree_promo-0.40.0 app/models/promotion.rb