Sha256: 49bde345154d89bd75bd73c230ea68c02c348f215a6f32184463cf8a8df7839b

Contents?: true

Size: 1.54 KB

Versions: 3

Compression:

Stored size: 1.54 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 && promotion_credits.with_order.count >= usage_limit
  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_credits.reload.detect { |credit| credit.source_id == self.id }
    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

3 entries across 3 versions & 1 rubygems

Version Path
spree_promo-0.30.2 app/models/promotion.rb
spree_promo-0.30.1 app/models/promotion.rb
spree_promo-0.30.0 app/models/promotion.rb