class Credit < ActiveRecord::Base
  has_many :credit_expenses
  has_one :credit_product, :through => :order
  belongs_to :order, :foreign_key => :operation_id
	scope :between, lambda { |start, stop|
          where("(credits.created_at <= ? and credits.expire_after >= ?)", stop.end_of_day,start.beginning_of_day)
	    }
  
  scope :plus, lambda {
    where(:cred => true)
  }
  
  scope :moins, lambda {
    where(:debt => true)
  }
  
  scope :boughts, lambda {
    includes(:order).where(:orders => {:paid => true})
    
  }

  def solde
    
    self.value - self.credit_expenses.sum(:value)
    
    
  end
  
  def self.parts_at(date)
    Credit.between(date, date).includes(:order).where("orders.unpaid is null").sum("orders.nbr_parts")
  end

end
