You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
1.1 KiB
39 lines
1.1 KiB
class RecipientSchedule < ApplicationRecord
|
|
|
|
belongs_to :recipient
|
|
belongs_to :schedule
|
|
has_many :attempts
|
|
|
|
validates_associated :recipient
|
|
validates_associated :schedule
|
|
|
|
scope :ready, -> { where('next_attempt_at <= ?', Time.new) }
|
|
scope :for, -> (recipient) { where(recipient_id: recipient.id) }
|
|
|
|
def next_question
|
|
upcoming = upcoming_question_ids.split(/,/)
|
|
Question.where(id: upcoming.first).first
|
|
end
|
|
|
|
def attempt_question(question: next_question)
|
|
attempt = recipient.attempts.create(
|
|
schedule: schedule,
|
|
recipient_schedule: self,
|
|
question: question
|
|
)
|
|
|
|
if attempt.send_message
|
|
return if upcoming_question_ids.blank?
|
|
upcoming = upcoming_question_ids.split(/,/)[1..-1].join(',')
|
|
attempted = ((attempted_question_ids.try(:split, /,/) || []) + [question.id]).join(',')
|
|
update_attributes(
|
|
upcoming_question_ids: upcoming,
|
|
attempted_question_ids: attempted,
|
|
last_attempt_at: attempt.sent_at,
|
|
next_attempt_at: attempt.sent_at + (60 * 60 * schedule.frequency_hours)
|
|
)
|
|
end
|
|
return attempt
|
|
end
|
|
end
|