customer.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. class Customer < ActiveRecord::Base
  2. ##--- Associaciones
  3. belongs_to :contact
  4. has_one :billing_information
  5. has_many :sales
  6. has_many :special_prices
  7. has_many :pre_sales
  8. has_many :credits
  9. has_many :credit_payments, :through => :credits
  10. accepts_nested_attributes_for :contact, :reject_if => :all_blank
  11. accepts_nested_attributes_for :billing_information, :reject_if => :all_blank
  12. enum status: [ :erased, :active, :inactive, :debtor ]
  13. ##--- Llevar registro de Actividad del usuario
  14. audited
  15. ##--- Validaciones previas de guardar
  16. validates_presence_of :nick_name, message: "Debe capturar el nombre."
  17. # validates_presence_of :phone, message: "Debe capturar el teléfono."
  18. # validates_presence_of :email, message: "Debe capturar el correo electrónico de la Empresa."
  19. 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
  20. validates :credit_limit, :numericality => { :only_integer => false, :message => "El limite de crédito debe ser numérico.", allow_nil: true }
  21. validates :time_limit, :numericality => { :only_integer => true, :message => "El liempo limite debe especificarse en dias.", allow_nil: true }
  22. ##--- Tipo de vistas / consultas
  23. scope :vigentes, -> { where( "status != 0").order(" status ASC, nick_name ASC") }
  24. scope :credito, -> { where("status !=0 and credit = true").order("nick_name ASC")}
  25. before_save do
  26. if !self.credit
  27. self.credit_limit = 0
  28. self.time_limit = 0
  29. end
  30. end
  31. def verify_credit
  32. time = 0
  33. time = self.created_at + self.time_limit.days
  34. if time.to_date < Date.today && self.credit == true
  35. self.update_attributes(:status => :debtor)
  36. self.update_attributes(:credit => false)
  37. end
  38. return self
  39. end
  40. def get_debiting
  41. debiting = 0
  42. self.credits.activos.each do |credit|
  43. debiting = debiting + credit.rest
  44. end
  45. return debiting
  46. end
  47. def sale_approved?(amount)
  48. puts "cantidad de nuevo credito: #{amount}"
  49. puts "limite de credito: #{credit_limit}"
  50. if amount > credit_limit
  51. puts "venta no aprobada"
  52. false
  53. else
  54. puts "venta aprobada"
  55. true
  56. end
  57. end
  58. def self.get_customers_under_limit
  59. customers = Array.new
  60. Customer.vigentes.each do |customer|
  61. if customer.credit_limit > customer.get_debiting
  62. customers << customer
  63. end
  64. end
  65. return customers
  66. end
  67. end