dawarich/app/models/stat.rb

43 lines
922 B
Ruby
Raw Normal View History

2024-03-24 13:55:35 -04:00
# frozen_string_literal: true
2024-03-23 15:29:55 -04:00
class Stat < ApplicationRecord
include DistanceConvertible
2024-03-23 15:29:55 -04:00
validates :year, :month, presence: true
belongs_to :user
2024-03-24 13:55:35 -04:00
def distance_by_day
2024-12-06 10:52:36 -05:00
monthly_points = points
calculate_daily_distances(monthly_points)
2024-03-24 13:55:35 -04:00
end
2024-05-25 07:45:49 -04:00
def self.year_distance(year, user)
2024-12-06 10:52:36 -05:00
stats_by_month = where(year:, user:).order(:month).index_by(&:month)
2024-12-06 10:52:36 -05:00
(1..12).map do |month|
month_name = Date::MONTHNAMES[month]
2024-12-06 10:52:36 -05:00
distance = stats_by_month[month]&.distance || 0
[month_name, distance]
end
end
2024-12-06 10:52:36 -05:00
def points
user.tracked_points
.without_raw_data
.where(timestamp: timespan)
.order(timestamp: :asc)
end
2024-04-02 17:20:25 -04:00
private
def timespan
DateTime.new(year, month).beginning_of_month..DateTime.new(year, month).end_of_month
end
2024-12-06 10:52:36 -05:00
def calculate_daily_distances(monthly_points)
2025-07-22 16:41:12 -04:00
Stats::DailyDistanceQuery.new(monthly_points, timespan).call
2024-12-06 10:52:36 -05:00
end
2024-03-23 15:29:55 -04:00
end