75 lines
1.9 KiB
Ruby
75 lines
1.9 KiB
Ruby
class User < ApplicationRecord
|
|
has_secure_password
|
|
has_many :sessions, dependent: :destroy
|
|
has_many :moods
|
|
|
|
normalizes :email_address, with: ->(e) { e.strip.downcase }
|
|
|
|
generates_token_for :invitation, expires_in: 5.days do
|
|
invitation_accepted_at
|
|
end
|
|
|
|
def invite_user!(email)
|
|
invited_user = User.create!(
|
|
email_address: email,
|
|
password: SecureRandom.hex(16) # temporary password
|
|
)
|
|
|
|
# Send invitation email using the generated token
|
|
token = invited_user.generate_token_for(:invitation)
|
|
UserMailer.invitation_email(invited_user, token).deliver_later
|
|
|
|
invited_user
|
|
end
|
|
|
|
def self.find_by_invitation_token(token)
|
|
find_by_token_for(:invitation, token)
|
|
end
|
|
|
|
def invitation_token
|
|
generate_token_for(:invitation)
|
|
end
|
|
|
|
def history
|
|
history_range(Mood.first.recorded_at.to_date, Date.today)
|
|
end
|
|
|
|
private
|
|
|
|
def history_range(from, to)
|
|
return [] if Mood.count < 1
|
|
|
|
first_monday = monday_of_the_week(first_mood_date(from))
|
|
|
|
current_date = first_monday
|
|
current_mode = last_mode_before(current_date)
|
|
log_mood = []
|
|
mood_range = Mood.order(:recorded_at).where(user: self, recorded_at: (first_monday..to))
|
|
mood_range.each do |mood|
|
|
while current_date < mood.recorded_at.to_date do
|
|
log_mood << { day: current_date, mode: current_mode }
|
|
current_date += 1
|
|
end
|
|
current_mode = mood.mode
|
|
end
|
|
|
|
while current_date <= to.to_date do
|
|
log_mood << { day: current_date, mode: current_mode }
|
|
current_date += 1
|
|
end
|
|
log_mood.each_slice(7).to_a
|
|
end
|
|
|
|
def first_mood_date(from)
|
|
Mood.order(recorded_at: :asc).where("user_id = :user_id AND recorded_at >= :from", user_id: self.id, from:).first.recorded_at.to_date
|
|
end
|
|
|
|
def monday_of_the_week(date)
|
|
date - date.wday + 1
|
|
end
|
|
|
|
def last_mode_before(last)
|
|
mood = Mood.where("user_id = :user_id AND recorded_at < :last", user_id: self.id, last: last).last
|
|
mood&.mode || "croisiere"
|
|
end
|
|
end
|