require "study_engine/config" require "study_engine/study_id" module StudyEngine class Assessment < ActiveRecord::Base cattr_accessor(:timeout_interval) { 10.minutes } default_scope -> { includes(:persisted_results) } def timestamp_attributes_for_create super + [:assessment_updated_at] end def self.by_event event where(event: event) end def self.by_study_id study_id return none unless study_id where(study_id: study_id) end def self.by_site site where("study_id RLIKE '...-#{site}-....'") end has_many :persisted_results, class_name: "Result", dependent: :destroy before_create :assign_group_index belongs_to :coordinator, class_name: "User" def coordinator_email coordinator.try(:email) end def restarted_assessment Assessment.by_study_id(study_id).where(event: event).where.not(id: id).last end def stream_id StudyID.new("STR-#{study_id.site}-#{1000 + id}") unless new_record? end def notes? notes.present? end serialize :study_id, StudyID def results @results ||= begin bank_ids = StudyEngine.bank_finder.call(self) return persisted_results if persisted_results.length == bank_ids.length bank_ids.map do |bank_id| persisted_results.find_or_initialize_by(bank_id: bank_id) end end end def current_result results.find { |result| !result.finished? } end def percent_complete (results.select(&:finished?).count / results.count.to_f * 100).round end delegate :current_question, to: :current_result def save_answer answer current_result.save_answer answer save! touch :assessment_updated_at end def complete? current_result.nil? end def incomplete? !complete? end def results_summary "#{results.select(&:finished?).count}/#{results.count}" end def full_history persisted_results.flat_map(&:answers).map(&:question_id) end def by_url? method_applied == "By URL" end def by_mail? method_applied == "By mail" end def group_index_name return "" if group_index.nil? event_groups[group_index] end private def assign_group_index return unless event_groups.any? self.group_index = restarted_assessment.try(:group_index) || self.class.by_event(event).count % event_groups.length end def event_groups StudyEngine.groups[event] || [] end end end