Modelo de gastos para mosi-app.com
class Gasto < ActiveRecord::Base
attr_accessible :cantidad, :user_id, :concepto_id, :fecha, :street, :city, :country, :name, :tag_tokens
belongs_to :user
belongs_to :concepto
has_many :user_tags
has_many :tags, through: :user_tags
attr_reader :tag_tokens
acts_as_gmappable
default_scope order("gastos.fecha desc")
scope :gastos_hoy, lambda {where("fecha >= ? and fecha < ?", Date.today.beginning_of_day.utc, Date.today.end_of_day.utc)}
scope :top_conceptosmas, order("cantidad desc").limit(5)
scope :top_conceptosmenos, order("cantidad asc").limit(5)
validates :cantidad, numericality: {greater_than: 0}, presence: true
validates_presence_of :fecha, :concepto_nombre
def concepto_nombre
concepto.try(:nombre)
end
def titulo_serie
"#{concepto.try(:nombre)}"
end
def tags_to_string
"#{tags.each {|t| t.name}.join(', ')}"
end
def concepto_nombre=(nombre)
self.concepto = Concepto.find_or_create_by_nombre(nombre.capitalize) if nombre.present?
end
def tag_tokens=(tokens)
self.tag_ids = Tag.ids_from_tokens(tokens)
end
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |gasto|
csv << gasto.attributes.values_at(*column_names)
end
end
end
def self.datos_grafica(inicio = 3.weeks.ago, fin = Date.today)
total_gastos = gastos_por_dia(inicio, fin)
(inicio.to_date..fin.to_date).map do |dia|
{
fecha: dia,
total: total_gastos[dia] || 0
}
end
end
def self.gastos_por_dia(inicio, fin)
gastos = where(fecha: inicio.beginning_of_day..fin)
gastos = gastos.group("date(fecha)")
gastos = gastos.select("fecha, sum(cantidad) as total_del_dia")
gastos.each_with_object({}) do |gasto, cantidades|
cantidades[gasto.fecha.to_date] = gasto.total_del_dia
end
end
def gmaps4rails_address
"#{self.street}, #{self.city}, #{self.country}"
end
end