require "study_engine/form" require "study_engine/assessment" require "study_engine/config" module StudyEngine class BeginAssessmentForm < Form wraps "study_engine/assessment" attributes :study_id, :event, :method_applied, :coordinator attr_accessor :restart delegate :study, :site, :id, to: :study_id, prefix: true delegate :study=, :site=, :id=, to: :study_id, prefix: true validate :presence_of_event validate :format_of_study_id validate :uniqueness_of_study_id_and_event, unless: :restart validate :presence_of_previous_events def study_id_study study_options.one? ? study_options.first : study_id.study end def study_id_site site_options.one? ? site_options.first : study_id.site end def study_id_id id_options.one? ? id_options.first : study_id.id end def study_id @study_id ||= StudyID.new end def method_applied @method_applied || "In-person" end def existing_assessment if study_id and new_record? @existing_assessment ||= Assessment.by_study_id(study_id).where(event: event).last end end def restartable? existing_assessment.try(:incomplete?) end def study_options StudyID::Bank.studies_grouped_by_site.fetch(coordinator.try(:site_id)) { StudyID::Bank.studies } end def site_options coordinator.try(:site_id).present? ? [coordinator.site_id] : StudyID::Bank.sites end def id_options ids_grouped_by_study_and_site[study_id_study.to_s + study_id_site.to_s] end def ids_grouped_by_study_and_site StudyID::Bank.ids_grouped_by_study_and_site end delegate :by_url?, :by_mail?, :group_index_name, :created_at, :assessment_updated_at, to: :@model private def format_of_study_id if study_id.present? unless study_id.valid? errors.add :base, "METRC study ID must be in the following format: XXX-XXX-####" end else errors.add :base, "METRC study ID can not be blank. Enter ID in the following format: XXX-XXX-####" end end def presence_of_event if event.blank? events = StudyEngine.events.dup events.map!(&:titleize) events.last.prepend("or ") events = events.join(", ") errors.add :base, "Study event can not be blank. Choose #{events} assessment." end end def uniqueness_of_study_id_and_event if existing_assessment errors.add :base, "Assessment data has already been collected for this ID number and event. Please check these fields to confirm you are beginning an assessment for the correct ID and event." end end def presence_of_previous_events index = StudyEngine.events.index(event) return if index.nil? || index.zero? previous_events = StudyEngine.events[0...index] previous_events.each do |previous_event| if Assessment.by_study_id(study_id).by_event(previous_event).none? errors.add :base, "#{previous_event.capitalize} assessment must already exist to administer #{event} assessment" end end end end end