diff --git a/app/controllers/api/v2/plans_controller.rb b/app/controllers/api/v2/plans_controller.rb index 7714e9c892..aeb9144e7b 100644 --- a/app/controllers/api/v2/plans_controller.rb +++ b/app/controllers/api/v2/plans_controller.rb @@ -17,6 +17,8 @@ def show raise Pundit::NotAuthorizedError unless plans_policy.show? @items = [@plan] + @question_and_answer = ActiveModel::Type::Boolean.new.cast(params[:question_and_answer]) + render '/api/v2/plans/index', status: :ok end @@ -26,6 +28,8 @@ def index @plans = PlansPolicy::Scope.new(@resource_owner).resolve @items = paginate_response(results: @plans) + @question_and_answer = ActiveModel::Type::Boolean.new.cast(params[:question_and_answer]) + render '/api/v2/plans/index', status: :ok end end diff --git a/app/presenters/api/v2/plan_presenter.rb b/app/presenters/api/v2/plan_presenter.rb index 204cd68011..0f0257f093 100644 --- a/app/presenters/api/v2/plan_presenter.rb +++ b/app/presenters/api/v2/plan_presenter.rb @@ -35,6 +35,22 @@ def identifier Identifier.new(value: Rails.application.routes.url_helpers.api_v2_plan_url(@plan)) end + # Fetch all questions and answers from a plan, regardless of theme + def fetch_all_q_and_a # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity + return [] unless @plan&.questions.present? + + @plan.questions.filter_map do |q| + a = @plan.answers.find { |ans| ans.question_id == q.id } + next unless a.present? && !a.blank? + + { + title: "Question #{q.number || q.id}", + question: q.text.to_s, + answer: a.text.to_s + } + end + end + private # Retrieve the answers that have the Budget theme diff --git a/app/views/api/v2/plans/_show.json.jbuilder b/app/views/api/v2/plans/_show.json.jbuilder index 0de52775a3..1ce53c235d 100644 --- a/app/views/api/v2/plans/_show.json.jbuilder +++ b/app/views/api/v2/plans/_show.json.jbuilder @@ -68,5 +68,22 @@ unless @minimal json.title template.title end end + + if @question_and_answer + json.questions_and_answers do + outputs.each do |output| + q_and_a = presenter.send(:fetch_all_q_and_a) + next if q_and_a.blank? + + json.set! output.id.to_s do + json.array! q_and_a do |item| + json.title item[:title] + json.question item[:question] + json.answer item[:answer] + end + end + end + end + end end end