class Customer < ActiveRecord::Base ##--- Associaciones belongs_to :contact has_one :billing_information has_many :sales has_many :special_prices has_many :pre_sales has_many :credits has_many :credit_payments, :through => :credits accepts_nested_attributes_for :contact, :reject_if => :all_blank accepts_nested_attributes_for :billing_information, :reject_if => :all_blank enum status: [ :erased, :active, :inactive, :debtor ] ##--- Llevar registro de Actividad del usuario audited ##--- Validaciones previas de guardar validates_presence_of :nick_name, message: "Debe capturar el nombre." # validates_presence_of :phone, message: "Debe capturar el teléfono." # validates_presence_of :email, message: "Debe capturar el correo electrónico de la Empresa." validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i ,message: "El formato del correo electrónico es inválido", :allow_blank => true validates :credit_limit, :numericality => { :only_integer => false, :message => "El limite de crédito debe ser numérico.", allow_nil: true } validates :time_limit, :numericality => { :only_integer => true, :message => "El liempo limite debe especificarse en dias.", allow_nil: true } ##--- Tipo de vistas / consultas scope :vigentes, -> { where( "status != 0").order(" status ASC, nick_name ASC") } scope :credito, -> { where("status !=0 and credit = true").order("nick_name ASC")} before_save do if !self.credit self.credit_limit = 0 self.time_limit = 0 end end def verify_credit time = 0 time = self.created_at + self.time_limit.days if time.to_date < Date.today && self.credit == true self.update_attributes(:status => :debtor) self.update_attributes(:credit => false) end return self end def get_debiting debiting = 0 self.credits.activos.each do |credit| debiting = debiting + credit.rest end return debiting end def sale_approved?(amount) puts "cantidad de nuevo credito: #{amount}" puts "limite de credito: #{credit_limit}" if amount > credit_limit puts "venta no aprobada" false else puts "venta aprobada" true end end def self.get_customers_under_limit customers = Array.new Customer.vigentes.each do |customer| if customer.credit_limit > customer.get_debiting customers << customer end end return customers end end