diff --git a/.rubocop.yml b/.rubocop.yml index c7e11b1cc..31f1ae694 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -5,3 +5,148 @@ AllCops: - 'db/seeds.rb' require: rubocop-rails + +Layout/SpaceAroundOperators: + AllowForAlignment: false + EnforcedStyleForExponentOperator: no_space + +Layout/DotPosition: + EnforcedStyle: leading + +Style/TrailingCommaInArguments: + EnforcedStyleForMultiline: comma + +Style/TrailingCommaInArrayLiteral: + EnforcedStyleForMultiline: comma + +Style/TrailingCommaInHashLiteral: + EnforcedStyleForMultiline: comma + +Layout/ArrayAlignment: + Enabled: false + +Layout/MultilineMethodCallIndentation: + Enabled: false + +Style/ConditionalAssignment: + Enabled: false + +Style/Documentation: + Enabled: false + +Style/CommentAnnotation: + Enabled: false + +Style/MixinUsage: + Enabled: false + +Style/CombinableLoops: + Enabled: false + +Style/ClassVars: + Enabled: false + +Style/GuardClause: + Enabled: false + +Style/HashLikeCase: + Enabled: false + +Layout/LineLength: + Enabled: false + +Metrics/AbcSize: + Enabled: false + +Metrics/BlockLength: + Enabled: false + +Metrics/CyclomaticComplexity: + Enabled: false + +Metrics/ClassLength: + Enabled: false + +Metrics/MethodLength: + Enabled: false + +Metrics/ModuleLength: + Enabled: false + +Metrics/PerceivedComplexity: + Enabled: false + +Naming/VariableNumber: + Enabled: false + +Naming/AccessorMethodName: + Enabled: false + +Naming/ConstantName: + Enabled: false + +Naming/MethodName: + Enabled: false + +Naming/PredicateName: + Enabled: false + +Lint/AssignmentInCondition: + Enabled: false + +Lint/DuplicateBranch: + Enabled: false + +Lint/EmptyClass: + Enabled: false + +Lint/UselessAssignment: + Enabled: false + +Lint/DuplicateMethods: + Enabled: false + +Lint/EmptyBlock: + Enabled: false + +Rails/Date: + Enabled: false + +Rails/I18nLocaleTexts: + Enabled: false + +Rails/SkipsModelValidations: + Enabled: false + +Rails/CreateTableWithTimestamps: + Enabled: false + +Rails/HasManyOrHasOneDependent: + Enabled: false + +Rails/HasAndBelongsToMany: + Enabled: false + +Rails/BulkChangeTable: + Enabled: false + +Rails/ReversibleMigration: + Enabled: false + +Rails/FilePath: + Enabled: false + +Rails/UniqueValidationWithoutIndex: + Enabled: false + +Rails/OutputSafety: + Enabled: false + +Rails/LexicallyScopedActionFilter: + Enabled: false + +Rails/DynamicFindBy: + Enabled: false + +Security/Open: + Enabled: false diff --git a/Gemfile b/Gemfile index 9acc23003..235fd6b42 100644 --- a/Gemfile +++ b/Gemfile @@ -45,7 +45,7 @@ gem "image_processing", "~> 1.12" gem "brakeman" gem "bundler-audit" gem "rubocop-rails" - +gem "rubocop-rspec" gem 'active_model_serializers', '>= 0.10.13' gem 'acts-as-list' gem 'aws-sdk-rails', '>= 3.6.1' diff --git a/Gemfile.lock b/Gemfile.lock index 946e0aa23..9d751a120 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -412,6 +412,8 @@ GEM activesupport (>= 4.2.0) rack (>= 1.1) rubocop (>= 1.7.0, < 2.0) + rubocop-rspec (2.11.1) + rubocop (~> 1.19) ruby-graphviz (1.2.5) rexml ruby-progressbar (1.11.0) @@ -535,6 +537,7 @@ DEPENDENCIES rspec-rails (>= 5.1.1) rspec_junit_formatter rubocop-rails + rubocop-rspec sass-rails (>= 6.0.0) selenium-webdriver sidekiq diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb index d67269728..9aec23053 100644 --- a/app/channels/application_cable/channel.rb +++ b/app/channels/application_cable/channel.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ApplicationCable class Channel < ActionCable::Channel::Base end diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb index 0ff5442f4..8d6c2a1bf 100644 --- a/app/channels/application_cable/connection.rb +++ b/app/channels/application_cable/connection.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ApplicationCable class Connection < ActionCable::Connection::Base end diff --git a/app/channels/export_channel.rb b/app/channels/export_channel.rb index 343172954..a39b4cb1b 100644 --- a/app/channels/export_channel.rb +++ b/app/channels/export_channel.rb @@ -1,8 +1,9 @@ +# frozen_string_literal: true + class ExportChannel < ApplicationCable::Channel def subscribed stream_from "exports_channel_#{params[:uuid]}" end - def unsubscribed - end + def unsubscribed; end end diff --git a/app/controllers/admin/barriers_controller.rb b/app/controllers/admin/barriers_controller.rb index 916eedbc9..e03beebf3 100644 --- a/app/controllers/admin/barriers_controller.rb +++ b/app/controllers/admin/barriers_controller.rb @@ -1,45 +1,47 @@ -class Admin::BarriersController < AdminController - before_action :ensure_admin - before_action :set_barrier, only: [:show, :edit, :update, :destroy] +# frozen_string_literal: true - def index - @barriers = Barrier.all - end +module Admin + class BarriersController < AdminController + before_action :ensure_admin + before_action :set_barrier, only: %i[show edit update destroy] - def show - end + def index + @barriers = Barrier.all + end - def new - @barrier = Barrier.new - end + def show; end - def edit - end + def new + @barrier = Barrier.new + end + + def edit; end - def create - @barrier = Barrier.new(barrier_params) + def create + @barrier = Barrier.new(barrier_params) - if @barrier.save - redirect_to admin_barrier_path(@barrier), notice: 'Barrier was successfully created.' - else - render :new + if @barrier.save + redirect_to admin_barrier_path(@barrier), notice: 'Barrier was successfully created.' + else + render :new + end end - end - def update - if @barrier.update(barrier_params) - redirect_to admin_barrier_path(@barrier), notice: 'Barrier was successfully updated.' - else - render :edit + def update + if @barrier.update(barrier_params) + redirect_to admin_barrier_path(@barrier), notice: 'Barrier was successfully updated.' + else + render :edit + end end - end - def destroy - @barrier.destroy - redirect_to admin_barriers_url, notice: 'Barrier was successfully destroyed.' - end + def destroy + @barrier.destroy + redirect_to admin_barriers_url, notice: 'Barrier was successfully destroyed.' + end + + private - private def set_barrier @barrier = Barrier.find(params[:id]) end @@ -47,4 +49,5 @@ def set_barrier def barrier_params params.require(:barrier).permit(:name, :description) end + end end diff --git a/app/controllers/admin/collections_controller.rb b/app/controllers/admin/collections_controller.rb index 5b1de874b..c283c8073 100644 --- a/app/controllers/admin/collections_controller.rb +++ b/app/controllers/admin/collections_controller.rb @@ -1,33 +1,34 @@ -class Admin::CollectionsController < AdminController - before_action :set_collection, only: [:show, :edit, :copy, - :submit, :publish, - :update, :destroy, - :events - ] - - def index - @quarter = params[:quarter].present? ? params[:quarter].to_i : nil - @year = params[:year].present? ? params[:year].to_i : nil - - if performance_manager_permissions? - if @quarter && @year - @collections = Collection.where(quarter: @quarter, year: @year) - .order('organizations.name', :year, :quarter, 'service_providers.name') - .includes(:organization, :service_provider) - elsif @quarter - @collections = Collection.where(quarter: @quarter) - .order('organizations.name', :year, :quarter, 'service_providers.name') - .includes(:organization, :service_provider) - else - @collections = Collection.all - .order('organizations.name', :year, :quarter, 'service_providers.name') - .includes(:organization, :service_provider) - end - else - if @quarter && @year +# frozen_string_literal: true + +module Admin + class CollectionsController < AdminController + before_action :set_collection, only: %i[show edit copy + submit publish + update destroy + events] + + def index + @quarter = params[:quarter].present? ? params[:quarter].to_i : nil + @year = params[:year].present? ? params[:year].to_i : nil + + if performance_manager_permissions? + if @quarter && @year + @collections = Collection.where(quarter: @quarter, year: @year) + .order('organizations.name', :year, :quarter, 'service_providers.name') + .includes(:organization, :service_provider) + elsif @quarter + @collections = Collection.where(quarter: @quarter) + .order('organizations.name', :year, :quarter, 'service_providers.name') + .includes(:organization, :service_provider) + else + @collections = Collection.all + .order('organizations.name', :year, :quarter, 'service_providers.name') + .includes(:organization, :service_provider) + end + elsif @quarter && @year @collections = current_user.collections.where(quarter: @quarter, year: @year) - .order('organizations.name', :year, :quarter, 'service_providers.name') - .includes(:organization, :service_provider) + .order('organizations.name', :year, :quarter, 'service_providers.name') + .includes(:organization, :service_provider) elsif @quarter @collections = current_user.collections.where(quarter: @quarter) .order('organizations.name', :year, :quarter, 'service_providers.name') @@ -38,91 +39,91 @@ def index .includes(:organization, :service_provider) end end - end - def show - ensure_collection_owner(collection: @collection) - end + def show + ensure_collection_owner(collection: @collection) + end - def new - @collection = Collection.new - @collection.user = current_user - @collection.organization_id = params[:organization_id] - @collection.service_provider_id = params[:service_provider_id] - @collection.year = fiscal_year(Date.today) - @collection.quarter = fiscal_quarter(Date.today) - end + def new + @collection = Collection.new + @collection.user = current_user + @collection.organization_id = params[:organization_id] + @collection.service_provider_id = params[:service_provider_id] + @collection.year = fiscal_year(Date.today) + @collection.quarter = fiscal_quarter(Date.today) + end - def edit - ensure_collection_owner(collection: @collection) - end + def edit + ensure_collection_owner(collection: @collection) + end - def submit - @collection.submit! - Event.log_event(Event.names[:collection_submitted], "Collection", @collection.id, "Collection #{@collection.name} submitted at #{DateTime.now}", current_user.id) - UserMailer.collection_notification(collection_id: @collection.id).deliver_later - redirect_to admin_collection_path(@collection), notice: 'Collection has been submitted successfully.' - end + def submit + @collection.submit! + Event.log_event(Event.names[:collection_submitted], 'Collection', @collection.id, "Collection #{@collection.name} submitted at #{DateTime.now}", current_user.id) + UserMailer.collection_notification(collection_id: @collection.id).deliver_later + redirect_to admin_collection_path(@collection), notice: 'Collection has been submitted successfully.' + end - def publish - @collection.publish! - Event.log_event(Event.names[:collection_published], "Collection", @collection.id, "Collection #{@collection.name} published at #{DateTime.now}", current_user.id) - redirect_to admin_collection_path(@collection), notice: 'Collection has been published successfully.' - end + def publish + @collection.publish! + Event.log_event(Event.names[:collection_published], 'Collection', @collection.id, "Collection #{@collection.name} published at #{DateTime.now}", current_user.id) + redirect_to admin_collection_path(@collection), notice: 'Collection has been published successfully.' + end - def copy - ensure_collection_owner(collection: @collection) + def copy + ensure_collection_owner(collection: @collection) - respond_to do |format| - new_collection = @collection.duplicate!(new_user: current_user) + respond_to do |format| + new_collection = @collection.duplicate!(new_user: current_user) - if new_collection.valid? - Event.log_event(Event.names[:collection_copied], "Collection", @collection.id, "Collection #{@collection.name} copied at #{DateTime.now}", current_user.id) + if new_collection.valid? + Event.log_event(Event.names[:collection_copied], 'Collection', @collection.id, "Collection #{@collection.name} copied at #{DateTime.now}", current_user.id) - format.html { redirect_to admin_collection_path(new_collection), notice: 'Collection was successfully copied.' } - format.json { render :show, status: :created, location: new_collection } - else - format.html { render :new } - format.json { render json: new_collection.errors, status: :unprocessable_entity } + format.html { redirect_to admin_collection_path(new_collection), notice: 'Collection was successfully copied.' } + format.json { render :show, status: :created, location: new_collection } + else + format.html { render :new } + format.json { render json: new_collection.errors, status: :unprocessable_entity } + end end end - end - def create - @collection = Collection.new(collection_params) + def create + @collection = Collection.new(collection_params) - @collection.user = current_user - if @collection.save - Event.log_event(Event.names[:collection_created], "Collection", @collection.id, "Collection #{@collection.name} created at #{DateTime.now}", current_user.id) - redirect_to admin_collection_path(@collection), notice: 'Collection was successfully created.' - else - render :new + @collection.user = current_user + if @collection.save + Event.log_event(Event.names[:collection_created], 'Collection', @collection.id, "Collection #{@collection.name} created at #{DateTime.now}", current_user.id) + redirect_to admin_collection_path(@collection), notice: 'Collection was successfully created.' + else + render :new + end end - end - def update - ensure_collection_owner(collection: @collection) + def update + ensure_collection_owner(collection: @collection) - if @collection.update(collection_params) - Event.log_event(Event.names[:collection_updated], "Collection", @collection.id, "Collection #{@collection.name} updated at #{DateTime.now}", current_user.id) - redirect_to admin_collection_path(@collection), notice: 'Collection was successfully updated.' - else - render :edit + if @collection.update(collection_params) + Event.log_event(Event.names[:collection_updated], 'Collection', @collection.id, "Collection #{@collection.name} updated at #{DateTime.now}", current_user.id) + redirect_to admin_collection_path(@collection), notice: 'Collection was successfully updated.' + else + render :edit + end end - end - def destroy - ensure_collection_owner(collection: @collection) - @collection.destroy - Event.log_event(Event.names[:collection_deleted], "Collection", @collection.id, "Collection #{@collection.name} deleted at #{DateTime.now}", current_user.id) - redirect_to admin_collections_url, notice: 'Collection was successfully destroyed.' - end + def destroy + ensure_collection_owner(collection: @collection) + @collection.destroy + Event.log_event(Event.names[:collection_deleted], 'Collection', @collection.id, "Collection #{@collection.name} deleted at #{DateTime.now}", current_user.id) + redirect_to admin_collections_url, notice: 'Collection was successfully destroyed.' + end - def events - @events = Event.where(object_type: "Collection", object_id: @collection.id).order(:created_at) - end + def events + @events = Event.where(object_type: 'Collection', object_id: @collection.id).order(:created_at) + end + + private - private def set_collection if performance_manager_permissions? @collection = Collection.find(params[:id]) @@ -147,4 +148,5 @@ def collection_params :rating, ) end + end end diff --git a/app/controllers/admin/digital_product_versions_controller.rb b/app/controllers/admin/digital_product_versions_controller.rb index b10f921d2..b6209dd15 100644 --- a/app/controllers/admin/digital_product_versions_controller.rb +++ b/app/controllers/admin/digital_product_versions_controller.rb @@ -1,52 +1,54 @@ -class Admin::DigitalProductVersionsController < ApplicationController +# frozen_string_literal: true - before_action :set_digital_product - before_action :set_digital_product_version, only: [:show, :edit, :update, :destroy] +module Admin + class DigitalProductVersionsController < ApplicationController + before_action :set_digital_product + before_action :set_digital_product_version, only: %i[show edit update destroy] - def index - @digital_product_versions = DigitalProductVersion.where(digital_product_id: params[:digital_product_id]) - end + def index + @digital_product_versions = DigitalProductVersion.where(digital_product_id: params[:digital_product_id]) + end - def show - end + def show; end - def create - @digital_product_version = DigitalProductVersion.new(digital_product_version_params) + def create + @digital_product_version = DigitalProductVersion.new(digital_product_version_params) - if @digital_product_version.save - redirect_to admin_digital_product_digital_product_versions_path(@digital_product) - else - render :new, status: :unprocessable_entity + if @digital_product_version.save + redirect_to admin_digital_product_digital_product_versions_path(@digital_product) + else + render :new, status: :unprocessable_entity + end end - end - def update - @digital_product_version = DigitalProductVersion.find(params[:id]) + def update + @digital_product_version = DigitalProductVersion.find(params[:id]) - if @digital_product_version.update(digital_product_version_params) - redirect_to admin_digital_product_digital_product_versions_path(@digital_product) - else - render :edit, status: :unprocessable_entity + if @digital_product_version.update(digital_product_version_params) + redirect_to admin_digital_product_digital_product_versions_path(@digital_product) + else + render :edit, status: :unprocessable_entity + end end - end - def edit - @digital_product_version = DigitalProductVersion.find(params[:id]) - end + def edit + @digital_product_version = DigitalProductVersion.find(params[:id]) + end - def new - @digital_product_version = DigitalProductVersion.new - end + def new + @digital_product_version = DigitalProductVersion.new + end - def destroy - digital_product_version = DigitalProductVersion.destroy(params[:id]) - respond_to do | format | - format.turbo_stream - format.html { redirect_to admin_digital_product_digital_product_versions_path(@digital_product) } + def destroy + digital_product_version = DigitalProductVersion.destroy(params[:id]) + respond_to do |format| + format.turbo_stream + format.html { redirect_to admin_digital_product_digital_product_versions_path(@digital_product) } + end end - end - private + private + # Use callbacks to share common setup or constraints between actions. def set_digital_product @digital_product = DigitalProduct.find(params[:digital_product_id]) @@ -60,4 +62,5 @@ def set_digital_product_version def digital_product_version_params params.require(:digital_product_version).permit(:digital_product_id, :store_url, :platform, :version_number, :publish_date, :description, :whats_new, :screenshot_url, :device, :language, :average_rating, :number_of_ratings) end + end end diff --git a/app/controllers/admin/digital_products_controller.rb b/app/controllers/admin/digital_products_controller.rb index e95b4770a..6f1aa8dd4 100644 --- a/app/controllers/admin/digital_products_controller.rb +++ b/app/controllers/admin/digital_products_controller.rb @@ -1,164 +1,160 @@ -class Admin::DigitalProductsController < AdminController - before_action :set_digital_product, only: [ - :show, :edit, :update, :destroy, - :add_tag, :remove_tag, - :add_organization, :remove_organization, - :add_user, :remove_user, - :submit, :publish, :archive, :reset - ] - - def index - @digital_products = DigitalProduct.order(:name, :service).page(params[:page]) - end +# frozen_string_literal: true + +module Admin + class DigitalProductsController < AdminController + before_action :set_digital_product, only: %i[ + show edit update destroy + add_tag remove_tag + add_organization remove_organization + add_user remove_user + submit publish archive reset + ] + + def index + @digital_products = DigitalProduct.order(:name, :service).page(params[:page]) + end - def review - @digital_products = DigitalProduct.where("aasm_state = 'created' OR aasm_state = 'edited'").order(:name, :service).page(params[:page]) - end + def review + @digital_products = DigitalProduct.where("aasm_state = 'created' OR aasm_state = 'edited'").order(:name, :service).page(params[:page]) + end - def show - end + def show; end - def new - @digital_product = DigitalProduct.new - end + def new + @digital_product = DigitalProduct.new + end - def edit - end + def edit; end - def create - @digital_product = DigitalProduct.new(digital_product_params) - @digital_product.organization_list.add(current_user.organization_id) + def create + @digital_product = DigitalProduct.new(digital_product_params) + @digital_product.organization_list.add(current_user.organization_id) - if @digital_product.save - current_user.add_role(:contact, @digital_product) - redirect_to admin_digital_product_path(@digital_product), notice: 'Digital product was successfully created.' - else - render :new + if @digital_product.save + current_user.add_role(:contact, @digital_product) + redirect_to admin_digital_product_path(@digital_product), notice: 'Digital product was successfully created.' + else + render :new + end end - end - def update - if @digital_product.update(digital_product_params) - redirect_to admin_digital_product_path(@digital_product), notice: 'Digital product was successfully updated.' - else - render :edit + def update + if @digital_product.update(digital_product_params) + redirect_to admin_digital_product_path(@digital_product), notice: 'Digital product was successfully updated.' + else + render :edit + end end - end - def destroy - @digital_product.destroy - redirect_to admin_digital_products_url, notice: 'Digital product was successfully destroyed.' - end + def destroy + @digital_product.destroy + redirect_to admin_digital_products_url, notice: 'Digital product was successfully destroyed.' + end - def add_tag - @digital_product.tag_list.add(digital_product_params[:tag_list].split(',')) - @digital_product.save - end + def add_tag + @digital_product.tag_list.add(digital_product_params[:tag_list].split(',')) + @digital_product.save + end - def remove_tag - @digital_product.tag_list.remove(digital_product_params[:tag_list].split(',')) - @digital_product.save - end + def remove_tag + @digital_product.tag_list.remove(digital_product_params[:tag_list].split(',')) + @digital_product.save + end - def add_organization - @digital_product.organization_list.add(params[:organization_id]) - @digital_product.save - set_sponsoring_agency_options - end + def add_organization + @digital_product.organization_list.add(params[:organization_id]) + @digital_product.save + set_sponsoring_agency_options + end - def remove_organization - @digital_product.organization_list.remove(params[:organization_id]) - @digital_product.save - set_sponsoring_agency_options - end + def remove_organization + @digital_product.organization_list.remove(params[:organization_id]) + @digital_product.save + set_sponsoring_agency_options + end - def add_user - @user = User.find_by_email(params[:user][:email]) + def add_user + @user = User.find_by_email(params[:user][:email]) - if @user - @user.add_role(:contact, @digital_product) + @user&.add_role(:contact, @digital_product) end - end - def remove_user - @user = User.find_by_id(params[:user][:id]) - if @user - @user.remove_role(:contact, @digital_product) + def remove_user + @user = User.find_by_id(params[:user][:id]) + @user&.remove_role(:contact, @digital_product) end - end - def submit - if @digital_product.submit! - Event.log_event(Event.names[:digital_product_submitted], "Digital Product", @digital_product.id, "Digital Product #{@digital_product.name} submitted at #{DateTime.now}", current_user.id) + def submit + if @digital_product.submit! + Event.log_event(Event.names[:digital_product_submitted], 'Digital Product', @digital_product.id, "Digital Product #{@digital_product.name} submitted at #{DateTime.now}", current_user.id) - UserMailer.notification( - title: "Digital Product has been submitted", - body: "Digital Product #{@digital_product.name} submitted at #{DateTime.now} by #{current_user.email}", - path: admin_digital_product_url(@digital_product), - emails: User.registry_managers.collect(&:email) - ).deliver_later + UserMailer.notification( + title: 'Digital Product has been submitted', + body: "Digital Product #{@digital_product.name} submitted at #{DateTime.now} by #{current_user.email}", + path: admin_digital_product_url(@digital_product), + emails: User.registry_managers.collect(&:email), + ).deliver_later - redirect_to admin_digital_product_path(@digital_product), notice: 'Digital product was successfully submitted.' - else - render :edit + redirect_to admin_digital_product_path(@digital_product), notice: 'Digital product was successfully submitted.' + else + render :edit + end end - end - def publish - ensure_digital_product_permissions(digital_product: @digital_product) + def publish + ensure_digital_product_permissions(digital_product: @digital_product) - if @digital_product.publish! - Event.log_event(Event.names[:digital_product_published], "Digital Product", @digital_product.id, "Digital Product #{@digital_product.name} published at #{DateTime.now}", current_user.id) + if @digital_product.publish! + Event.log_event(Event.names[:digital_product_published], 'Digital Product', @digital_product.id, "Digital Product #{@digital_product.name} published at #{DateTime.now}", current_user.id) - UserMailer.notification( - title: "Digital Product has been published", - body: "Digital Product #{@digital_product.name} published at #{DateTime.now} by #{current_user.email}", - path: admin_digital_product_url(@digital_product), - emails: User.registry_managers.collect(&:email) # + @digital_product.contact_emails - ).deliver_later + UserMailer.notification( + title: 'Digital Product has been published', + body: "Digital Product #{@digital_product.name} published at #{DateTime.now} by #{current_user.email}", + path: admin_digital_product_url(@digital_product), + emails: User.registry_managers.collect(&:email), # + @digital_product.contact_emails + ).deliver_later - redirect_to admin_digital_product_path(@digital_product), notice: "Digital Product #{@digital_product.name} was published." - else - render :edit + redirect_to admin_digital_product_path(@digital_product), notice: "Digital Product #{@digital_product.name} was published." + else + render :edit + end end - end - def archive - ensure_digital_product_permissions(digital_product: @digital_product) + def archive + ensure_digital_product_permissions(digital_product: @digital_product) - if @digital_product.archive! - Event.log_event(Event.names[:digital_product_archived], "Digital Product", @digital_product.id, "Digital Product #{@digital_product.name} archived at #{DateTime.now}", current_user.id) - redirect_to admin_digital_product_path(@digital_product), notice: "Digital Product #{@digital_product.name} was archived." - else - render :edit + if @digital_product.archive! + Event.log_event(Event.names[:digital_product_archived], 'Digital Product', @digital_product.id, "Digital Product #{@digital_product.name} archived at #{DateTime.now}", current_user.id) + redirect_to admin_digital_product_path(@digital_product), notice: "Digital Product #{@digital_product.name} was archived." + else + render :edit + end end - end - def reset - ensure_digital_product_permissions(digital_product: @digital_product) + def reset + ensure_digital_product_permissions(digital_product: @digital_product) - if @digital_product.reset! - Event.log_event(Event.names[:digital_product_reset], "Digital Service Account", @digital_product.id, "Digital Product #{@digital_product.name} reset at #{DateTime.now}", current_user.id) - redirect_to admin_digital_product_path(@digital_product), notice: "Digital Service Account #{@digital_product.name} was reset." - else - render :edit + if @digital_product.reset! + Event.log_event(Event.names[:digital_product_reset], 'Digital Service Account', @digital_product.id, "Digital Product #{@digital_product.name} reset at #{DateTime.now}", current_user.id) + redirect_to admin_digital_product_path(@digital_product), notice: "Digital Service Account #{@digital_product.name} was reset." + else + render :edit + end end - end - def search - search_text = params[:search] - organization_id = params[:organization_id] - - @digital_products = DigitalProduct.all - @digital_products = @digital_products.where("name ilike '%#{search_text}%'") if search_text && search_text.length >= 3 - @digital_products = @digital_products.tagged_with(organization_id, context: "organizations") if organization_id.present? && organization_id != '' - @digital_products = @digital_products.where("service = ?", params[:service]) if params[:service].present? && params[:service] != 'All' - @digital_products = @digital_products.where("aasm_state = ?", params[:aasm_state].downcase) if params[:aasm_state].present? && params[:aasm_state] != 'All' - @digital_products - end + def search + search_text = params[:search] + organization_id = params[:organization_id] + @digital_products = DigitalProduct.all + @digital_products = @digital_products.where("name ilike '%#{search_text}%'") if search_text && search_text.length >= 3 + @digital_products = @digital_products.tagged_with(organization_id, context: 'organizations') if organization_id.present? && organization_id != '' + @digital_products = @digital_products.where('service = ?', params[:service]) if params[:service].present? && params[:service] != 'All' + @digital_products = @digital_products.where('aasm_state = ?', params[:aasm_state].downcase) if params[:aasm_state].present? && params[:aasm_state] != 'All' + @digital_products + end - private + private def set_digital_product @digital_product = DigitalProduct.find(params[:id]) @@ -167,9 +163,7 @@ def set_digital_product def set_sponsoring_agency_options @sponsoring_agency_options = Organization.all.order(:name) - if @sponsoring_agency_options && @digital_product - @sponsoring_agency_options = @sponsoring_agency_options - @digital_product.sponsoring_agencies - end + @sponsoring_agency_options -= @digital_product.sponsoring_agencies if @sponsoring_agency_options && @digital_product end def digital_product_params @@ -187,7 +181,8 @@ def digital_product_params :long_description, :certified_at, :tag_list, - :organization_list + :organization_list, ) end + end end diff --git a/app/controllers/admin/digital_service_accounts_controller.rb b/app/controllers/admin/digital_service_accounts_controller.rb index 8bfa5c4c0..b43f920a4 100644 --- a/app/controllers/admin/digital_service_accounts_controller.rb +++ b/app/controllers/admin/digital_service_accounts_controller.rb @@ -2,194 +2,188 @@ module Admin class DigitalServiceAccountsController < AdminController + before_action :set_digital_service_account, only: %i[ + show edit update destroy + add_tag remove_tag + add_user remove_user + add_organization remove_organization + submit publish archive reset + ] + + def index + @digital_service_accounts = DigitalServiceAccount.order(:name).page(params[:page]) + end - before_action :set_digital_service_account, only: [ - :show, :edit, :update, :destroy, - :add_tag, :remove_tag, - :add_user, :remove_user, - :add_organization, :remove_organization, - :submit, :publish, :archive, :reset - ] - - def index - @digital_service_accounts = DigitalServiceAccount.order(:name).page(params[:page]) - end - - def review - ensure_admin_or_contact(@digital_service_account) - @digital_service_accounts = DigitalServiceAccount.where("aasm_state = 'created' OR aasm_state = 'edited'").order(:organization_id, :name).page(params[:page]) - end + def review + ensure_admin_or_contact(@digital_service_account) + @digital_service_accounts = DigitalServiceAccount.where("aasm_state = 'created' OR aasm_state = 'edited'").order(:organization_id, :name).page(params[:page]) + end - def show - ensure_admin_or_contact(@digital_service_account) - end + def show + ensure_admin_or_contact(@digital_service_account) + end - def new - ensure_admin - @digital_service_account = DigitalServiceAccount.new - end + def new + ensure_admin + @digital_service_account = DigitalServiceAccount.new + end - def edit - ensure_admin_or_contact(@digital_service_account) - end + def edit + ensure_admin_or_contact(@digital_service_account) + end - def create - ensure_admin - @digital_service_account = DigitalServiceAccount.new(digital_service_account_params) - @digital_service_account.organization_list.add(current_user.organization_id) + def create + ensure_admin + @digital_service_account = DigitalServiceAccount.new(digital_service_account_params) + @digital_service_account.organization_list.add(current_user.organization_id) - if @digital_service_account.save - current_user.add_role(:contact, @digital_service_account) + if @digital_service_account.save + current_user.add_role(:contact, @digital_service_account) - Event.log_event(Event.names[:digital_service_account_created], "Digital Service Account", @digital_service_account.id, "Digital Service Account #{@digital_service_account.name} created at #{DateTime.now}", current_user.id) + Event.log_event(Event.names[:digital_service_account_created], 'Digital Service Account', @digital_service_account.id, "Digital Service Account #{@digital_service_account.name} created at #{DateTime.now}", current_user.id) - UserMailer.social_media_account_created_notification(digital_service_account: @digital_service_account, link: admin_digital_service_account_path(@digital_service_account)).deliver_later + UserMailer.social_media_account_created_notification(digital_service_account: @digital_service_account, link: admin_digital_service_account_path(@digital_service_account)).deliver_later - redirect_to admin_digital_service_account_path(@digital_service_account), notice: 'Digital service account was successfully created.' - else - render :new + redirect_to admin_digital_service_account_path(@digital_service_account), notice: 'Digital service account was successfully created.' + else + render :new + end end - end - def update - ensure_admin_or_contact(@digital_service_account) - if @digital_service_account.update(digital_service_account_params) - Event.log_event(Event.names[:digital_service_account_updated], 'DigitalServiceAccount', - @digital_service_account.id, "updated by #{current_user.email} on #{Date.today}", current_user.id) - @digital_service_account.update_state! - redirect_to admin_digital_service_account_path(@digital_service_account), - notice: 'Digital service account was successfully updated.' - else - render :edit + def update + ensure_admin_or_contact(@digital_service_account) + if @digital_service_account.update(digital_service_account_params) + Event.log_event(Event.names[:digital_service_account_updated], 'DigitalServiceAccount', + @digital_service_account.id, "updated by #{current_user.email} on #{Date.today}", current_user.id) + @digital_service_account.update_state! + redirect_to admin_digital_service_account_path(@digital_service_account), + notice: 'Digital service account was successfully updated.' + else + render :edit + end end - end - def destroy - ensure_admin_or_contact(@digital_service_account) - @digital_service_account.destroy - Event.log_event(Event.names[:digital_service_account_deleted], 'DigitalServiceAccount', - @digital_service_account.id, "deleted by #{current_user.email} on #{Date.today}", current_user.id) - redirect_to admin_digital_service_accounts_url, notice: 'Digital service account was deleted.' - end + def destroy + ensure_admin_or_contact(@digital_service_account) + @digital_service_account.destroy + Event.log_event(Event.names[:digital_service_account_deleted], 'DigitalServiceAccount', + @digital_service_account.id, "deleted by #{current_user.email} on #{Date.today}", current_user.id) + redirect_to admin_digital_service_accounts_url, notice: 'Digital service account was deleted.' + end - def add_tag - ensure_admin_or_contact(@digital_service_account) - @digital_service_account.tag_list.add(digital_service_account_params[:tag_list].split(',')) - @digital_service_account.save - end + def add_tag + ensure_admin_or_contact(@digital_service_account) + @digital_service_account.tag_list.add(digital_service_account_params[:tag_list].split(',')) + @digital_service_account.save + end - def remove_tag - ensure_admin_or_contact(@digital_service_account) - @digital_service_account.tag_list.remove(digital_service_account_params[:tag_list].split(',')) - @digital_service_account.save - end + def remove_tag + ensure_admin_or_contact(@digital_service_account) + @digital_service_account.tag_list.remove(digital_service_account_params[:tag_list].split(',')) + @digital_service_account.save + end - def add_organization - ensure_admin_or_contact(@digital_service_account) - @digital_service_account.organization_list.add(params[:organization_id]) - @digital_service_account.save - set_sponsoring_agency_options - end + def add_organization + ensure_admin_or_contact(@digital_service_account) + @digital_service_account.organization_list.add(params[:organization_id]) + @digital_service_account.save + set_sponsoring_agency_options + end - def remove_organization - ensure_admin_or_contact(@digital_service_account) - @digital_service_account.organization_list.remove(params[:organization_id]) - @digital_service_account.save - set_sponsoring_agency_options - end + def remove_organization + ensure_admin_or_contact(@digital_service_account) + @digital_service_account.organization_list.remove(params[:organization_id]) + @digital_service_account.save + set_sponsoring_agency_options + end - def add_user - ensure_admin_or_contact(@digital_service_account) - @user = User.find_by_email(params[:user][:email]) + def add_user + ensure_admin_or_contact(@digital_service_account) + @user = User.find_by_email(params[:user][:email]) - if @user - @user.add_role(:contact, @digital_service_account) + @user&.add_role(:contact, @digital_service_account) end - end - def remove_user - ensure_admin_or_contact(@digital_service_account) - @user = User.find_by_id(params[:user][:id]) + def remove_user + ensure_admin_or_contact(@digital_service_account) + @user = User.find_by_id(params[:user][:id]) - if @user - @user.remove_role(:contact, @digital_service_account) + @user&.remove_role(:contact, @digital_service_account) end - end - def submit - ensure_digital_service_account_permissions(digital_service_account: @digital_service_account) + def submit + ensure_digital_service_account_permissions(digital_service_account: @digital_service_account) - if @digital_service_account.submit! - Event.log_event(Event.names[:digital_service_account_submitted], "Digital Service Account", @digital_service_account.id, "Digital Service Account #{@digital_service_account.name} submitted at #{DateTime.now}", current_user.id) + if @digital_service_account.submit! + Event.log_event(Event.names[:digital_service_account_submitted], 'Digital Service Account', @digital_service_account.id, "Digital Service Account #{@digital_service_account.name} submitted at #{DateTime.now}", current_user.id) - UserMailer.notification( - title: "Digital Service Account was submitted", - body: "Digital Service Account #{@digital_service_account.name} submitted at #{DateTime.now} by #{current_user.email}", - path: admin_digital_service_account_url(@digital_service_account), - emails: User.registry_managers.collect(&:email) # + @digital_product.contact_emails - ).deliver_later + UserMailer.notification( + title: 'Digital Service Account was submitted', + body: "Digital Service Account #{@digital_service_account.name} submitted at #{DateTime.now} by #{current_user.email}", + path: admin_digital_service_account_url(@digital_service_account), + emails: User.registry_managers.collect(&:email), # + @digital_product.contact_emails + ).deliver_later - redirect_to admin_digital_service_account_path(@digital_service_account), notice: "Digital Service Account #{@digital_service_account.name} was submitted." - else - render :edit + redirect_to admin_digital_service_account_path(@digital_service_account), notice: "Digital Service Account #{@digital_service_account.name} was submitted." + else + render :edit + end end - end - def publish - ensure_digital_service_account_permissions(digital_service_account: @digital_service_account) + def publish + ensure_digital_service_account_permissions(digital_service_account: @digital_service_account) - if @digital_service_account.publish! - Event.log_event(Event.names[:digital_service_account_published], "Digital Service Account", @digital_service_account.id, "Digital Service Account #{@digital_service_account.name} published at #{DateTime.now}", current_user.id) + if @digital_service_account.publish! + Event.log_event(Event.names[:digital_service_account_published], 'Digital Service Account', @digital_service_account.id, "Digital Service Account #{@digital_service_account.name} published at #{DateTime.now}", current_user.id) - UserMailer.notification( - title: "Digital Service Account was published", - body: "Digital Service Account #{@digital_service_account.name} published at #{DateTime.now} by #{current_user.email}", - path: admin_digital_service_account_url(@digital_service_account), - emails: User.registry_managers.collect(&:email) # + @digital_product.contact_emails - ).deliver_later + UserMailer.notification( + title: 'Digital Service Account was published', + body: "Digital Service Account #{@digital_service_account.name} published at #{DateTime.now} by #{current_user.email}", + path: admin_digital_service_account_url(@digital_service_account), + emails: User.registry_managers.collect(&:email), # + @digital_product.contact_emails + ).deliver_later - redirect_to admin_digital_service_account_path(@digital_service_account), notice: "Digital Service Account #{@digital_service_account.name} was published." - else - render :edit + redirect_to admin_digital_service_account_path(@digital_service_account), notice: "Digital Service Account #{@digital_service_account.name} was published." + else + render :edit + end end - end - def archive - ensure_digital_service_account_permissions(digital_service_account: @digital_service_account) + def archive + ensure_digital_service_account_permissions(digital_service_account: @digital_service_account) - if @digital_service_account.archive! - Event.log_event(Event.names[:digital_service_account_archived], "Digital Service Account", @digital_service_account.id, "Digital Service Account #{@digital_service_account.name} archived at #{DateTime.now}", current_user.id) - redirect_to admin_digital_service_account_path(@digital_service_account), notice: "Digital Service Account #{@digital_service_account.name} was archived." - else - render :edit + if @digital_service_account.archive! + Event.log_event(Event.names[:digital_service_account_archived], 'Digital Service Account', @digital_service_account.id, "Digital Service Account #{@digital_service_account.name} archived at #{DateTime.now}", current_user.id) + redirect_to admin_digital_service_account_path(@digital_service_account), notice: "Digital Service Account #{@digital_service_account.name} was archived." + else + render :edit + end end - end - def reset - ensure_digital_service_account_permissions(digital_service_account: @digital_service_account) + def reset + ensure_digital_service_account_permissions(digital_service_account: @digital_service_account) - if @digital_service_account.reset! - Event.log_event(Event.names[:digital_service_account_reset], "Digital Service Account", @digital_service_account.id, "Digital Service Account #{@digital_service_account.name} reset at #{DateTime.now}", current_user.id) - redirect_to admin_digital_service_account_path(@digital_service_account), notice: "Digital Service Account #{@digital_service_account.name} was reset." - else - render :edit + if @digital_service_account.reset! + Event.log_event(Event.names[:digital_service_account_reset], 'Digital Service Account', @digital_service_account.id, "Digital Service Account #{@digital_service_account.name} reset at #{DateTime.now}", current_user.id) + redirect_to admin_digital_service_account_path(@digital_service_account), notice: "Digital Service Account #{@digital_service_account.name} was reset." + else + render :edit + end end - end - - def search - search_text = params[:search] - organization_id = params[:organization_id] - @digital_service_accounts = DigitalServiceAccount.all - @digital_service_accounts = @digital_service_accounts.where("name ilike '%#{search_text}%'") if search_text && search_text.length >= 3 - @digital_service_accounts = @digital_service_accounts.tagged_with(organization_id, context: "organizations") if organization_id.present? && organization_id != '' - @digital_service_accounts = @digital_service_accounts.where("service = ?", params[:service]) if params[:service].present? && params[:service] != 'All' - @digital_service_accounts = @digital_service_accounts.where("aasm_state = ?", params[:aasm_state].downcase) if params[:aasm_state].present? && params[:aasm_state] != 'All' - @digital_service_accounts - end + def search + search_text = params[:search] + organization_id = params[:organization_id] + @digital_service_accounts = DigitalServiceAccount.all + @digital_service_accounts = @digital_service_accounts.where("name ilike '%#{search_text}%'") if search_text && search_text.length >= 3 + @digital_service_accounts = @digital_service_accounts.tagged_with(organization_id, context: 'organizations') if organization_id.present? && organization_id != '' + @digital_service_accounts = @digital_service_accounts.where('service = ?', params[:service]) if params[:service].present? && params[:service] != 'All' + @digital_service_accounts = @digital_service_accounts.where('aasm_state = ?', params[:aasm_state].downcase) if params[:aasm_state].present? && params[:aasm_state] != 'All' + @digital_service_accounts + end - private + private def set_digital_service_account @digital_service_account = DigitalServiceAccount.find(params[:id]) @@ -198,9 +192,7 @@ def set_digital_service_account def set_sponsoring_agency_options @sponsoring_agency_options = Organization.all.order(:name) - if @sponsoring_agency_options && @digital_service_account - @sponsoring_agency_options = @sponsoring_agency_options - @digital_service_account.sponsoring_agencies - end + @sponsoring_agency_options -= @digital_service_account.sponsoring_agencies if @sponsoring_agency_options && @digital_service_account end def digital_service_account_params @@ -217,7 +209,8 @@ def digital_service_account_params :long_description, :tags, :tag_list, - :organization_list) + :organization_list, + ) end end end diff --git a/app/controllers/admin/form_sections_controller.rb b/app/controllers/admin/form_sections_controller.rb index c8c98fe77..70f9fdf6d 100644 --- a/app/controllers/admin/form_sections_controller.rb +++ b/app/controllers/admin/form_sections_controller.rb @@ -1,68 +1,71 @@ -class Admin::FormSectionsController < AdminController - before_action :set_form, only: [:new, :create, :show, :edit, :update, :destroy] - before_action :set_form_section, only: [:edit, :update, :destroy] +# frozen_string_literal: true - def new - next_position = @form.form_sections.collect(&:position).max + 1 - @section = @form.form_sections.new - @section.title = "New Section" - @section.position = next_position - @section.save! - @tabindex = 0 - @multi_section_question_number = 0 - render layout: false - end +module Admin + class FormSectionsController < AdminController + before_action :set_form, only: %i[new create show edit update destroy] + before_action :set_form_section, only: %i[edit update destroy] - def edit - render layout: false - end + def new + next_position = @form.form_sections.collect(&:position).max + 1 + @section = @form.form_sections.new + @section.title = 'New Section' + @section.position = next_position + @section.save! + @tabindex = 0 + @multi_section_question_number = 0 + render layout: false + end - def sort - params[:form_section].each_with_index do |id, index| - FormSection.where(id: id).update_all(position: index + 1) + def edit + render layout: false end - head :ok - end + def sort + params[:form_section].each_with_index do |id, index| + FormSection.where(id:).update_all(position: index + 1) + end + head :ok + end - def update_title - section = FormSection.where(id: params[:form_section_id]).first - section.update!(title: params[:title]) - render json: section - end + def update_title + section = FormSection.where(id: params[:form_section_id]).first + section.update!(title: params[:title]) + render json: section + end - def create - next_position = @form.form_sections.collect(&:position).max + 1 - @form_section = @form.form_sections.new(form_section_params) - @form_section.position = next_position + def create + next_position = @form.form_sections.collect(&:position).max + 1 + @form_section = @form.form_sections.new(form_section_params) + @form_section.position = next_position - if @form_section.save - redirect_to questions_admin_form_path(@form), notice: 'Form section was successfully created.' - else - render :new + if @form_section.save + redirect_to questions_admin_form_path(@form), notice: 'Form section was successfully created.' + else + render :new + end end - end - def update - if @form_section.update(form_section_params) - redirect_to questions_admin_form_url(@form), notice: 'Form section was successfully updated.' - else - render :edit + def update + if @form_section.update(form_section_params) + redirect_to questions_admin_form_url(@form), notice: 'Form section was successfully updated.' + else + render :edit + end end - end - def destroy - if @form.form_sections.count < 1 - redirect_to questions_admin_form_url(@form), alert: 'Cannot delete only remaining Form section' - elsif @form_section.destroy - redirect_to questions_admin_form_url(@form), notice: 'Form section was successfully deleted.' - else - redirect_to questions_admin_form_url(@form), alert: 'Form section cannot be deleted because it has one or more questions.' + def destroy + if @form.form_sections.count < 1 + redirect_to questions_admin_form_url(@form), alert: 'Cannot delete only remaining Form section' + elsif @form_section.destroy + redirect_to questions_admin_form_url(@form), notice: 'Form section was successfully deleted.' + else + redirect_to questions_admin_form_url(@form), alert: 'Form section cannot be deleted because it has one or more questions.' + end end - end - private + private + def set_form_section @form_section = @form.form_sections.find(params[:id]) end @@ -74,4 +77,5 @@ def set_form def form_section_params params.require(:form_section).permit(:title, :position, :next_section_id) end + end end diff --git a/app/controllers/admin/forms_controller.rb b/app/controllers/admin/forms_controller.rb index 7880af01e..b18fd33f9 100644 --- a/app/controllers/admin/forms_controller.rb +++ b/app/controllers/admin/forms_controller.rb @@ -1,417 +1,415 @@ +# frozen_string_literal: true require 'csv' -class Admin::FormsController < AdminController - respond_to :html, :js, :docx - - skip_before_action :verify_authenticity_token, only: [:js] - before_action :set_user, only: [:add_user, :remove_user] - before_action :set_form, only: [ - :show, :edit, :update, :destroy, - :compliance, - :permissions, :questions, :responses, :delivery_method, - :copy, :copy_by_id, - :invite, - :notifications, - :export, - :export_pra_document, - :export_submissions, - :export_a11_header, - :export_a11_submissions, - :example, :js, :trigger, - :add_user, :remove_user, - :publish, - :archive, - :reset, - :update_ui_truncation, - :update_title, :update_instructions, :update_disclaimer_text, - :update_success_text, :update_display_logo, - :update_admin_options, :update_form_manager_options, - :events - ] - - def index - if admin_permissions? - @forms = Form.non_templates.order("organization_id ASC").order("name ASC") - else - @forms = current_user.forms.non_templates.order("organization_id ASC").order("name ASC").entries +module Admin + class FormsController < AdminController + respond_to :html, :js, :docx + + skip_before_action :verify_authenticity_token, only: [:js] + before_action :set_user, only: %i[add_user remove_user] + before_action :set_form, only: %i[ + show edit update destroy + compliance + permissions questions responses delivery_method + copy copy_by_id + invite + notifications + export + export_pra_document + export_submissions + export_a11_header + export_a11_submissions + example js trigger + add_user remove_user + publish + archive + reset + update_ui_truncation + update_title update_instructions update_disclaimer_text + update_success_text update_display_logo + update_admin_options update_form_manager_options + events + ] + + def index + if admin_permissions? + @forms = Form.non_templates.order('organization_id ASC').order('name ASC') + else + @forms = current_user.forms.non_templates.order('organization_id ASC').order('name ASC').entries + end end - end - def export - questions = [] - @form.questions.each do |q| - attrs = q.attributes + def export + questions = [] + @form.questions.each do |q| + attrs = q.attributes - if q.question_options.present? - attrs[:question_options] = [] - q.question_options.each do |qo| - attrs[:question_options] << qo.attributes + if q.question_options.present? + attrs[:question_options] = [] + q.question_options.each do |qo| + attrs[:question_options] << qo.attributes + end end + + questions << attrs end - questions << attrs + render json: { form: @form, questions: } end - render json: { form: @form, questions: questions } - end - - def invite - invitee = invite_params[:refer_user] + def invite + invitee = invite_params[:refer_user] - if invitee.present? && invitee =~ URI::MailTo::EMAIL_REGEXP && (ENV['GITHUB_CLIENT_ID'].present? ? true : User::APPROVED_DOMAINS.any? { |word| invitee.end_with?(word) }) - if User.exists?(email: invitee) - redirect_to permissions_admin_form_path(@form), alert: "User with email #{invitee} already exists" - else - UserMailer.invite(current_user, invitee).deliver_later - redirect_to permissions_admin_form_path(@form), notice: "Invite sent to #{invitee}" - end - else - if ENV['GITHUB_CLIENT_ID'].present? - redirect_to permissions_admin_form_path(@form), alert: "Please enter a valid email address" + if invitee.present? && invitee =~ URI::MailTo::EMAIL_REGEXP && (ENV['GITHUB_CLIENT_ID'].present? ? true : User::APPROVED_DOMAINS.any? { |word| invitee.end_with?(word) }) + if User.exists?(email: invitee) + redirect_to permissions_admin_form_path(@form), alert: "User with email #{invitee} already exists" + else + UserMailer.invite(current_user, invitee).deliver_later + redirect_to permissions_admin_form_path(@form), notice: "Invite sent to #{invitee}" + end + elsif ENV['GITHUB_CLIENT_ID'].present? + redirect_to permissions_admin_form_path(@form), alert: 'Please enter a valid email address' else - redirect_to permissions_admin_form_path(@form), alert: "Please enter a valid .gov or .mil email address" + redirect_to permissions_admin_form_path(@form), alert: 'Please enter a valid .gov or .mil email address' end end - end - def publish - Event.log_event(Event.names[:form_published], "Form", @form.uuid,"Form #{@form.name} published at #{DateTime.now}", current_user.id) + def publish + Event.log_event(Event.names[:form_published], 'Form', @form.uuid, "Form #{@form.name} published at #{DateTime.now}", current_user.id) - @form.publish! - redirect_to admin_form_path(@form), notice: "Published" - end - - def archive - Event.log_event(Event.names[:form_archived], "Form", @form.uuid,"Form #{@form.name} archived at #{DateTime.now}", current_user.id) - - @form.archive! - redirect_to admin_form_path(@form), notice: "Archived" - end - - def reset - Event.log_event(Event.names[:form_reset], "Form", @form.uuid,"Form #{@form.name} reset at #{DateTime.now}", current_user.id) + @form.publish! + redirect_to admin_form_path(@form), notice: 'Published' + end - @form.reset! - redirect_to admin_form_path(@form), notice: "Form has been reset" - end + def archive + Event.log_event(Event.names[:form_archived], 'Form', @form.uuid, "Form #{@form.name} archived at #{DateTime.now}", current_user.id) - def update_title - ensure_form_manager(form: @form) - @form.update!(title: params[:title]) - render json: @form - end + @form.archive! + redirect_to admin_form_path(@form), notice: 'Archived' + end - def update_instructions - ensure_form_manager(form: @form) - @form.update!(instructions: params[:instructions]) - render json: @form - end + def reset + Event.log_event(Event.names[:form_reset], 'Form', @form.uuid, "Form #{@form.name} reset at #{DateTime.now}", current_user.id) - def update_disclaimer_text - ensure_form_manager(form: @form) - @form.update!(disclaimer_text: params[:disclaimer_text]) - render json: @form - end + @form.reset! + redirect_to admin_form_path(@form), notice: 'Form has been reset' + end - def update_success_text - ensure_form_manager(form: @form) - @form.update!(success_text: params[:success_text], success_text_heading: params[:success_text_heading]) - render(partial: "admin/questions/success_text", locals: { form: @form }) - end + def update_title + ensure_form_manager(form: @form) + @form.update!(title: params[:title]) + render json: @form + end - def update_display_logo - ensure_form_manager(form: @form) - @form.update(form_logo_params) - end + def update_instructions + ensure_form_manager(form: @form) + @form.update!(instructions: params[:instructions]) + render json: @form + end - def update_admin_options - ensure_form_manager(form: @form) - @form.update(form_admin_options_params) - flash.now[:notice] = "Admin form options updated successfully" - end + def update_disclaimer_text + ensure_form_manager(form: @form) + @form.update!(disclaimer_text: params[:disclaimer_text]) + render json: @form + end - def update_form_manager_options - ensure_form_manager(form: @form) - @form.update(form_admin_options_params) - flash.now[:notice] = "Form Manager forms options updated successfully" - end + def update_success_text + ensure_form_manager(form: @form) + @form.update!(success_text: params[:success_text], success_text_heading: params[:success_text_heading]) + render(partial: 'admin/questions/success_text', locals: { form: @form }) + end - def show - ensure_response_viewer(form: @form) unless @form.template? - @questions = @form.questions - end + def update_display_logo + ensure_form_manager(form: @form) + @form.update(form_logo_params) + end - def permissions - ensure_form_manager(form: @form) - if admin_permissions? - @available_members = User.all.order(:email) - @form.users - else - @available_members = @form.organization.users.active.order(:email) - @form.users + def update_admin_options + ensure_form_manager(form: @form) + @form.update(form_admin_options_params) + flash.now[:notice] = 'Admin form options updated successfully' end - end - def questions - ensure_form_manager(form: @form) unless @form.template? - @questions = @form.questions - end + def update_form_manager_options + ensure_form_manager(form: @form) + @form.update(form_admin_options_params) + flash.now[:notice] = 'Form Manager forms options updated successfully' + end - def responses - FormCache.invalidate_reports(@form.short_uuid) if params["use_cache"].present? && params["use_cache"] == "false" - ensure_response_viewer(form: @form) unless @form.template? - end + def show + ensure_response_viewer(form: @form) unless @form.template? + @questions = @form.questions + end - def delivery_method - ensure_form_manager(form: @form) - end + def permissions + ensure_form_manager(form: @form) + if admin_permissions? + @available_members = User.all.order(:email) - @form.users + else + @available_members = @form.organization.users.active.order(:email) - @form.users + end + end - def example - redirect_to touchpoint_path, notice: "Previewing Touchpoint" and return if @form.delivery_method == "touchpoints-hosted-only" - redirect_to admin_forms_path, notice: "Form does not have a delivery_method of 'modal' or 'inline' or 'custom-button-modal'" and return unless @form.delivery_method == "modal" || @form.delivery_method == "inline" || @form.delivery_method == "custom-button-modal" + def questions + ensure_form_manager(form: @form) unless @form.template? + @questions = @form.questions + end - render layout: false - end + def responses + FormCache.invalidate_reports(@form.short_uuid) if params['use_cache'].present? && params['use_cache'] == 'false' + ensure_response_viewer(form: @form) unless @form.template? + end - def js - render(partial: "components/widget/fba", formats: :js, locals: { form: @form }) - end + def delivery_method + ensure_form_manager(form: @form) + end - def new - @templates = Form.templates - @form = Form.new - @surveys = current_user.forms.non_templates.order("organization_id ASC").order("name ASC").entries - end + def example + redirect_to touchpoint_path, notice: 'Previewing Touchpoint' and return if @form.delivery_method == 'touchpoints-hosted-only' + redirect_to admin_forms_path, notice: "Form does not have a delivery_method of 'modal' or 'inline' or 'custom-button-modal'" and return unless @form.delivery_method == 'modal' || @form.delivery_method == 'inline' || @form.delivery_method == 'custom-button-modal' - def edit - ensure_form_manager(form: @form) - end + render layout: false + end - def notifications - ensure_form_manager(form: @form) - end + def js + render(partial: 'components/widget/fba', formats: :js, locals: { form: @form }) + end - def create - ensure_form_manager(form: @form) + def new + @templates = Form.templates + @form = Form.new + @surveys = current_user.forms.non_templates.order('organization_id ASC').order('name ASC').entries + end - @form = Form.new(form_params) + def edit + ensure_form_manager(form: @form) + end - @form.organization_id = current_user.organization_id - @form.user_id = current_user.id - @form.title = @form.name - @form.modal_button_text = t('form.help_improve') - @form.success_text_heading = t('success') - @form.success_text = t('form.submit_thankyou') - @form.delivery_method = "touchpoints-hosted-only" - @form.load_css = true - unless @form.user - @form.user = current_user + def notifications + ensure_form_manager(form: @form) end - respond_to do |format| - if @form.save - Event.log_event(Event.names[:form_created], "Form", @form.uuid,"Form #{@form.name} created at #{DateTime.now}", current_user.id) + def create + ensure_form_manager(form: @form) + + @form = Form.new(form_params) + + @form.organization_id = current_user.organization_id + @form.user_id = current_user.id + @form.title = @form.name + @form.modal_button_text = t('form.help_improve') + @form.success_text_heading = t('success') + @form.success_text = t('form.submit_thankyou') + @form.delivery_method = "touchpoints-hosted-only" + @form.load_css = true + unless @form.user + @form.user = current_user + end - UserRole.create!({ - user: current_user, - form: @form, - role: UserRole::Role::FormManager - }) + respond_to do |format| + if @form.save + Event.log_event(Event.names[:form_created], "Form", @form.uuid,"Form #{@form.name} created at #{DateTime.now}", current_user.id) - format.html { redirect_to questions_admin_form_path(@form), notice: 'Survey was successfully created.' } - format.json { render :show, status: :created, location: @form } - else - format.html { render :new, status: :unprocessable_entity } - format.json { render json: @form.errors, status: :unprocessable_entity } + UserRole.create!({ + user: current_user, + form: @form, + role: UserRole::Role::FormManager + }) + + format.html { redirect_to questions_admin_form_path(@form), notice: 'Survey was successfully created.' } + format.json { render :show, status: :created, location: @form } + else + format.html { render :new, status: :unprocessable_entity } + format.json { render json: @form.errors, status: :unprocessable_entity } + end end end - end - def copy - respond_to do |format| - new_form = @form.duplicate!(new_user: current_user) + def copy + respond_to do |format| + new_form = @form.duplicate!(new_user: current_user) - if new_form.valid? - @role = UserRole.create!({ - user: current_user, - form: new_form, - role: UserRole::Role::FormManager - }) + if new_form.valid? + @role = UserRole.create!({ + user: current_user, + form: new_form, + role: UserRole::Role::FormManager, + }) - Event.log_event(Event.names[:form_copied], "Form", @form.uuid, "Form #{@form.name} copied at #{DateTime.now}", current_user.id) + Event.log_event(Event.names[:form_copied], 'Form', @form.uuid, "Form #{@form.name} copied at #{DateTime.now}", current_user.id) - format.html { redirect_to admin_form_path(new_form), notice: 'Survey was successfully copied.' } - format.json { render :show, status: :created, location: new_form } - else - format.html { render :new, status: :unprocessable_entity } - format.json { render json: new_form.errors, status: :unprocessable_entity } + format.html { redirect_to admin_form_path(new_form), notice: 'Survey was successfully copied.' } + format.json { render :show, status: :created, location: new_form } + else + format.html { render :new, status: :unprocessable_entity } + format.json { render json: new_form.errors, status: :unprocessable_entity } + end end end - end - def copy_by_id - copy - end + def copy_by_id + copy + end - def update_ui_truncation - ensure_response_viewer(form: @form) + def update_ui_truncation + ensure_response_viewer(form: @form) - respond_to do |format| - if @form.update(ui_truncate_text_responses: !@form.ui_truncate_text_responses) - format.json { render json: {}, status: :ok, location: @form } - else - format.json { render json: @form.errors, status: :unprocessable_entity } + respond_to do |format| + if @form.update(ui_truncate_text_responses: !@form.ui_truncate_text_responses) + format.json { render json: {}, status: :ok, location: @form } + else + format.json { render json: @form.errors, status: :unprocessable_entity } + end end end - end - def update - ensure_form_manager(form: @form) + def update + ensure_form_manager(form: @form) - transition_state + transition_state - respond_to do |format| - if @form.update(form_params) - format.html { - redirect_to get_edit_path(@form), notice: 'Survey was successfully updated.' - } - format.json { render :show, status: :ok, location: @form } - else - format.html { render (params[:form][:delivery_method].present? ? :delivery_method : :edit), status: :unprocessable_entity } - format.json { render json: @form.errors, status: :unprocessable_entity } + respond_to do |format| + if @form.update(form_params) + format.html do + redirect_to get_edit_path(@form), notice: 'Survey was successfully updated.' + end + format.json { render :show, status: :ok, location: @form } + else + format.html { render (params[:form][:delivery_method].present? ? :delivery_method : :edit), status: :unprocessable_entity } + format.json { render json: @form.errors, status: :unprocessable_entity } + end end end - end - # Start building our wizard workflow - def get_edit_path(form) - if params[:form][:delivery_method].present? - delivery_method_admin_form_path(form) - else - admin_form_path(form) + # Start building our wizard workflow + def get_edit_path(form) + if params[:form][:delivery_method].present? + delivery_method_admin_form_path(form) + else + admin_form_path(form) + end end - end - - def destroy - ensure_form_manager(form: @form) - respond_to do |format| - format.html { - if @form.destroy - Event.log_event(Event.names[:form_deleted], "Form", @form.uuid,"Form #{@form.name} deleted at #{DateTime.now}", current_user.id) - redirect_to admin_forms_url, notice: 'Survey was successfully destroyed.' - else - redirect_to edit_admin_form_url(@form), notice: @form.errors.full_messages.to_sentence + def destroy + ensure_form_manager(form: @form) + + respond_to do |format| + format.html do + if @form.destroy + Event.log_event(Event.names[:form_deleted], 'Form', @form.uuid, "Form #{@form.name} deleted at #{DateTime.now}", current_user.id) + redirect_to admin_forms_url, notice: 'Survey was successfully destroyed.' + else + redirect_to edit_admin_form_url(@form), notice: @form.errors.full_messages.to_sentence + end end - } - format.json { head :no_content } + format.json { head :no_content } + end end - end + # Roles and Permissions + # + # Associate a user with a Form + def add_user + raise ArgumentException unless current_user.admin? || (@form.user_role?(user: current_user) == UserRole::Role::FormManager) + raise ArgumentException unless UserRole::ROLES.include?(params[:role]) - # Roles and Permissions - # - # Associate a user with a Form - def add_user - raise ArgumentException unless current_user.admin? || (@form.user_role?(user: current_user) == UserRole::Role::FormManager) - raise ArgumentException unless UserRole::ROLES.include?(params[:role]) + @role = UserRole.new({ + user: @user, + form: @form, + role: params[:role], + }) - @role = UserRole.new({ - user: @user, - form: @form, - role: params[:role], - }) + if @role.save + flash[:notice] = 'User Role successfully added to Form' - if @role.save - flash[:notice] = "User Role successfully added to Form" - - render json: { + render json: { email: @user.email, - form: @form.short_uuid + form: @form.short_uuid, } - else - render json: @role.errors, status: :unprocessable_entity + else + render json: @role.errors, status: :unprocessable_entity + end end - end - # Disassociate a user with a Form - def remove_user - @role = @form.user_roles.find_by_user_id(params[:user_id]) + # Disassociate a user with a Form + def remove_user + @role = @form.user_roles.find_by_user_id(params[:user_id]) - if @role.destroy - flash[:notice] = "User Role successfully removed from Form" + if @role.destroy + flash[:notice] = 'User Role successfully removed from Form' - render json: { - email: @user.email, - form: @form.short_uuid - } - else - render json: @role.errors, status: :unprocessable_entity + render json: { + email: @user.email, + form: @form.short_uuid, + } + else + render json: @role.errors, status: :unprocessable_entity + end end - end - - # Data reporting - # - # - def export_pra_document - respond_to do |format| - format.html { - redirect_to admin_form_path(@form) - } - format.docx { - docx = PraForm.part_a(form: @form) - send_data docx.render.string, filename: "pra-part-a-#{timestamp_string}.docx" - } + # Data reporting + # + # + def export_pra_document + respond_to do |format| + format.html do + redirect_to admin_form_path(@form) + end + format.docx do + docx = PraForm.part_a(form: @form) + send_data docx.render.string, filename: "pra-part-a-#{timestamp_string}.docx" + end + end end - end - def export_submissions - start_date = params[:start_date] ? Date.parse(params[:start_date]).to_date : Time.now.beginning_of_quarter - end_date = params[:end_date] ? Date.parse(params[:end_date]).to_date : Time.now.end_of_quarter + def export_submissions + start_date = params[:start_date] ? Date.parse(params[:start_date]).to_date : Time.zone.now.beginning_of_quarter + end_date = params[:end_date] ? Date.parse(params[:end_date]).to_date : Time.zone.now.end_of_quarter - respond_to do |format| - format.csv { - csv_content = Form.find_by_short_uuid(@form.short_uuid).to_csv(start_date: start_date, end_date: end_date) - send_data csv_content - } - format.json { - ExportJob.perform_later(params[:uuid], @form.short_uuid, start_date.to_s, end_date.to_s, "touchpoints-form-responses-#{timestamp_string}.csv") - render json: { result: :ok } - } + respond_to do |format| + format.csv do + csv_content = Form.find_by_short_uuid(@form.short_uuid).to_csv(start_date:, end_date:) + send_data csv_content + end + format.json do + ExportJob.perform_later(params[:uuid], @form.short_uuid, start_date.to_s, end_date.to_s, "touchpoints-form-responses-#{timestamp_string}.csv") + render json: { result: :ok } + end + end end - end - # A-11 Header report. File 1 of 2 - # - def export_a11_header - start_date = params[:start_date] ? Date.parse(params[:start_date]).to_date : Time.now.beginning_of_quarter - end_date = params[:end_date] ? Date.parse(params[:end_date]).to_date : Time.now.end_of_quarter + # A-11 Header report. File 1 of 2 + # + def export_a11_header + start_date = params[:start_date] ? Date.parse(params[:start_date]).to_date : Time.zone.now.beginning_of_quarter + end_date = params[:end_date] ? Date.parse(params[:end_date]).to_date : Time.zone.now.end_of_quarter - respond_to do |format| - format.csv { - send_data @form.to_a11_header_csv(start_date: start_date, end_date: end_date), filename: "a11-header-#{timestamp_string}.csv" - } + respond_to do |format| + format.csv do + send_data @form.to_a11_header_csv(start_date:, end_date:), filename: "a11-header-#{timestamp_string}.csv" + end + end end - end - # A-11 Detail report. File 2 of 2 - # - def export_a11_submissions - start_date = Date.parse(params[:start_date]).to_date || Time.now.beginning_of_quarter - end_date = Date.parse(params[:end_date]).to_date || Time.now.end_of_quarter + # A-11 Detail report. File 2 of 2 + # + def export_a11_submissions + start_date = Date.parse(params[:start_date]).to_date || Time.zone.now.beginning_of_quarter + end_date = Date.parse(params[:end_date]).to_date || Time.zone.now.end_of_quarter - respond_to do |format| - format.csv { - send_data @form.to_a11_submissions_csv(start_date: start_date, end_date: end_date), filename: "A-11-Responses-#{timestamp_string}.csv" - } + respond_to do |format| + format.csv do + send_data @form.to_a11_submissions_csv(start_date:, end_date:), filename: "A-11-Responses-#{timestamp_string}.csv" + end + end end - end - def events - @events = Event.where(object_type: "Form", object_id: @form.uuid).order(:created_at) - end + def events + @events = Event.where(object_type: 'Form', object_id: @form.uuid).order(:created_at) + end + private - private def set_form @form = Form.find_by_short_uuid(params[:id]) redirect_to admin_forms_path, notice: "no survey with ID of #{params[:id]}" unless @form @@ -452,7 +450,6 @@ def form_params :success_text, :success_text_heading, :service_id, - # PRA Info :omb_approval_number, :expiration_date, @@ -467,11 +464,8 @@ def form_params :agency_poc_name, :department, :bureau, - :load_css, - :ui_truncate_text_responses, - :question_text_01, :question_text_02, :question_text_03, @@ -491,7 +485,7 @@ def form_params :question_text_17, :question_text_18, :question_text_19, - :question_text_20 + :question_text_20, ) end @@ -525,15 +519,12 @@ def form_admin_options_params # Add rules for AASM state transitions here def transition_state - if params["form"]["aasm_state"] == "live" and !@form.live? - Event.log_event(Event.names[:form_published], "Form", @form.uuid, "Form #{@form.name} published at #{DateTime.now}", current_user.id) - end - if params["form"]["aasm_state"] == "archived" and !@form.archived? - Event.log_event(Event.names[:form_archived], "Form", @form.uuid, "Form #{@form.name} archived at #{DateTime.now}", current_user.id) - end + Event.log_event(Event.names[:form_published], 'Form', @form.uuid, "Form #{@form.name} published at #{DateTime.now}", current_user.id) if (params['form']['aasm_state'] == 'live') && !@form.live? + Event.log_event(Event.names[:form_archived], 'Form', @form.uuid, "Form #{@form.name} archived at #{DateTime.now}", current_user.id) if (params['form']['aasm_state'] == 'archived') && !@form.archived? end def invite_params - params.require(:user).permit(:refer_user) + params.require(:user).permit(:refer_user) end + end end diff --git a/app/controllers/admin/goal_targets_controller.rb b/app/controllers/admin/goal_targets_controller.rb index 804c9b5ed..2bc198ee2 100644 --- a/app/controllers/admin/goal_targets_controller.rb +++ b/app/controllers/admin/goal_targets_controller.rb @@ -1,74 +1,74 @@ -class Admin::GoalTargetsController < AdminController - before_action :set_goal - before_action :set_goal_target, only: [:show, :edit, :update, :destroy] +# frozen_string_literal: true - def index - @goal_targets = GoalTarget.all - end +module Admin + class GoalTargetsController < AdminController + before_action :set_goal + before_action :set_goal_target, only: %i[show edit update destroy] - def show + def index + @goal_targets = GoalTarget.all + end - end + def show; end - def new - @goal_target = GoalTarget.new - @goal_target.assertion = 'New goal target' - @goal_target.starting_value = 0 - @goal_target.target_value = 0 - @goal_target.current_value = 0 - render layout: false - end + def new + @goal_target = GoalTarget.new + @goal_target.assertion = 'New goal target' + @goal_target.starting_value = 0 + @goal_target.target_value = 0 + @goal_target.current_value = 0 + render layout: false + end - def edit - render layout: false - end + def edit + render layout: false + end - def create - ensure_performance_manager_permissions + def create + ensure_performance_manager_permissions - @goal_target = GoalTarget.new(goal_target_params) + @goal_target = GoalTarget.new(goal_target_params) - respond_to do |format| - if @goal_target.save - format.html { redirect_to admin_goal_goal_target_path(@goal, @goal_target), notice: 'Goal target was successfully created.'} - format.json { render :create, status: :created, goal: @goal } - format.js - else - format.html { render :new } - format.json { render json: @goal_target.errors, status: :unprocessable_entity } + respond_to do |format| + if @goal_target.save + format.html { redirect_to admin_goal_goal_target_path(@goal, @goal_target), notice: 'Goal target was successfully created.' } + format.json { render :create, status: :created, goal: @goal } + else + format.html { render :new } + format.json { render json: @goal_target.errors, status: :unprocessable_entity } + end format.js end end - end - def update - ensure_performance_manager_permissions + def update + ensure_performance_manager_permissions - respond_to do |format| - if @goal_target.update(goal_target_params) - format.html { redirect_to admin_goal_goal_target_path(@goal, @goal_target), notice: 'Goal target was successfully updated.'} - format.json { render :update, status: :updated, goal: @goal } - format.js - else - format.html { render :edit } - format.json { render json: @goal_target.errors, status: :unprocessable_entity } + respond_to do |format| + if @goal_target.update(goal_target_params) + format.html { redirect_to admin_goal_goal_target_path(@goal, @goal_target), notice: 'Goal target was successfully updated.' } + format.json { render :update, status: :updated, goal: @goal } + else + format.html { render :edit } + format.json { render json: @goal_target.errors, status: :unprocessable_entity } + end format.js end end - end - def destroy - ensure_performance_manager_permissions - @goal_target.destroy + def destroy + ensure_performance_manager_permissions + @goal_target.destroy - respond_to do |format| - format.html { redirect_to admin_goal_goal_targets_url(@goal), notice: 'Goal target was successfully destroyed.'} - format.json { render :destroy, status: :deleted, goal: @goal } - format.js + respond_to do |format| + format.html { redirect_to admin_goal_goal_targets_url(@goal), notice: 'Goal target was successfully destroyed.' } + format.json { render :destroy, status: :deleted, goal: @goal } + format.js + end end - end - private + private + def set_goal @goal = Goal.find(params[:goal_id]) end @@ -80,4 +80,5 @@ def set_goal_target def goal_target_params params.require(:goal_target).permit(:goal_id, :target_date_at, :assertion, :kpi, :starting_value, :target_value, :current_value) end + end end diff --git a/app/controllers/admin/goals_controller.rb b/app/controllers/admin/goals_controller.rb index e58b4b2a9..cb08fb9e5 100644 --- a/app/controllers/admin/goals_controller.rb +++ b/app/controllers/admin/goals_controller.rb @@ -1,154 +1,157 @@ -class Admin::GoalsController < AdminController - before_action :set_goal, only: - %i[show - edit - update - update_organization_id - update_name - update_statement - update_description - update_position - update_tags - update_users - update_four_year_goal - update_parent_id - goal_targets - goal_objectives - destroy - add_tag - remove_tag] - - before_action :set_goal_tags, only: [:show, :add_tag, :remove_tag] - - def index - @goals = Goal.all - end +# frozen_string_literal: true + +module Admin + class GoalsController < AdminController + before_action :set_goal, only: + %i[show + edit + update + update_organization_id + update_name + update_statement + update_description + update_position + update_tags + update_users + update_four_year_goal + update_parent_id + goal_targets + goal_objectives + destroy + add_tag + remove_tag] + + before_action :set_goal_tags, only: %i[show add_tag remove_tag] + + def index + @goals = Goal.all + end - def show; end + def show; end - def new - ensure_performance_manager_permissions - - @goal = Goal.new - @goal.organization_id = current_user.organization_id - @goal.name = 'New Goal' - @goal.save! - end + def new + ensure_performance_manager_permissions - def edit - ensure_performance_manager_permissions - end + @goal = Goal.new + @goal.organization_id = current_user.organization_id + @goal.name = 'New Goal' + @goal.save! + end - def create - ensure_performance_manager_permissions + def edit + ensure_performance_manager_permissions + end + + def create + ensure_performance_manager_permissions - @goal = Goal.new(goal_params) + @goal = Goal.new(goal_params) - if @goal.save - redirect_to admin_goal_path(@goal), notice: 'Goal was successfully created.' - else - render :new + if @goal.save + redirect_to admin_goal_path(@goal), notice: 'Goal was successfully created.' + else + render :new + end end - end - def update - ensure_performance_manager_permissions + def update + ensure_performance_manager_permissions - if @goal.update(goal_params) - redirect_to admin_goal_path(@goal), notice: 'Goal was successfully updated.' - else - render :edit + if @goal.update(goal_params) + redirect_to admin_goal_path(@goal), notice: 'Goal was successfully updated.' + else + render :edit + end end - end - - def add_tag - @goal.tag_list.add(goal_params[:tag_list].split(',')) - @goal.save - end - def remove_tag - @goal.tag_list.remove(goal_params[:tag_list].split(',')) - @goal.save - end + def add_tag + @goal.tag_list.add(goal_params[:tag_list].split(',')) + @goal.save + end - def update_organization_id - @goal.update!(update_organization_id: params[:organization_id]) - render json: @goal - end + def remove_tag + @goal.tag_list.remove(goal_params[:tag_list].split(',')) + @goal.save + end - def update_name - @goal.update!(name: params[:name]) - render json: @goal - end + def update_organization_id + @goal.update!(update_organization_id: params[:organization_id]) + render json: @goal + end - def update_statement - @goal.update!(goal_statement: params[:goal_statement]) - render json: @goal - end + def update_name + @goal.update!(name: params[:name]) + render json: @goal + end - def update_description - @goal.update!(description: params[:description]) - render json: @goal - end + def update_statement + @goal.update!(goal_statement: params[:goal_statement]) + render json: @goal + end - def update_position - @goal.update!(position: params[:position]) - render json: @goal - end + def update_description + @goal.update!(description: params[:description]) + render json: @goal + end - def update_tags - @goal.update!(tags: params[:tags].split(' ')) - render json: @goal - end + def update_position + @goal.update!(position: params[:position]) + render json: @goal + end - def update_users - @goal.update!(users: [params[:users].to_i]) - render json: @goal - end + def update_tags + @goal.update!(tags: params[:tags].split) + render json: @goal + end - def update_four_year_goal - @goal.update!(four_year_goal: params[:four_year_goal]) - render json: @goal - end + def update_users + @goal.update!(users: [params[:users].to_i]) + render json: @goal + end - def update_parent_id - @goal.update!(parent_id: params[:parent_id]) - render json: @goal - end + def update_four_year_goal + @goal.update!(four_year_goal: params[:four_year_goal]) + render json: @goal + end - def destroy - ensure_performance_manager_permissions + def update_parent_id + @goal.update!(parent_id: params[:parent_id]) + render json: @goal + end - @goal.destroy - redirect_to admin_goals_url, notice: 'Goal was successfully destroyed.' - end + def destroy + ensure_performance_manager_permissions - def goal_targets; end + @goal.destroy + redirect_to admin_goals_url, notice: 'Goal was successfully destroyed.' + end - def goal_objectives; end + def goal_targets; end + def goal_objectives; end - private + private - def set_goal - @goal = Goal.find(params[:id]) - end + def set_goal + @goal = Goal.find(params[:id]) + end - def set_goal_tags - @goal_tags_for_select = Goal::TAGS - end + def set_goal_tags + @goal_tags_for_select = Goal::TAGS + end - def goal_params - params.require(:goal).permit( - :organization_id, - :name, - :description, - :statement, - :tags, - :users, - :four_year_goal, - :parent_id, - :tag_list - ) + def goal_params + params.require(:goal).permit( + :organization_id, + :name, + :description, + :statement, + :tags, + :users, + :four_year_goal, + :parent_id, + :tag_list, + ) + end end end diff --git a/app/controllers/admin/milestones_controller.rb b/app/controllers/admin/milestones_controller.rb index 6c6beeefb..7f1c9ab77 100644 --- a/app/controllers/admin/milestones_controller.rb +++ b/app/controllers/admin/milestones_controller.rb @@ -1,54 +1,56 @@ -class Admin::MilestonesController < AdminController - before_action :set_milestone, only: [:show, :edit, :update, :destroy] +# frozen_string_literal: true - def index - @milestones = Milestone.all - end +module Admin + class MilestonesController < AdminController + before_action :set_milestone, only: %i[show edit update destroy] - def show - end + def index + @milestones = Milestone.all + end - def new - ensure_performance_manager_permissions + def show; end - @milestone = Milestone.new - end + def new + ensure_performance_manager_permissions - def edit - ensure_performance_manager_permissions + @milestone = Milestone.new + end - end + def edit + ensure_performance_manager_permissions + end - def create - ensure_performance_manager_permissions + def create + ensure_performance_manager_permissions - @milestone = Milestone.new(milestone_params) + @milestone = Milestone.new(milestone_params) - if @milestone.save - redirect_to admin_milestone_path(@milestone), notice: 'Milestone was successfully created.' - else - render :new + if @milestone.save + redirect_to admin_milestone_path(@milestone), notice: 'Milestone was successfully created.' + else + render :new + end end - end - def update - ensure_performance_manager_permissions + def update + ensure_performance_manager_permissions - if @milestone.update(milestone_params) - redirect_to admin_milestone_path(@milestone), notice: 'Milestone was successfully updated.' - else - render :edit + if @milestone.update(milestone_params) + redirect_to admin_milestone_path(@milestone), notice: 'Milestone was successfully updated.' + else + render :edit + end end - end - def destroy - ensure_performance_manager_permissions - - @milestone.destroy - redirect_to admin_milestones_url, notice: 'Milestone was successfully destroyed.' - end + def destroy + ensure_performance_manager_permissions + + @milestone.destroy + redirect_to admin_milestones_url, notice: 'Milestone was successfully destroyed.' + end + + private - private def set_milestone @milestone = Milestone.find(params[:id]) end @@ -64,4 +66,5 @@ def milestone_params :notes, ) end + end end diff --git a/app/controllers/admin/objectives_controller.rb b/app/controllers/admin/objectives_controller.rb index 03d351205..dc59f0649 100644 --- a/app/controllers/admin/objectives_controller.rb +++ b/app/controllers/admin/objectives_controller.rb @@ -1,89 +1,90 @@ -class Admin::ObjectivesController < AdminController - before_action :set_goal - before_action :set_objective, only: [:show, :edit, :update, :destroy, :add_tag, :remove_tag] - before_action :set_objective_tags, only: [:edit, :add_tag, :remove_tag] +# frozen_string_literal: true - def index - @objectives = @goal.objectives - end +module Admin + class ObjectivesController < AdminController + before_action :set_goal + before_action :set_objective, only: %i[show edit update destroy add_tag remove_tag] + before_action :set_objective_tags, only: %i[edit add_tag remove_tag] - def show - end + def index + @objectives = @goal.objectives + end - def new - ensure_performance_manager_permissions + def show; end - @objective = Objective.new - @objective.goal_id = @goal.id - @objective.organization_id = @goal.organization_id - @objective.name = 'New Objective' - render :layout => false - end + def new + ensure_performance_manager_permissions - def edit - ensure_performance_manager_permissions + @objective = Objective.new + @objective.goal_id = @goal.id + @objective.organization_id = @goal.organization_id + @objective.name = 'New Objective' + render layout: false + end - render layout: false - end + def edit + ensure_performance_manager_permissions - def create - ensure_performance_manager_permissions + render layout: false + end - @objective = Objective.new(objective_params) - respond_to do |format| - if @objective.save! - format.html { redirect_to admin_objective_path(@objective), notice: 'Objective was successfully created.'} - format.json { render :create, status: :created, goal: @goal } - format.js - else - format.html { render :new } - format.json { render json: @objective.errors, status: :unprocessable_entity } + def create + ensure_performance_manager_permissions + + @objective = Objective.new(objective_params) + respond_to do |format| + if @objective.save! + format.html { redirect_to admin_objective_path(@objective), notice: 'Objective was successfully created.' } + format.json { render :create, status: :created, goal: @goal } + else + format.html { render :new } + format.json { render json: @objective.errors, status: :unprocessable_entity } + end format.js end end - end - def update - ensure_performance_manager_permissions - - @objective.update(objective_params) - @objective.tags = objective_params[:tags].split(" ") - @objective.users = [objective_params[:users].to_i] if objective_params[:users].present? - respond_to do |format| - if @objective.save - format.html { redirect_to admin_objective_path(@objective), notice: 'Objective was successfully updated.'} - format.json { render :update, status: :updated, goal: @goal } - format.js - else - format.html { render :edit } - format.json { render json: @objective.errors, status: :unprocessable_entity } + def update + ensure_performance_manager_permissions + + @objective.update(objective_params) + @objective.tags = objective_params[:tags].split + @objective.users = [objective_params[:users].to_i] if objective_params[:users].present? + respond_to do |format| + if @objective.save + format.html { redirect_to admin_objective_path(@objective), notice: 'Objective was successfully updated.' } + format.json { render :update, status: :updated, goal: @goal } + else + format.html { render :edit } + format.json { render json: @objective.errors, status: :unprocessable_entity } + end format.js end end - end - def destroy - ensure_performance_manager_permissions + def destroy + ensure_performance_manager_permissions - @objective.destroy - respond_to do |format| - format.html { redirect_to admin_objectives_url, notice: 'Objective was successfully destroyed.'} - format.json { render :destroy, status: :deleted, goal: @goal } - format.js + @objective.destroy + respond_to do |format| + format.html { redirect_to admin_objectives_url, notice: 'Objective was successfully destroyed.' } + format.json { render :destroy, status: :deleted, goal: @goal } + format.js + end end - end - def add_tag - @objective.tag_list.add(objective_params[:tag_list].split(',')) - @objective.save - end + def add_tag + @objective.tag_list.add(objective_params[:tag_list].split(',')) + @objective.save + end - def remove_tag - @objective.tag_list.remove(objective_params[:tag_list].split(',')) - @objective.save - end + def remove_tag + @objective.tag_list.remove(objective_params[:tag_list].split(',')) + @objective.save + end + + private - private def set_goal @goal = Goal.find(params[:goal_id]) end @@ -105,7 +106,8 @@ def objective_params :milestone_id, :tags, :users, - :tag_list + :tag_list, ) end + end end diff --git a/app/controllers/admin/offerings_controller.rb b/app/controllers/admin/offerings_controller.rb index 1793cfb2e..2b00e2352 100644 --- a/app/controllers/admin/offerings_controller.rb +++ b/app/controllers/admin/offerings_controller.rb @@ -1,78 +1,76 @@ -class Admin::OfferingsController < ApplicationController +# frozen_string_literal: true - before_action :set_offering, only: [:show, :edit, :update, :destroy, :add_offering_persona, :remove_offering_persona] +module Admin + class OfferingsController < ApplicationController + before_action :set_offering, only: %i[show edit update destroy add_offering_persona remove_offering_persona] - before_action :set_offering_persona_options, only: [ - :new, - :create, - :edit, - :update, - ] + before_action :set_offering_persona_options, only: %i[ + new + create + edit + update + ] - def index - @offerings = Offering.all.order(:name) - end + def index + @offerings = Offering.all.order(:name) + end - def show - end + def show; end - def new - @offering = Offering.new - end + def new + @offering = Offering.new + end - def edit - end + def edit; end - def create - @offering = Offering.new(offering_params) + def create + @offering = Offering.new(offering_params) - if @offering.save - redirect_to admin_offering_path(@offering), notice: 'Offering was successfully created.' - else - render :new + if @offering.save + redirect_to admin_offering_path(@offering), notice: 'Offering was successfully created.' + else + render :new + end end - end - def update - if @offering.update(offering_params) - redirect_to admin_offering_path(@offering), notice: 'Offering was successfully updated.' - else - render :edit + def update + if @offering.update(offering_params) + redirect_to admin_offering_path(@offering), notice: 'Offering was successfully updated.' + else + render :edit + end end - end - def destroy - @offering.destroy - redirect_to admin_offerings_url, notice: 'Offering was successfully destroyed.' - end + def destroy + @offering.destroy + redirect_to admin_offerings_url, notice: 'Offering was successfully destroyed.' + end - def add_offering_persona - @offering.persona_list.add(params[:persona_id]) - @offering.save - set_offering_persona_options - end + def add_offering_persona + @offering.persona_list.add(params[:persona_id]) + @offering.save + set_offering_persona_options + end - def remove_offering_persona - @offering.persona_list.remove(params[:persona_id]) - @offering.save - set_offering_persona_options - end + def remove_offering_persona + @offering.persona_list.remove(params[:persona_id]) + @offering.save + set_offering_persona_options + end - private + private - def set_offering - @offering = Offering.find(params[:id]) - end + def set_offering + @offering = Offering.find(params[:id]) + end - def offering_params - params.require(:offering).permit(:name, :service_id) - end + def offering_params + params.require(:offering).permit(:name, :service_id) + end - def set_offering_persona_options - @offering_persona_options = Persona.all.order(:name) - if @offering_persona_options && @offering - @offering_persona_options = @offering_persona_options - @offering.offering_personas + def set_offering_persona_options + @offering_persona_options = Persona.all.order(:name) + @offering_persona_options -= @offering.offering_personas if @offering_persona_options && @offering end end - end diff --git a/app/controllers/admin/omb_cx_reporting_collections_controller.rb b/app/controllers/admin/omb_cx_reporting_collections_controller.rb index 5f5c69041..696f9501f 100644 --- a/app/controllers/admin/omb_cx_reporting_collections_controller.rb +++ b/app/controllers/admin/omb_cx_reporting_collections_controller.rb @@ -1,52 +1,50 @@ -class Admin::OmbCxReportingCollectionsController < AdminController - before_action :set_omb_cx_reporting_collection, only: [:show, :edit, :update, :destroy] - before_action :set_collections, only: [:new, :create, :edit, :update] +# frozen_string_literal: true - def index - ensure_admin - @omb_cx_reporting_collections = OmbCxReportingCollection.all - end +module Admin + class OmbCxReportingCollectionsController < AdminController + before_action :set_omb_cx_reporting_collection, only: %i[show edit update destroy] + before_action :set_collections, only: %i[new create edit update] - def show - end + def index + ensure_admin + @omb_cx_reporting_collections = OmbCxReportingCollection.all + end - def new - @omb_cx_reporting_collection = OmbCxReportingCollection.new + def show; end - if params[:collection_id] - if @collection = Collection.find(params[:collection_id]) - @omb_cx_reporting_collection.collection_id = params[:collection_id] - end + def new + @omb_cx_reporting_collection = OmbCxReportingCollection.new + + @omb_cx_reporting_collection.collection_id = params[:collection_id] if params[:collection_id] && @collection = Collection.find(params[:collection_id]) end - end - def edit - end + def edit; end - def create - @omb_cx_reporting_collection = OmbCxReportingCollection.new(omb_cx_reporting_collection_params) + def create + @omb_cx_reporting_collection = OmbCxReportingCollection.new(omb_cx_reporting_collection_params) - if @omb_cx_reporting_collection.save - redirect_to admin_omb_cx_reporting_collection_path(@omb_cx_reporting_collection), notice: 'Omb cx reporting collection was successfully created.' - else - render :new + if @omb_cx_reporting_collection.save + redirect_to admin_omb_cx_reporting_collection_path(@omb_cx_reporting_collection), notice: 'Omb cx reporting collection was successfully created.' + else + render :new + end end - end - def update - if @omb_cx_reporting_collection.update(omb_cx_reporting_collection_params) - redirect_to admin_omb_cx_reporting_collection_path(@omb_cx_reporting_collection), notice: 'Omb cx reporting collection was successfully updated.' - else - render :edit + def update + if @omb_cx_reporting_collection.update(omb_cx_reporting_collection_params) + redirect_to admin_omb_cx_reporting_collection_path(@omb_cx_reporting_collection), notice: 'Omb cx reporting collection was successfully updated.' + else + render :edit + end end - end - def destroy - @omb_cx_reporting_collection.destroy - redirect_to admin_collection_url(@omb_cx_reporting_collection.collection), notice: 'Omb cx reporting collection was successfully destroyed.' - end + def destroy + @omb_cx_reporting_collection.destroy + redirect_to admin_collection_url(@omb_cx_reporting_collection.collection), notice: 'Omb cx reporting collection was successfully destroyed.' + end + + private - private def set_omb_cx_reporting_collection @omb_cx_reporting_collection = OmbCxReportingCollection.find(params[:id]) end @@ -137,7 +135,8 @@ def omb_cx_reporting_collection_params :q11_2, :q11_3, :q11_4, - :q11_5 + :q11_5, ) end + end end diff --git a/app/controllers/admin/organizations_controller.rb b/app/controllers/admin/organizations_controller.rb index 25724c562..edb5aa7e8 100644 --- a/app/controllers/admin/organizations_controller.rb +++ b/app/controllers/admin/organizations_controller.rb @@ -1,181 +1,184 @@ -class Admin::OrganizationsController < AdminController - - before_action :set_organization, only: [ - :show, - :performance, - :edit, - :update, - :performance_update, - :destroy, - :add_tag, - :remove_tag, - :create_two_year_goal, - :create_four_year_goal, - :delete_two_year_goal, - :delete_four_year_goal, - :sort_goals, - :sort_objectives - ] - - def index - @organizations = Organization.all.order(:name) - @tags = Organization.tag_counts_by_name - end +# frozen_string_literal: true + +module Admin + class OrganizationsController < AdminController + before_action :set_organization, only: %i[ + show + performance + edit + update + performance_update + destroy + add_tag + remove_tag + create_two_year_goal + create_four_year_goal + delete_two_year_goal + delete_four_year_goal + sort_goals + sort_objectives + ] + + def index + @organizations = Organization.all.order(:name) + @tags = Organization.tag_counts_by_name + end - def show - @forms = @organization.forms - @collections = @organization.collections - @users = @organization.users.active.order(:email) - end + def show + @forms = @organization.forms + @collections = @organization.collections + @users = @organization.users.active.order(:email) + end - def new - ensure_admin + def new + ensure_admin - @organization = Organization.new - end + @organization = Organization.new + end - def edit - ensure_admin - end + def edit + ensure_admin + end - def performance - ensure_performance_manager_permissions - end + def performance + ensure_performance_manager_permissions + end - def create - ensure_admin + def create + ensure_admin - @organization = Organization.new(organization_params) + @organization = Organization.new(organization_params) - respond_to do |format| - if @organization.save - format.html { redirect_to admin_organization_path(@organization), notice: 'Organization was successfully created.' } - format.json { render :show, status: :created, location: @organization } - else - format.html { render :new } - format.json { render json: @organization.errors, status: :unprocessable_entity } + respond_to do |format| + if @organization.save + format.html { redirect_to admin_organization_path(@organization), notice: 'Organization was successfully created.' } + format.json { render :show, status: :created, location: @organization } + else + format.html { render :new } + format.json { render json: @organization.errors, status: :unprocessable_entity } + end end end - end - def create_four_year_goal - ensure_performance_manager_permissions + def create_four_year_goal + ensure_performance_manager_permissions - @goal = Goal.new - @goal.organization_id = @organization.id - @goal.four_year_goal = true - @goal.name = "New Strategic Goal" - @goal.save - end + @goal = Goal.new + @goal.organization_id = @organization.id + @goal.four_year_goal = true + @goal.name = 'New Strategic Goal' + @goal.save + end - def create_two_year_goal - ensure_performance_manager_permissions + def create_two_year_goal + ensure_performance_manager_permissions - @goal = Goal.new - @goal.organization_id = @organization.id - @goal.four_year_goal = false - @goal.name = "New 2 Year APG" - @goal.save - end + @goal = Goal.new + @goal.organization_id = @organization.id + @goal.four_year_goal = false + @goal.name = 'New 2 Year APG' + @goal.save + end - def sort_goals - ensure_performance_manager_permissions + def sort_goals + ensure_performance_manager_permissions - params[:goal].each_with_index do |id, index| - Goal.where(id: id).update_all(position: index + 1) + params[:goal].each_with_index do |id, index| + Goal.where(id:).update_all(position: index + 1) + end + + head :ok end - head :ok - end + def sort_objectives + ensure_performance_manager_permissions - def sort_objectives - ensure_performance_manager_permissions + params[:objective].each_with_index do |id, index| + Objective.where(id:).update_all(position: index + 1) + end - params[:objective].each_with_index do |id, index| - Objective.where(id: id).update_all(position: index + 1) + head :ok end - head :ok - end - - def delete_two_year_goal - ensure_performance_manager_permissions + def delete_two_year_goal + ensure_performance_manager_permissions - Goal.find(params[:goal_id]).destroy - end + Goal.find(params[:goal_id]).destroy + end - def delete_four_year_goal - ensure_performance_manager_permissions + def delete_four_year_goal + ensure_performance_manager_permissions - Goal.find(params[:goal_id]).destroy - end + Goal.find(params[:goal_id]).destroy + end - def update - ensure_admin + def update + ensure_admin + + respond_to do |format| + if @organization.update(organization_params) + format.html { redirect_to admin_organization_path(@organization), notice: 'Organization was successfully updated.' } + format.json { render :show, status: :ok, location: @organization } + else + format.html { render :edit } + format.json { render json: @organization.errors, status: :unprocessable_entity } + end + end + end - respond_to do |format| - if @organization.update(organization_params) - format.html { redirect_to admin_organization_path(@organization), notice: 'Organization was successfully updated.' } - format.json { render :show, status: :ok, location: @organization } - else - format.html { render :edit } - format.json { render json: @organization.errors, status: :unprocessable_entity } + def performance_update + ensure_performance_manager_permissions + + respond_to do |format| + if @organization.update(organization_params) + format.html { redirect_to performance_admin_organization_path(@organization), notice: 'Organization was successfully updated.' } + format.json { render :show, status: :ok, location: @organization } + else + format.html { render :edit } + format.json { render json: @organization.errors, status: :unprocessable_entity } + end end end - end - def performance_update - ensure_performance_manager_permissions + def destroy + ensure_admin - respond_to do |format| - if @organization.update(organization_params) - format.html { redirect_to performance_admin_organization_path(@organization), notice: 'Organization was successfully updated.' } - format.json { render :show, status: :ok, location: @organization } - else - format.html { render :edit } - format.json { render json: @organization.errors, status: :unprocessable_entity } + @organization.destroy + respond_to do |format| + format.html { redirect_to admin_organizations_url, notice: 'Organization was successfully destroyed.' } + format.json { head :no_content } end end - end - def destroy - ensure_admin - - @organization.destroy - respond_to do |format| - format.html { redirect_to admin_organizations_url, notice: 'Organization was successfully destroyed.' } - format.json { head :no_content } + def search + search_text = params[:search] + tag_name = params[:tag] + if search_text.present? + search_text = "%#{search_text}%" + @organizations = Organization.where(' domain ilike ? or name ilike ? or abbreviation ilike ? or url ilike ? ', search_text, search_text, search_text, search_text) + elsif tag_name.present? + @organizations = Organization.tagged_with(tag_name) + else + @organizations = Organization.all + end end - end - def search - search_text = params[:search] - tag_name = params[:tag] - if search_text.present? - search_text = "%" + search_text + "%" - @organizations = Organization.where(" domain ilike ? or name ilike ? or abbreviation ilike ? or url ilike ? ", search_text, search_text, search_text, search_text) - elsif tag_name.present? - @organizations = Organization.tagged_with(tag_name) - else - @organizations = Organization.all + def add_tag + ensure_admin + + @organization.tag_list.add(organization_params[:tag_list].split(',')) + @organization.save end - end - def add_tag - ensure_admin + def remove_tag + ensure_admin - @organization.tag_list.add(organization_params[:tag_list].split(',')) - @organization.save - end + @organization.tag_list.remove(organization_params[:tag_list].split(',')) + @organization.save + end - def remove_tag - ensure_admin - - @organization.tag_list.remove(organization_params[:tag_list].split(',')) - @organization.save - end + private - private def set_organization @organization = Organization.find_by_id(params[:id]) || Organization.find_by_abbreviation(params[:id].upcase) end @@ -199,4 +202,5 @@ def organization_params :learning_agenda_url, ) end + end end diff --git a/app/controllers/admin/performance_controller.rb b/app/controllers/admin/performance_controller.rb index dbf470128..e01c1f3f2 100644 --- a/app/controllers/admin/performance_controller.rb +++ b/app/controllers/admin/performance_controller.rb @@ -1,23 +1,25 @@ -class Admin::PerformanceController < AdminController - before_action :set_organization, only: [:edit, :apg] +# frozen_string_literal: true - def index - end +module Admin + class PerformanceController < AdminController + before_action :set_organization, only: %i[edit apg] - def edit - end + def index; end - def apg - @apg = Objective.find(params[:apg]) - end + def edit; end - def apgs - @organizations = Organization.all.order(:name) - end + def apg + @apg = Objective.find(params[:apg]) + end + + def apgs + @organizations = Organization.all.order(:name) + end - private + private - def set_organization - @organization = Organization.find_by_id(params[:id]) || Organization.find_by_abbreviation(params[:id].upcase) + def set_organization + @organization = Organization.find_by_id(params[:id]) || Organization.find_by_abbreviation(params[:id].upcase) + end end end diff --git a/app/controllers/admin/personas_controller.rb b/app/controllers/admin/personas_controller.rb index 75eb16b17..4e9595d54 100644 --- a/app/controllers/admin/personas_controller.rb +++ b/app/controllers/admin/personas_controller.rb @@ -1,44 +1,46 @@ -class Admin::PersonasController < AdminController - before_action :set_persona, only: [:show, :edit, :update, :destroy] +# frozen_string_literal: true - def index - @personas = Persona.all.order(:name) - end +module Admin + class PersonasController < AdminController + before_action :set_persona, only: %i[show edit update destroy] - def show - end + def index + @personas = Persona.all.order(:name) + end - def new - @persona = Persona.new - end + def show; end - def edit - end + def new + @persona = Persona.new + end + + def edit; end - def create - @persona = Persona.new(persona_params) + def create + @persona = Persona.new(persona_params) - if @persona.save! - redirect_to admin_persona_path(@persona), notice: 'Persona was successfully created.' - else - render :new + if @persona.save! + redirect_to admin_persona_path(@persona), notice: 'Persona was successfully created.' + else + render :new + end end - end - def update - if @persona.update(persona_params) - redirect_to admin_persona_path(@persona), notice: 'Persona was successfully updated.' - else - render :edit + def update + if @persona.update(persona_params) + redirect_to admin_persona_path(@persona), notice: 'Persona was successfully updated.' + else + render :edit + end end - end - def destroy - @persona.destroy - redirect_to admin_personas_url, notice: 'Persona was successfully destroyed.' - end + def destroy + @persona.destroy + redirect_to admin_personas_url, notice: 'Persona was successfully destroyed.' + end + + private - private def set_persona @persona = Persona.find(params[:id]) end @@ -46,4 +48,5 @@ def set_persona def persona_params params.require(:persona).permit(:name, :description, :tags, :notes, :user_id) end + end end diff --git a/app/controllers/admin/question_options_controller.rb b/app/controllers/admin/question_options_controller.rb index 7c0f2d473..cd84f97fc 100644 --- a/app/controllers/admin/question_options_controller.rb +++ b/app/controllers/admin/question_options_controller.rb @@ -1,103 +1,106 @@ -class Admin::QuestionOptionsController < AdminController - before_action :set_question, only: [:new, :create, :create_other, :show, :edit, :update, :destroy] - before_action :set_question_option, only: [:show, :edit, :update, :destroy] +# frozen_string_literal: true - def index - @question_options = QuestionOption.all - end +module Admin + class QuestionOptionsController < AdminController + before_action :set_question, only: %i[new create create_other show edit update destroy] + before_action :set_question_option, only: %i[show edit update destroy] - def show - end + def index + @question_options = QuestionOption.all + end - def new - @question_option = QuestionOption.new - render layout: false - end + def show; end - def edit - render layout: false - end + def new + @question_option = QuestionOption.new + render layout: false + end - def sort - params[:question_option].each_with_index do |id, index| - QuestionOption.find(id).update(position: index + 1) + def edit + render layout: false end - head :ok - end + def sort + params[:question_option].each_with_index do |id, index| + QuestionOption.find(id).update(position: index + 1) + end - def update_title - question_option = QuestionOption.where(id: params[:question_option_id]).first - question_option.update!(text: params[:text]) - render json: question_option - end + head :ok + end - def create - text_array = question_option_params[:text].split("\n") - position = @question.question_options.size + 1 - @question_options = [] - @errors = [] - result = false - - if text_array.length > 0 - text_array.each do | txt | - if (txt.upcase == 'OTHER' || txt.upcase == 'OTRO') - @errors << "Use add #{txt} button" - next - end - question_option = QuestionOption.where(question_id: params[:question_id], text: txt).first - if question_option - @errors << "Question option already exists for text #{txt}" - next - end - question_option = QuestionOption.new(question_id: params[:question_id], text: txt, value: txt, position: position) - if question_option.save - @question_options << question_option - position += 1 - else - @errors << question_option.errors.full_messages + def update_title + question_option = QuestionOption.where(id: params[:question_option_id]).first + question_option.update!(text: params[:text]) + render json: question_option + end + + def create + text_array = question_option_params[:text].split("\n") + position = @question.question_options.size + 1 + @question_options = [] + @errors = [] + result = false + + if text_array.length.positive? + text_array.each do |txt| + if txt.upcase == 'OTHER' || txt.upcase == 'OTRO' + @errors << "Use add #{txt} button" + next + end + question_option = QuestionOption.where(question_id: params[:question_id], text: txt).first + if question_option + @errors << "Question option already exists for text #{txt}" + next + end + question_option = QuestionOption.new(question_id: params[:question_id], text: txt, value: txt, position:) + if question_option.save + @question_options << question_option + position += 1 + else + @errors << question_option.errors.full_messages + end end - end - else - question_option = QuestionOption.where(question_id: params[:question_id], text: params[:text]).first - if question_option - @errors << "Question option already exists for text #{params[:text]}" else - question_option = QuestionOption.new(question_option_params) - question_option.position = position - if question_option.save - @question_options << question_option + question_option = QuestionOption.where(question_id: params[:question_id], text: params[:text]).first + if question_option + @errors << "Question option already exists for text #{params[:text]}" else - @errors << question_option.errors.full_messages + question_option = QuestionOption.new(question_option_params) + question_option.position = position + if question_option.save + @question_options << question_option + else + @errors << question_option.errors.full_messages + end end end + render :create, format: :js end - render :create, format: :js - end - def create_other - @errors = [] - question_option = QuestionOption.new() - question_option.position = @question.question_options.size + 1 - question_option.question_id = @question.id - question_option.text = "Other" - question_option.value = "OTHER" - question_option.save! - @question_options = [ question_option ] - render :create, format: :js - end + def create_other + @errors = [] + question_option = QuestionOption.new + question_option.position = @question.question_options.size + 1 + question_option.question_id = @question.id + question_option.text = 'Other' + question_option.value = 'OTHER' + question_option.save! + @question_options = [question_option] + render :create, format: :js + end - def update - @question_option.update(question_option_params) - render :update, format: :js - end + def update + @question_option.update(question_option_params) + render :update, format: :js + end - def destroy - @question_option.destroy - head :ok - end + def destroy + @question_option.destroy + head :ok + end + + private - private def set_question_option @question_option = QuestionOption.find(params[:id]) end @@ -111,7 +114,8 @@ def question_option_params :question_id, :text, :position, - :value + :value, ) end + end end diff --git a/app/controllers/admin/questions_controller.rb b/app/controllers/admin/questions_controller.rb index 92e3067af..5aebe8428 100644 --- a/app/controllers/admin/questions_controller.rb +++ b/app/controllers/admin/questions_controller.rb @@ -1,74 +1,77 @@ -class Admin::QuestionsController < AdminController - before_action :set_form, only: [:new, :create, :show, :edit, :update, :sort, :destroy] - before_action :set_question, only: [:show, :edit, :update, :destroy] +# frozen_string_literal: true - def index - @questions = Question.all.order(:position) - end +module Admin + class QuestionsController < AdminController + before_action :set_form, only: %i[new create show edit update sort destroy] + before_action :set_question, only: %i[show edit update destroy] - def show - render layout: false - end + def index + @questions = Question.all.order(:position) + end - def new - @question = Question.new - set_defaults - render layout: false - end + def show + render layout: false + end - def edit - render layout: false - end + def new + @question = Question.new + set_defaults + render layout: false + end - def sort - form_section_id = params[:form_section_id] - params[:question].each_with_index do |id, index| - @form.questions.find(id).update(position: index + 1, form_section_id: form_section_id) + def edit + render layout: false end - head :ok - end + def sort + form_section_id = params[:form_section_id] + params[:question].each_with_index do |id, index| + @form.questions.find(id).update(position: index + 1, form_section_id:) + end - def create - next_position = @form.questions.size + 1 - @question = Question.new(question_params) - @question.position = next_position - - respond_to do |format| - if @question.save - format.html { redirect_to questions_admin_form_path(@form), notice: 'Question was successfully created.' } - format.json { render json: @question } - else - format.html { render :new } - format.json { render json: @question.errors, status: :unprocessable_entity } + head :ok + end + + def create + next_position = @form.questions.size + 1 + @question = Question.new(question_params) + @question.position = next_position + + respond_to do |format| + if @question.save + format.html { redirect_to questions_admin_form_path(@form), notice: 'Question was successfully created.' } + format.json { render json: @question } + else + format.html { render :new } + format.json { render json: @question.errors, status: :unprocessable_entity } + end end end - end - def update - respond_to do |format| - if @question.update(question_params) - format.html { render layout: false } - format.json { render json: @question } - else + def update + respond_to do |format| format.html { render layout: false } - format.json { render json: @question.errors, status: :unprocessable_entity } + if @question.update(question_params) + format.json { render json: @question } + else + format.json { render json: @question.errors, status: :unprocessable_entity } + end end end - end - def destroy - ensure_form_manager(form: @form) + def destroy + ensure_form_manager(form: @form) - @question.destroy - respond_to do |format| - format.js { } - format.html { redirect_to questions_admin_form_url(@form), notice: 'Question was successfully destroyed.' } - format.json { head :no_content } + @question.destroy + respond_to do |format| + format.js {} + format.html { redirect_to questions_admin_form_url(@form), notice: 'Question was successfully destroyed.' } + format.json { head :no_content } + end end - end - private + private + def set_form @form = Form.find_by_short_uuid(params[:form_id]) end @@ -80,8 +83,8 @@ def set_question def set_defaults @question.form_id = @form.id @question.form_section_id = params[:form_section_id] - @question.text = "New Question" - @question.question_type = "text_field" + @question.text = 'New Question' + @question.question_type = 'text_field' @question.answer_field = first_unused_answer_field @question.save! end @@ -97,17 +100,17 @@ def question_params :answer_field, :position, :is_required, - :character_limit + :character_limit, ) end def first_unused_answer_field - answer_fields = Question.where(form_id: @form.id).collect { | q | q.answer_field } - (1..20).each do | ind | - af = "answer_#{ind.to_s.rjust(2,"0")}" + answer_fields = Question.where(form_id: @form.id).collect(&:answer_field) + (1..20).each do |ind| + af = "answer_#{ind.to_s.rjust(2, '0')}" return af unless answer_fields.include?(af) end - "answer_01" + 'answer_01' end - + end end diff --git a/app/controllers/admin/reporting_controller.rb b/app/controllers/admin/reporting_controller.rb index b90f16609..92cecd430 100644 --- a/app/controllers/admin/reporting_controller.rb +++ b/app/controllers/admin/reporting_controller.rb @@ -1,390 +1,391 @@ -class Admin::ReportingController < AdminController - def hisps - row = [] - header_fields = [ - :department, - :department_abbreviation, - :service_provider_id, - :name, - :description, - :notes, - :new_hisp +# frozen_string_literal: true + +module Admin + class ReportingController < AdminController + def hisps + row = [] + header_fields = %i[ + department + department_abbreviation + service_provider_id + name + description + notes + new_hisp ] - row << header_fields.join(",") - - ServiceProvider.active.includes(:organization).order("organizations.name", :name).each do |hisp| - row_fields = [ - hisp.organization.name, - hisp.organization.abbreviation.downcase, - hisp.slug, - "\"#{hisp.name}\"", - "\"#{hisp.description}\"", - "\"#{hisp.notes}\"", - hisp.new, - ] - row << row_fields.join(",") - end - - render plain: row.join("\n") - end - - def hisp_services - row = [] - header_fields = [ - :organization_name, - :organization_abbreviation, - :organization_id, - :service_provider_name, - :service_provider_slug, - :year, - :quarter, - :service_provided, - :transaction_point, - :channel, - :total_volume, - :surveys_offered_count, - :response_count, - :satisfied, - :trust, - :effective, - :easy, - :efficient, - :transparent, - :employee - ] - - row << header_fields.join(",") - - ServiceProvider.all.includes(:organization).order("organizations.name", :name).each do |service_provider| - service_provider.services.order(:name).each do |service| - service.omb_cx_reporting_collections.includes(:service, :collection).order("collections.year", "collections.quarter", "services.name").each do |omb_cx_reporting_collection| - - row_fields = [ - omb_cx_reporting_collection.organization_abbreviation, - "\"#{omb_cx_reporting_collection.organization_name}\"", - omb_cx_reporting_collection.organization_id, - "\"#{omb_cx_reporting_collection.collection.service_provider.name}\"", - omb_cx_reporting_collection.collection.service_provider.slug, - omb_cx_reporting_collection.collection.year, - omb_cx_reporting_collection.collection.quarter, - "\"#{omb_cx_reporting_collection.service_provided}\"", - "\"#{omb_cx_reporting_collection.transaction_point}\"", - "\"#{omb_cx_reporting_collection.channel}\"", - omb_cx_reporting_collection.volume_of_customers, - omb_cx_reporting_collection.volume_of_customers_provided_survey_opportunity, - omb_cx_reporting_collection.volume_of_respondents, - omb_cx_reporting_collection.q1_point_scale, - omb_cx_reporting_collection.q2_point_scale, - omb_cx_reporting_collection.q3_point_scale, - omb_cx_reporting_collection.q4_point_scale, - omb_cx_reporting_collection.q5_point_scale, - omb_cx_reporting_collection.q6_point_scale, - omb_cx_reporting_collection.q7_point_scale - ] - row << row_fields.join(",") - - end + row << header_fields.join(',') + + ServiceProvider.active.includes(:organization).order('organizations.name', :name).each do |hisp| + row_fields = [ + hisp.organization.name, + hisp.organization.abbreviation.downcase, + hisp.slug, + "\"#{hisp.name}\"", + "\"#{hisp.description}\"", + "\"#{hisp.notes}\"", + hisp.new, + ] + row << row_fields.join(',') end - end - render plain: row.join("\n") - end - - def hisp_service_cx_data_collections - rows = [] - header_fields = [ - :organization_abbreviation, - :organization_name, - :organization_id, - :collection_name, - :collection_id, - :year, - :quarter, - :service_provider_name, - :service_provider_slug, - :service_provider_id, - :service_name, - :service_slug, - :service_id, - :service_provided, - :transaction_point, - :channel, - :volume_of_customers, - :volume_of_customers_provided_survey_opportunity, - :volume_of_customers, - :volume_of_respondents, - :omb_control_number, - :federal_register_url, - :operational_metrics, - :start_date, - :end_date - ] + render plain: row.join("\n") + end - rows << header_fields.join(",") + def hisp_services + row = [] + header_fields = %i[ + organization_name + organization_abbreviation + organization_id + service_provider_name + service_provider_slug + year + quarter + service_provided + transaction_point + channel + total_volume + surveys_offered_count + response_count + satisfied + trust + effective + easy + efficient + transparent + employee + ] - ServiceProvider.active.includes(:organization).order("organizations.name", :name).each do |service_provider| - service_provider.services.includes(:organization).order("organizations.name", :name).each do |service| - if params[:quarter] - @collections = service.collections.where(quarter: params[:quarter]) - else - @collections = service.collections - end + row << header_fields.join(',') - @collections.each do |collection| - collection.omb_cx_reporting_collections.includes(:collection).order("collections.year", "collections.quarter", "omb_cx_reporting_collections.service_provided", "omb_cx_reporting_collections.channel").each do |omb_cx_reporting_collection| + ServiceProvider.all.includes(:organization).order('organizations.name', :name).each do |service_provider| + service_provider.services.order(:name).each do |service| + service.omb_cx_reporting_collections.includes(:service, :collection).order('collections.year', 'collections.quarter', 'services.name').each do |omb_cx_reporting_collection| row_fields = [ omb_cx_reporting_collection.organization_abbreviation, "\"#{omb_cx_reporting_collection.organization_name}\"", omb_cx_reporting_collection.organization_id, - "\"#{omb_cx_reporting_collection.collection.name}\"", - omb_cx_reporting_collection.collection.id, - omb_cx_reporting_collection.collection.year, - omb_cx_reporting_collection.collection.quarter, "\"#{omb_cx_reporting_collection.collection.service_provider.name}\"", omb_cx_reporting_collection.collection.service_provider.slug, - omb_cx_reporting_collection.collection.service_provider.id, - omb_cx_reporting_collection.service.name, - omb_cx_reporting_collection.service.service_slug, - omb_cx_reporting_collection.service.id, + omb_cx_reporting_collection.collection.year, + omb_cx_reporting_collection.collection.quarter, "\"#{omb_cx_reporting_collection.service_provided}\"", "\"#{omb_cx_reporting_collection.transaction_point}\"", "\"#{omb_cx_reporting_collection.channel}\"", omb_cx_reporting_collection.volume_of_customers, omb_cx_reporting_collection.volume_of_customers_provided_survey_opportunity, - omb_cx_reporting_collection.volume_of_customers, omb_cx_reporting_collection.volume_of_respondents, - omb_cx_reporting_collection.omb_control_number, - omb_cx_reporting_collection.federal_register_url, - omb_cx_reporting_collection.operational_metrics, - omb_cx_reporting_collection.collection.start_date, - omb_cx_reporting_collection.collection.end_date + omb_cx_reporting_collection.q1_point_scale, + omb_cx_reporting_collection.q2_point_scale, + omb_cx_reporting_collection.q3_point_scale, + omb_cx_reporting_collection.q4_point_scale, + omb_cx_reporting_collection.q5_point_scale, + omb_cx_reporting_collection.q6_point_scale, + omb_cx_reporting_collection.q7_point_scale, ] - rows << row_fields.join(",") + row << row_fields.join(',') end end end - end - - render plain: rows.join("\n") - end - def hisp_service_cx_data_collections_summary - rows = [] - header_fields = [ - :organization_abbreviation, - :organization_name, - :organization_id, - :service_provider_name, - :service_provider_id, - :service_id, - :year, - :quarter, - :service_provided, - :transaction_point, - :channel, - :standardized_question_number, - :standardized_question_identifier, - :customized_question_text, - :likert_scale_1, - :likert_scale_2, - :likert_scale_3, - :likert_scale_4, - :likert_scale_5, - :point_scale, - :response_volume, - :notes, - :question_total, - :start_date, - :end_date - ] + render plain: row.join("\n") + end - rows << header_fields.join(",") + def hisp_service_cx_data_collections + rows = [] + header_fields = %i[ + organization_abbreviation + organization_name + organization_id + collection_name + collection_id + year + quarter + service_provider_name + service_provider_slug + service_provider_id + service_name + service_slug + service_id + service_provided + transaction_point + channel + volume_of_customers + volume_of_customers_provided_survey_opportunity + volume_of_customers + volume_of_respondents + omb_control_number + federal_register_url + operational_metrics + start_date + end_date + ] - ServiceProvider.active.includes(:organization).order("organizations.name", :name).each do |service_provider| - service_provider.services.includes(:organization).order("organizations.name", :name).each do |service| - if params[:quarter] - @collections = service.collections.where(quarter: params[:quarter]) - else - @collections = service.collections - end + rows << header_fields.join(',') - @collections.each do |collection| - collection.omb_cx_reporting_collections.includes(:collection).order("collections.year", "collections.quarter", "omb_cx_reporting_collections.service_provided", "omb_cx_reporting_collections.channel").each do |omb_cx_reporting_collection| - # WRITE A CSV LINE FOR EACH OF THE 7 STANDARD QUESTIONS - (1..7).each do |question_number| - next if params[:question] && (question_number.to_s != params[:question]) + ServiceProvider.active.includes(:organization).order('organizations.name', :name).each do |service_provider| + service_provider.services.includes(:organization).order('organizations.name', :name).each do |service| + if params[:quarter] + @collections = service.collections.where(quarter: params[:quarter]) + else + @collections = service.collections + end + @collections.each do |collection| + collection.omb_cx_reporting_collections.includes(:collection).order('collections.year', 'collections.quarter', 'omb_cx_reporting_collections.service_provided', 'omb_cx_reporting_collections.channel').each do |omb_cx_reporting_collection| row_fields = [ omb_cx_reporting_collection.organization_abbreviation, "\"#{omb_cx_reporting_collection.organization_name}\"", omb_cx_reporting_collection.organization_id, + "\"#{omb_cx_reporting_collection.collection.name}\"", + omb_cx_reporting_collection.collection.id, + omb_cx_reporting_collection.collection.year, + omb_cx_reporting_collection.collection.quarter, "\"#{omb_cx_reporting_collection.collection.service_provider.name}\"", omb_cx_reporting_collection.collection.service_provider.slug, + omb_cx_reporting_collection.collection.service_provider.id, + omb_cx_reporting_collection.service.name, omb_cx_reporting_collection.service.service_slug, - omb_cx_reporting_collection.collection.year, - omb_cx_reporting_collection.collection.quarter, + omb_cx_reporting_collection.service.id, "\"#{omb_cx_reporting_collection.service_provided}\"", "\"#{omb_cx_reporting_collection.transaction_point}\"", "\"#{omb_cx_reporting_collection.channel}\"", - question_number, - hisp_questions_key[question_number.to_s], - "\"#{omb_cx_reporting_collection.send("q#{question_number}_text")}\"", - omb_cx_reporting_collection.send("q#{question_number}_1"), - omb_cx_reporting_collection.send("q#{question_number}_2"), - omb_cx_reporting_collection.send("q#{question_number}_3"), - omb_cx_reporting_collection.send("q#{question_number}_4"), - omb_cx_reporting_collection.send("q#{question_number}_5"), - omb_cx_reporting_collection.send("q#{question_number}_point_scale"), - omb_cx_reporting_collection.question_total(question: "q#{question_number}"), - "", + omb_cx_reporting_collection.volume_of_customers, + omb_cx_reporting_collection.volume_of_customers_provided_survey_opportunity, + omb_cx_reporting_collection.volume_of_customers, + omb_cx_reporting_collection.volume_of_respondents, + omb_cx_reporting_collection.omb_control_number, + omb_cx_reporting_collection.federal_register_url, + omb_cx_reporting_collection.operational_metrics, omb_cx_reporting_collection.collection.start_date, - omb_cx_reporting_collection.collection.end_date + omb_cx_reporting_collection.collection.end_date, ] - rows << row_fields.join(",") - + rows << row_fields.join(',') end end end end - end - render plain: rows.join("\n") - end + render plain: rows.join("\n") + end - def hisp_service_questions - rows = [] - header_fields = [ - :organization_abbreviation, - :organization_name, - :organization_id, - :service_provider_name, - :service_provider_id, - :service_name, - :service_id, - :year, - :quarter, - :service_provided, - :transaction_point, - :channel, - :standardized_question_number, - :standardized_question_identifier, - :customized_question_text, - :likert_scale_1, - :likert_scale_2, - :likert_scale_3, - :likert_scale_4, - :likert_scale_5, - :point_scale, - :response_volume, - :notes, - :question_total, - :start_date, - :end_date - ] + def hisp_service_cx_data_collections_summary + rows = [] + header_fields = %i[ + organization_abbreviation + organization_name + organization_id + service_provider_name + service_provider_id + service_id + year + quarter + service_provided + transaction_point + channel + standardized_question_number + standardized_question_identifier + customized_question_text + likert_scale_1 + likert_scale_2 + likert_scale_3 + likert_scale_4 + likert_scale_5 + point_scale + response_volume + notes + question_total + start_date + end_date + ] - header_fields.join(",") + rows << header_fields.join(',') - rows << header_fields.join(",") + ServiceProvider.active.includes(:organization).order('organizations.name', :name).each do |service_provider| + service_provider.services.includes(:organization).order('organizations.name', :name).each do |service| + if params[:quarter] + @collections = service.collections.where(quarter: params[:quarter]) + else + @collections = service.collections + end - ServiceProvider.active.includes(:organization).order("organizations.name", :name).each do |service_provider| - service_provider.services.includes(:organization).order("organizations.name", :name).each do |service| - if params[:quarter] - @collections = service.collections.where(quarter: params[:quarter]) - else - @collections = service.collections + @collections.each do |collection| + collection.omb_cx_reporting_collections.includes(:collection).order('collections.year', 'collections.quarter', 'omb_cx_reporting_collections.service_provided', 'omb_cx_reporting_collections.channel').each do |omb_cx_reporting_collection| + # WRITE A CSV LINE FOR EACH OF THE 7 STANDARD QUESTIONS + (1..7).each do |question_number| + next if params[:question] && (question_number.to_s != params[:question]) + + row_fields = [ + omb_cx_reporting_collection.organization_abbreviation, + "\"#{omb_cx_reporting_collection.organization_name}\"", + omb_cx_reporting_collection.organization_id, + "\"#{omb_cx_reporting_collection.collection.service_provider.name}\"", + omb_cx_reporting_collection.collection.service_provider.slug, + omb_cx_reporting_collection.service.service_slug, + omb_cx_reporting_collection.collection.year, + omb_cx_reporting_collection.collection.quarter, + "\"#{omb_cx_reporting_collection.service_provided}\"", + "\"#{omb_cx_reporting_collection.transaction_point}\"", + "\"#{omb_cx_reporting_collection.channel}\"", + question_number, + hisp_questions_key[question_number.to_s], + "\"#{omb_cx_reporting_collection.send("q#{question_number}_text")}\"", + omb_cx_reporting_collection.send("q#{question_number}_1"), + omb_cx_reporting_collection.send("q#{question_number}_2"), + omb_cx_reporting_collection.send("q#{question_number}_3"), + omb_cx_reporting_collection.send("q#{question_number}_4"), + omb_cx_reporting_collection.send("q#{question_number}_5"), + omb_cx_reporting_collection.send("q#{question_number}_point_scale"), + omb_cx_reporting_collection.question_total(question: "q#{question_number}"), + '', + omb_cx_reporting_collection.collection.start_date, + omb_cx_reporting_collection.collection.end_date, + ] + rows << row_fields.join(',') + end + end + end end + end - @collections.each do |collection| - collection.omb_cx_reporting_collections.includes(:collection).order("collections.year", "collections.quarter", "omb_cx_reporting_collections.service_provided", "omb_cx_reporting_collections.channel").each do |omb_cx_reporting_collection| - # WRITE A CSV LINE FOR EACH OF THE 7 STANDARD QUESTIONS - (1..7).each do |question_number| - next if params[:question] && (question_number.to_s != params[:question]) + render plain: rows.join("\n") + end - row_fields = [ - omb_cx_reporting_collection.organization_abbreviation, - "\"#{omb_cx_reporting_collection.organization_name}\"", - omb_cx_reporting_collection.organization_id, - "\"#{omb_cx_reporting_collection.collection.service_provider.name}\"", - omb_cx_reporting_collection.collection.service_provider.slug, - omb_cx_reporting_collection.service.name, - omb_cx_reporting_collection.service.service_slug, - omb_cx_reporting_collection.collection.year, - omb_cx_reporting_collection.collection.quarter, - "\"#{omb_cx_reporting_collection.service_provided}\"", - omb_cx_reporting_collection.transaction_point, - omb_cx_reporting_collection.channel, - question_number, - hisp_questions_key[question_number.to_s], - "\"#{omb_cx_reporting_collection.send("q#{question_number}_text")}\"", - omb_cx_reporting_collection.send("q#{question_number}_1"), - omb_cx_reporting_collection.send("q#{question_number}_2"), - omb_cx_reporting_collection.send("q#{question_number}_3"), - omb_cx_reporting_collection.send("q#{question_number}_4"), - omb_cx_reporting_collection.send("q#{question_number}_5"), - omb_cx_reporting_collection.send("q#{question_number}_point_scale"), - omb_cx_reporting_collection.question_total(question: "q#{question_number}"), - omb_cx_reporting_collection.collection.start_date, - omb_cx_reporting_collection.collection.end_date, - ] + def hisp_service_questions + rows = [] + header_fields = %i[ + organization_abbreviation + organization_name + organization_id + service_provider_name + service_provider_id + service_name + service_id + year + quarter + service_provided + transaction_point + channel + standardized_question_number + standardized_question_identifier + customized_question_text + likert_scale_1 + likert_scale_2 + likert_scale_3 + likert_scale_4 + likert_scale_5 + point_scale + response_volume + notes + question_total + start_date + end_date + ] - rows << row_fields.join(",") - end # 1..7 - end # omb_cx_reporting_collection - end # collection - end # service - end # service_provider + header_fields.join(',') - render plain: rows.join("\n") - end + rows << header_fields.join(',') + + ServiceProvider.active.includes(:organization).order('organizations.name', :name).each do |service_provider| + service_provider.services.includes(:organization).order('organizations.name', :name).each do |service| + if params[:quarter] + @collections = service.collections.where(quarter: params[:quarter]) + else + @collections = service.collections + end + + @collections.each do |collection| + collection.omb_cx_reporting_collections.includes(:collection).order('collections.year', 'collections.quarter', 'omb_cx_reporting_collections.service_provided', 'omb_cx_reporting_collections.channel').each do |omb_cx_reporting_collection| + # WRITE A CSV LINE FOR EACH OF THE 7 STANDARD QUESTIONS + (1..7).each do |question_number| + next if params[:question] && (question_number.to_s != params[:question]) + + row_fields = [ + omb_cx_reporting_collection.organization_abbreviation, + "\"#{omb_cx_reporting_collection.organization_name}\"", + omb_cx_reporting_collection.organization_id, + "\"#{omb_cx_reporting_collection.collection.service_provider.name}\"", + omb_cx_reporting_collection.collection.service_provider.slug, + omb_cx_reporting_collection.service.name, + omb_cx_reporting_collection.service.service_slug, + omb_cx_reporting_collection.collection.year, + omb_cx_reporting_collection.collection.quarter, + "\"#{omb_cx_reporting_collection.service_provided}\"", + omb_cx_reporting_collection.transaction_point, + omb_cx_reporting_collection.channel, + question_number, + hisp_questions_key[question_number.to_s], + "\"#{omb_cx_reporting_collection.send("q#{question_number}_text")}\"", + omb_cx_reporting_collection.send("q#{question_number}_1"), + omb_cx_reporting_collection.send("q#{question_number}_2"), + omb_cx_reporting_collection.send("q#{question_number}_3"), + omb_cx_reporting_collection.send("q#{question_number}_4"), + omb_cx_reporting_collection.send("q#{question_number}_5"), + omb_cx_reporting_collection.send("q#{question_number}_point_scale"), + omb_cx_reporting_collection.question_total(question: "q#{question_number}"), + omb_cx_reporting_collection.collection.start_date, + omb_cx_reporting_collection.collection.end_date, + ] + + rows << row_fields.join(',') + end + end + end + end + end - def lifespan - @form_lifespans = Submission.select("form_id, count(*) as num_submissions, (max(submissions.created_at) - min(submissions.created_at)) as lifespan").group(:form_id) - @forms = Form.select(:id,:name,:organization_id,:uuid).where("exists (select id, uuid from submissions where submissions.form_id = forms.id)") - @orgs = Organization.all.order(:name) - @org_summary = [] - @orgs.each do | org | - org_row = {} - org_row[:name] = org.name - org_row[:forms] = [] - total_lifespan = 0 - total_submissions = 0 - @forms.select { |form| form.organization_id == org.id }.each do |org_form| - form_summary = {} - form_summary[:id] = org_form.id - form_summary[:name] = org_form.name - form_summary[:short_uuid] = org_form.short_uuid - form_summary[:counts] = @form_lifespans.select { |row| row.form_id == org_form.id }.first - total_lifespan += form_summary[:counts].lifespan if form_summary[:counts].present? - total_submissions += form_summary[:counts].num_submissions if form_summary[:counts].present? - org_row[:forms] << form_summary + render plain: rows.join("\n") + end + + def lifespan + @form_lifespans = Submission.select('form_id, count(*) as num_submissions, (max(submissions.created_at) - min(submissions.created_at)) as lifespan').group(:form_id) + @forms = Form.select(:id, :name, :organization_id, :uuid).where('exists (select id, uuid from submissions where submissions.form_id = forms.id)') + @orgs = Organization.all.order(:name) + @org_summary = [] + @orgs.each do |org| + org_row = {} + org_row[:name] = org.name + org_row[:forms] = [] + total_lifespan = 0 + total_submissions = 0 + @forms.select { |form| form.organization_id == org.id }.each do |org_form| + form_summary = {} + form_summary[:id] = org_form.id + form_summary[:name] = org_form.name + form_summary[:short_uuid] = org_form.short_uuid + form_summary[:counts] = @form_lifespans.select { |row| row.form_id == org_form.id }.first + total_lifespan += form_summary[:counts].lifespan if form_summary[:counts].present? + total_submissions += form_summary[:counts].num_submissions if form_summary[:counts].present? + org_row[:forms] << form_summary + end + org_row[:submissions] = total_submissions + org_row[:avg_lifespan] = org_row[:forms].size.positive? ? (total_lifespan / org_row[:forms].size) : 0 + @org_summary << org_row end - org_row[:submissions] = total_submissions - org_row[:avg_lifespan] = org_row[:forms].size > 0 ? (total_lifespan / org_row[:forms].size) : 0 - @org_summary << org_row end - end - def no_submissions - @forms = Form.live.select(:id,:name,:organization_id,:uuid).where("not exists (select id, uuid from submissions where submissions.form_id = forms.id and submissions.created_at > current_date - interval '30' day)").order(:organization_id) - @orgs = Organization.all.order(:name) - @org_summary = [] - @orgs.each do | org | - org_row = {} - org_row[:name] = org.name - org_row[:forms] = [] - @forms.select { |form| form.organization_id == org.id }.each do |org_form| - form_summary = {} - form_summary[:id] = org_form.id - form_summary[:name] = org_form.name - form_summary[:short_uuid] = org_form.short_uuid - org_row[:forms] << form_summary + def no_submissions + @forms = Form.live.select(:id, :name, :organization_id, :uuid).where("not exists (select id, uuid from submissions where submissions.form_id = forms.id and submissions.created_at > current_date - interval '30' day)").order(:organization_id) + @orgs = Organization.all.order(:name) + @org_summary = [] + @orgs.each do |org| + org_row = {} + org_row[:name] = org.name + org_row[:forms] = [] + @forms.select { |form| form.organization_id == org.id }.each do |org_form| + form_summary = {} + form_summary[:id] = org_form.id + form_summary[:name] = org_form.name + form_summary[:short_uuid] = org_form.short_uuid + org_row[:forms] << form_summary + end + @org_summary << org_row end - @org_summary << org_row end - end - def service_surveys - @services = Service.includes(:organization, :forms).all.order("organizations.name, services.name") + def service_surveys + @services = Service.includes(:organization, :forms).all.order('organizations.name, services.name') + end end end diff --git a/app/controllers/admin/service_providers_controller.rb b/app/controllers/admin/service_providers_controller.rb index 635389957..d4ab3aba8 100644 --- a/app/controllers/admin/service_providers_controller.rb +++ b/app/controllers/admin/service_providers_controller.rb @@ -1,102 +1,102 @@ -class Admin::ServiceProvidersController < AdminController - before_action :set_service_provider, only: [:show, :edit, :update, :destroy, :add_tag, :remove_tag, :add_service_provider_manager,:remove_service_provider_manager,] - before_action :ensure_admin, except: [:show] - - before_action :set_service_provider_manager_options, only: [ - :new, - :create, - :edit, - :update, - :add_service_provider_manager, - :remove_service_provider_manager, - ] - - def index - @service_providers = ServiceProvider.all.includes(:organization).order("organizations.name", "service_providers.name") - @tags = ServiceProvider.tag_counts_by_name - end +# frozen_string_literal: true + +module Admin + class ServiceProvidersController < AdminController + before_action :set_service_provider, only: %i[show edit update destroy add_tag remove_tag add_service_provider_manager remove_service_provider_manager] + before_action :ensure_admin, except: [:show] + + before_action :set_service_provider_manager_options, only: %i[ + new + create + edit + update + add_service_provider_manager + remove_service_provider_manager + ] + + def index + @service_providers = ServiceProvider.all.includes(:organization).order('organizations.name', 'service_providers.name') + @tags = ServiceProvider.tag_counts_by_name + end - def show - end + def show; end - def new - @service_provider = ServiceProvider.new - end + def new + @service_provider = ServiceProvider.new + end - def edit - end + def edit; end - def create - @service_provider = ServiceProvider.new(service_provider_params) + def create + @service_provider = ServiceProvider.new(service_provider_params) - if @service_provider.save - redirect_to admin_service_provider_path(@service_provider), notice: 'Service provider was successfully created.' - else - render :new + if @service_provider.save + redirect_to admin_service_provider_path(@service_provider), notice: 'Service provider was successfully created.' + else + render :new + end end - end - def update - if @service_provider.update(service_provider_params) - redirect_to admin_service_provider_path(@service_provider), notice: 'Service provider was successfully updated.' - else - render :edit + def update + if @service_provider.update(service_provider_params) + redirect_to admin_service_provider_path(@service_provider), notice: 'Service provider was successfully updated.' + else + render :edit + end end - end - def destroy - @service_provider.destroy - redirect_to admin_service_providers_url, notice: 'Service provider was successfully destroyed.' - end + def destroy + @service_provider.destroy + redirect_to admin_service_providers_url, notice: 'Service provider was successfully destroyed.' + end - def search - search_text = params[:search] - tag_name = params[:tag] - if search_text.present? - search_text = "%" + search_text + "%" - @service_providers = ServiceProvider.joins(:organization).where(" service_providers.name ilike ? or organizations.name ilike ? ", search_text, search_text) - elsif tag_name.present? - @service_providers = ServiceProvider.tagged_with(tag_name) - else - @service_providers = ServiceProvider.all + def search + search_text = params[:search] + tag_name = params[:tag] + if search_text.present? + search_text = "%#{search_text}%" + @service_providers = ServiceProvider.joins(:organization).where(' service_providers.name ilike ? or organizations.name ilike ? ', search_text, search_text) + elsif tag_name.present? + @service_providers = ServiceProvider.tagged_with(tag_name) + else + @service_providers = ServiceProvider.all + end end - end - def add_tag - @service_provider.tag_list.add(service_provider_params[:tag_list].split(',')) - @service_provider.save - end + def add_tag + @service_provider.tag_list.add(service_provider_params[:tag_list].split(',')) + @service_provider.save + end - def remove_tag - @service_provider.tag_list.remove(service_provider_params[:tag_list].split(',')) - @service_provider.save - end + def remove_tag + @service_provider.tag_list.remove(service_provider_params[:tag_list].split(',')) + @service_provider.save + end - def add_service_provider_manager - @manager = User.find(params[:user_id]) - @manager.add_role(:service_provider_manager, @service) unless @manager.has_role?(:service_provider_manager, @service) - end + def add_service_provider_manager + @manager = User.find(params[:user_id]) + @manager.add_role(:service_provider_manager, @service) unless @manager.has_role?(:service_provider_manager, @service) + end - def remove_service_provider_manager - @manager = User.find(params[:user_id]) - @manager.remove_role(:service_provider_manager, @service) - end + def remove_service_provider_manager + @manager = User.find(params[:user_id]) + @manager.remove_role(:service_provider_manager, @service) + end + + private - private def set_service_provider @service_provider = ServiceProvider.find(params[:id]) end def set_service_provider_manager_options if service_manager_permissions? - @service_provider_manager_options = User.active.order("email") + @service_provider_manager_options = User.active.order('email') else - @service_provider_manager_options = current_user.organization.users.active.order("email") + @service_provider_manager_options = current_user.organization.users.active.order('email') end - if @service_provider_manager_options && @service_provider - @service_provider_manager_options = @service_provider_manager_options - @service_provider.service_provider_managers - end + @service_provider_manager_options -= @service_provider.service_provider_managers if @service_provider_manager_options && @service_provider end def service_provider_params @@ -114,4 +114,5 @@ def service_provider_params :tag_list, ) end + end end diff --git a/app/controllers/admin/service_stage_barriers_controller.rb b/app/controllers/admin/service_stage_barriers_controller.rb index a4a56111d..37d143f35 100644 --- a/app/controllers/admin/service_stage_barriers_controller.rb +++ b/app/controllers/admin/service_stage_barriers_controller.rb @@ -1,45 +1,47 @@ -class Admin::ServiceStageBarriersController < AdminController - before_action :ensure_admin - before_action :set_service_stage_barrier, only: [:show, :edit, :update, :destroy] +# frozen_string_literal: true - def index - @service_stage_barriers = ServiceStageBarrier.all - end +module Admin + class ServiceStageBarriersController < AdminController + before_action :ensure_admin + before_action :set_service_stage_barrier, only: %i[show edit update destroy] - def show - end + def index + @service_stage_barriers = ServiceStageBarrier.all + end - def new - @service_stage_barrier = ServiceStageBarrier.new - end + def show; end - def edit - end + def new + @service_stage_barrier = ServiceStageBarrier.new + end + + def edit; end - def create - @service_stage_barrier = ServiceStageBarrier.new(service_stage_barrier_params) + def create + @service_stage_barrier = ServiceStageBarrier.new(service_stage_barrier_params) - if @service_stage_barrier.save - redirect_to @service_stage_barrier, notice: 'Service stage barrier was successfully created.' - else - render :new + if @service_stage_barrier.save + redirect_to @service_stage_barrier, notice: 'Service stage barrier was successfully created.' + else + render :new + end end - end - def update - if @service_stage_barrier.update(service_stage_barrier_params) - redirect_to @service_stage_barrier, notice: 'Service stage barrier was successfully updated.' - else - render :edit + def update + if @service_stage_barrier.update(service_stage_barrier_params) + redirect_to @service_stage_barrier, notice: 'Service stage barrier was successfully updated.' + else + render :edit + end end - end - def destroy - @service_stage_barrier.destroy - redirect_to service_stage_barriers_url, notice: 'Service stage barrier was successfully destroyed.' - end + def destroy + @service_stage_barrier.destroy + redirect_to service_stage_barriers_url, notice: 'Service stage barrier was successfully destroyed.' + end + + private - private def set_service_stage_barrier @service_stage_barrier = ServiceStageBarrier.find(params[:id]) end @@ -47,4 +49,5 @@ def set_service_stage_barrier def service_stage_barrier_params params.require(:service_stage_barrier).permit(:service_stage_id, :barrier_id) end + end end diff --git a/app/controllers/admin/service_stages_controller.rb b/app/controllers/admin/service_stages_controller.rb index 1e0cb4281..0b42a43a6 100644 --- a/app/controllers/admin/service_stages_controller.rb +++ b/app/controllers/admin/service_stages_controller.rb @@ -1,55 +1,56 @@ -class Admin::ServiceStagesController < AdminController - before_action :set_service - before_action :set_service_stage, only: [:show, :edit, :update, :destroy] +# frozen_string_literal: true - def index - ensure_service_owner(service: @service, user: current_user) - @service_stages = @service.service_stages - end +module Admin + class ServiceStagesController < AdminController + before_action :set_service + before_action :set_service_stage, only: %i[show edit update destroy] - def show - ensure_service_owner(service: @service, user: current_user) - end + def index + ensure_service_owner(service: @service, user: current_user) + @service_stages = @service.service_stages + end - def new - ensure_service_owner(service: @service, user: current_user) - @service_stage = ServiceStage.new - end + def show + ensure_service_owner(service: @service, user: current_user) + end - def edit - ensure_service_owner(service: @service, user: current_user) - end + def new + ensure_service_owner(service: @service, user: current_user) + @service_stage = ServiceStage.new + end - def create - ensure_service_owner(service: @service, user: current_user) - @service_stage = ServiceStage.new(service_stage_params) - @service_stage.service = @service + def edit + ensure_service_owner(service: @service, user: current_user) + end + + def create + ensure_service_owner(service: @service, user: current_user) + @service_stage = ServiceStage.new(service_stage_params) + @service_stage.service = @service - if @service_stage.save - redirect_to admin_service_service_stage_path(@service, @service_stage), notice: 'Service stage was successfully created.' - else - render :new + if @service_stage.save + redirect_to admin_service_service_stage_path(@service, @service_stage), notice: 'Service stage was successfully created.' + else + render :new + end end - end - def update - ensure_service_owner(service: @service, user: current_user) - if @service_stage.update(service_stage_params) - redirect_to admin_service_service_stage_path(@service, @service_stage), notice: 'Service stage was successfully updated.' - else - render :edit + def update + ensure_service_owner(service: @service, user: current_user) + if @service_stage.update(service_stage_params) + redirect_to admin_service_service_stage_path(@service, @service_stage), notice: 'Service stage was successfully updated.' + else + render :edit + end end - end - def destroy - ensure_service_owner(service: @service, user: current_user) + def destroy + ensure_service_owner(service: @service, user: current_user) - if @service_stage.destroy - redirect_to admin_service_service_stages_url(@service), notice: 'Service stage was successfully destroyed.' + redirect_to admin_service_service_stages_url(@service), notice: 'Service stage was successfully destroyed.' if @service_stage.destroy end - end - private + private def set_service @service = Service.find(params[:service_id]) @@ -61,8 +62,9 @@ def set_service_stage def service_stage_params params.require(:service_stage).permit(:name, :description, :service_id, :notes, :time, - :position, - :persona_id, - :total_eligible_population) + :position, + :persona_id, + :total_eligible_population) end + end end diff --git a/app/controllers/admin/services_controller.rb b/app/controllers/admin/services_controller.rb index 28f502211..8a36686d6 100644 --- a/app/controllers/admin/services_controller.rb +++ b/app/controllers/admin/services_controller.rb @@ -1,235 +1,225 @@ -class Admin::ServicesController < AdminController - before_action :set_service, only: [ - :show, :edit, - :update, - :submit, :approve, :verify, :archive, :reset, - :destroy, - :equity_assessment, - :omb_cx_reporting, - :add_tag, - :remove_tag, - :add_service_manager, - :remove_service_manager, - :versions, - :export_versions - ] - before_action :set_paper_trail_whodunnit - before_action :set_service_owner_options, only: [ - :new, - :create, - :edit, - :update, - :add_service_manager, - :remove_service_manager, - :export_verions - ] - - before_action :set_service_providers, only: [ - :new, :create, :edit, :update - ] - - def index - tag_name = params[:tag] - - if service_manager_permissions? - if tag_name.present? - @services = Service.tagged_with(tag_name).includes(:organization).order("organizations.name", :name) - else - @services = Service.all.includes(:organization).order("organizations.name", :name) - end - else - if tag_name.present? - @services = current_user.organization.services.tagged_with(tag_name).includes(:organization).order("organizations.name", :name) +# frozen_string_literal: true + +module Admin + class ServicesController < AdminController + before_action :set_service, only: %i[ + show edit + update + submit approve verify archive reset + destroy + equity_assessment + omb_cx_reporting + add_tag + remove_tag + add_service_manager + remove_service_manager + versions + export_versions + ] + before_action :set_paper_trail_whodunnit + before_action :set_service_owner_options, only: %i[ + new + create + edit + update + add_service_manager + remove_service_manager + export_verions + ] + + before_action :set_service_providers, only: %i[ + new create edit update + ] + + def index + tag_name = params[:tag] + + if service_manager_permissions? + if tag_name.present? + @services = Service.tagged_with(tag_name).includes(:organization).order('organizations.name', :name) + else + @services = Service.all.includes(:organization).order('organizations.name', :name) + end + elsif tag_name.present? + @services = current_user.organization.services.tagged_with(tag_name).includes(:organization).order('organizations.name', :name) else - @services = current_user.organization.services.includes(:organization).order("organizations.name", :name) + @services = current_user.organization.services.includes(:organization).order('organizations.name', :name) end + @tags = Service.tag_counts_on(:tags) end - @tags = Service.tag_counts_on(:tags) - end - def catalog - tag_name = params[:tag] + def catalog + tag_name = params[:tag] - if service_manager_permissions? - if tag_name.present? - @services = Service.tagged_with(tag_name).includes(:organization).order("organizations.name", :name) - else - @services = Service.all.includes(:organization).order("organizations.name", :name) - end - else - if tag_name.present? - @services = current_user.organization.services.tagged_with(tag_name).includes(:organization).order("organizations.name", :name) + if service_manager_permissions? + if tag_name.present? + @services = Service.tagged_with(tag_name).includes(:organization).order('organizations.name', :name) + else + @services = Service.all.includes(:organization).order('organizations.name', :name) + end + elsif tag_name.present? + @services = current_user.organization.services.tagged_with(tag_name).includes(:organization).order('organizations.name', :name) else - @services = current_user.organization.services.includes(:organization).order("organizations.name", :name) + @services = current_user.organization.services.includes(:organization).order('organizations.name', :name) end + @tags = Service.tag_counts_on(:tags) end - @tags = Service.tag_counts_on(:tags) - end - def versions - ensure_service_manager_permissions - @versions = @service.versions.limit(500).order("created_at DESC").page params[:page] - end + def versions + ensure_service_manager_permissions + @versions = @service.versions.limit(500).order('created_at DESC').page params[:page] + end - def export_versions - ensure_admin - ExportVersionsJob.perform_later(params[:uuid], @service,'touchpoints-service-versions.csv') - render json: { result: :ok } - end + def export_versions + ensure_admin + ExportVersionsJob.perform_later(params[:uuid], @service, 'touchpoints-service-versions.csv') + render json: { result: :ok } + end - def export_csv - @services = Service.all - send_data @services.to_csv, filename: "touchpoints-services-#{Date.today}.csv" - end + def export_csv + @services = Service.all + send_data @services.to_csv, filename: "touchpoints-services-#{Date.today}.csv" + end - def show - end + def show; end - def new - @service = Service.new - @service.service_owner_id = current_user.id - end + def new + @service = Service.new + @service.service_owner_id = current_user.id + end - def edit - ensure_service_owner(service: @service, user: current_user) - end + def edit + ensure_service_owner(service: @service, user: current_user) + end - def create - @service = Service.new(service_params) - @service.organization = @service.service_provider.organization + def create + @service = Service.new(service_params) + @service.organization = @service.service_provider.organization - if @service.save - redirect_to admin_service_path(@service), notice: 'Service was successfully created.' - else - render :new + if @service.save + redirect_to admin_service_path(@service), notice: 'Service was successfully created.' + else + render :new + end end - end - def update - ensure_service_owner(service: @service, user: current_user) + def update + ensure_service_owner(service: @service, user: current_user) - if @service.update(service_params) - redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' - else - render :edit + if @service.update(service_params) + redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' + else + render :edit + end end - end - def submit - ensure_service_owner(service: @service, user: current_user) - @service.submit - if @service.save - UserMailer.service_event_notification(subject: "Service was submitted", service: @service, event: :submitted, link: admin_service_url(@service)).deliver_later - redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' + def submit + ensure_service_owner(service: @service, user: current_user) + @service.submit + if @service.save + UserMailer.service_event_notification(subject: 'Service was submitted', service: @service, event: :submitted, link: admin_service_url(@service)).deliver_later + redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' + end end - end - def approve - ensure_service_owner(service: @service, user: current_user) - @service.approve - if @service.save - UserMailer.service_event_notification(subject: "Service was approved", service: @service, event: :approved, link: admin_service_url(@service)).deliver_later - redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' + def approve + ensure_service_owner(service: @service, user: current_user) + @service.approve + if @service.save + UserMailer.service_event_notification(subject: 'Service was approved', service: @service, event: :approved, link: admin_service_url(@service)).deliver_later + redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' + end end - end - def verify - ensure_service_owner(service: @service, user: current_user) - @service.verify - if @service.save - UserMailer.service_event_notification(subject: "Service was activated", service: @service, event: :activated, link: admin_service_url(@service)).deliver_later - redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' + def verify + ensure_service_owner(service: @service, user: current_user) + @service.verify + if @service.save + UserMailer.service_event_notification(subject: 'Service was activated', service: @service, event: :activated, link: admin_service_url(@service)).deliver_later + redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' + end end - end - def archive - ensure_service_owner(service: @service, user: current_user) - @service.archive - if @service.save - UserMailer.service_event_notification(subject: "Service was archived", service: @service, event: :archived, link: admin_service_url(@service)).deliver_later - redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' + def archive + ensure_service_owner(service: @service, user: current_user) + @service.archive + if @service.save + UserMailer.service_event_notification(subject: 'Service was archived', service: @service, event: :archived, link: admin_service_url(@service)).deliver_later + redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' + end end - end - def reset - ensure_service_owner(service: @service, user: current_user) - @service.reset - if @service.save - redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' + def reset + ensure_service_owner(service: @service, user: current_user) + @service.reset + redirect_to admin_service_path(@service), notice: 'Service was successfully updated.' if @service.save end - end - def destroy - ensure_service_owner(service: @service, user: current_user) + def destroy + ensure_service_owner(service: @service, user: current_user) - if @service.destroy - redirect_to admin_services_url, notice: 'Service was successfully destroyed.' + redirect_to admin_services_url, notice: 'Service was successfully destroyed.' if @service.destroy end - end - def search - search_text = params[:search] - tag_name = params[:tag] - if search_text.present? - search_text = "%" + search_text + "%" - @services = Service.joins(:organization).where(" services.name ilike ? or organizations.name ilike ? ", search_text, search_text) - elsif tag_name.present? - @services = Service.tagged_with(tag_name) - else - @services = Service.all + def search + search_text = params[:search] + tag_name = params[:tag] + if search_text.present? + search_text = "%#{search_text}%" + @services = Service.joins(:organization).where(' services.name ilike ? or organizations.name ilike ? ', search_text, search_text) + elsif tag_name.present? + @services = Service.tagged_with(tag_name) + else + @services = Service.all + end end - end - def add_tag - @service.tag_list.add(service_params[:tag_list].split(',')) - @service.save - end + def add_tag + @service.tag_list.add(service_params[:tag_list].split(',')) + @service.save + end - def remove_tag - @service.tag_list.remove(service_params[:tag_list].split(',')) - @service.save - end + def remove_tag + @service.tag_list.remove(service_params[:tag_list].split(',')) + @service.save + end - def add_service_manager - @manager = User.find(params[:user_id]) - @manager.add_role :service_manager, @service unless @manager.has_role?(:service_manager, @service) - end + def add_service_manager + @manager = User.find(params[:user_id]) + @manager.add_role :service_manager, @service unless @manager.has_role?(:service_manager, @service) + end - def remove_service_manager - @manager = User.find(params[:user_id]) - @manager.remove_role :service_manager, @service - end + def remove_service_manager + @manager = User.find(params[:user_id]) + @manager.remove_role :service_manager, @service + end - def equity_assessment - end + def equity_assessment; end - def omb_cx_reporting - end + def omb_cx_reporting; end + + private - private def set_service @service = Service.find(params[:id]) end def set_service_providers if service_manager_permissions? - @service_providers = ServiceProvider.all.includes(:organization).order("organizations.abbreviation", "service_providers.name") + @service_providers = ServiceProvider.all.includes(:organization).order('organizations.abbreviation', 'service_providers.name') else - @service_providers = current_user.organization.service_providers.includes(:organization).order("organizations.abbreviation", "service_providers.name") + @service_providers = current_user.organization.service_providers.includes(:organization).order('organizations.abbreviation', 'service_providers.name') end end - def set_service_owner_options if service_manager_permissions? - @service_owner_options = User.active.order("email") + @service_owner_options = User.active.order('email') else - @service_owner_options = current_user.organization.users.active.order("email") + @service_owner_options = current_user.organization.users.active.order('email') end - if @service - @service_owner_options = @service_owner_options - @service.service_managers - end + @service_owner_options -= @service.service_managers if @service end def service_params @@ -253,4 +243,5 @@ def service_params :where_customers_interact, ) end + end end diff --git a/app/controllers/admin/site_controller.rb b/app/controllers/admin/site_controller.rb index 93fc7eb78..3afdb503a 100644 --- a/app/controllers/admin/site_controller.rb +++ b/app/controllers/admin/site_controller.rb @@ -1,57 +1,59 @@ -class Admin::SiteController < AdminController - def index - @forms = Form.non_templates - @agencies = Organization.all.order(:name) - - @days_since = params[:recent] && params[:recent].to_i <= 365 ? params[:recent].to_i : 3 - @dates = (@days_since.days.ago.to_date..Date.today).map{ |date| date } - - @response_groups = Submission.group("date(created_at)").count.sort.last(@days_since.days) - @user_groups = User.group("date(created_at)").count.sort.last(@days_since.days) - @inactive_user_groups = User.where(inactive: true).group("date(updated_at)").count.sort.last(@days_since.days) - todays_submissions = Submission.where("created_at > ?", Time.now - @days_since.days) - - # Add in 0 count days to fetched analytics - @dates.each do | date | - @user_groups << [date, 0] unless @user_groups.detect{ | row | row[0].strftime("%m %d %Y") == date.strftime("%m %d %Y")} - @inactive_user_groups << [date, 0] unless @inactive_user_groups.detect{ | row | row[0].strftime("%m %d %Y") == date.strftime("%m %d %Y")} - @response_groups << [date, 0] unless @response_groups.detect{ | row | row[0].strftime("%m %d %Y") == date.strftime("%m %d %Y")} +# frozen_string_literal: true + +module Admin + class SiteController < AdminController + def index + @forms = Form.non_templates + @agencies = Organization.all.order(:name) + + @days_since = params[:recent] && params[:recent].to_i <= 365 ? params[:recent].to_i : 3 + @dates = (@days_since.days.ago.to_date..Date.today).map { |date| date } + + @response_groups = Submission.group('date(created_at)').count.sort.last(@days_since.days) + @user_groups = User.group('date(created_at)').count.sort.last(@days_since.days) + @inactive_user_groups = User.where(inactive: true).group('date(updated_at)').count.sort.last(@days_since.days) + todays_submissions = Submission.where('created_at > ?', Time.zone.now - @days_since.days) + + # Add in 0 count days to fetched analytics + @dates.each do |date| + @user_groups << [date, 0] unless @user_groups.detect { |row| row[0].strftime('%m %d %Y') == date.strftime('%m %d %Y') } + @inactive_user_groups << [date, 0] unless @inactive_user_groups.detect { |row| row[0].strftime('%m %d %Y') == date.strftime('%m %d %Y') } + @response_groups << [date, 0] unless @response_groups.detect { |row| row[0].strftime('%m %d %Y') == date.strftime('%m %d %Y') } + end + @user_groups = @user_groups.sort + @inactive_user_groups = @inactive_user_groups.sort + @response_groups = @response_groups.sort + + form_ids = todays_submissions.collect(&:form_id).uniq + @recent_forms = Form.find(form_ids) end - @user_groups = @user_groups.sort - @inactive_user_groups = @inactive_user_groups.sort - @response_groups = @response_groups.sort - form_ids = todays_submissions.collect(&:form_id).uniq - @recent_forms = Form.find(form_ids) - end - - def events - @events = Event.limit(500).order("created_at DESC").page params[:page] - end + def events + @events = Event.limit(500).order('created_at DESC').page params[:page] + end - def a11 - end + def a11; end - def heartbeat - render json: { - status: :success, - last_request_at: user_session["last_request_at"].presence || 0 - } - end + def heartbeat + render json: { + status: :success, + last_request_at: user_session['last_request_at'].presence || 0, + } + end - def events_export - ExportEventsJob.perform_later(params[:uuid]) - render json: { result: :ok } - end + def events_export + ExportEventsJob.perform_later(params[:uuid]) + render json: { result: :ok } + end - def management - ensure_admin - @organizations = Organization.all.order(:name) - @forms = Form.non_templates - @unmanaged_forms = @forms.order(:name) - @agencies = Organization.all.order(:name) - end + def management + ensure_admin + @organizations = Organization.all.order(:name) + @forms = Form.non_templates + @unmanaged_forms = @forms.order(:name) + @agencies = Organization.all.order(:name) + end - def registry + def registry; end end end diff --git a/app/controllers/admin/submissions_controller.rb b/app/controllers/admin/submissions_controller.rb index 0d352d4cb..0dc0da3b1 100644 --- a/app/controllers/admin/submissions_controller.rb +++ b/app/controllers/admin/submissions_controller.rb @@ -1,183 +1,180 @@ -class Admin::SubmissionsController < AdminController - before_action :ensure_admin, only: [:feed, :export_feed] - before_action :set_form, except: [:feed, :export_feed] - before_action :set_submission, except: [:feed, :export_feed, :search, :a11_chart, :a11_analysis, :responses_per_day, :responses_by_status, :performance_gov, :submissions_table] - - def show - end - - def update - respond_to do |format| - if @submission.update(status_params) - Event.log_event(Event.names[:response_status_changed], "Submission", @submission.id, "Submission #{@submission.id} changed status to #{status_params[:aasm_state]} at #{DateTime.now}", current_user.id) +# frozen_string_literal: true + +module Admin + class SubmissionsController < AdminController + before_action :ensure_admin, only: %i[feed export_feed] + before_action :set_form, except: %i[feed export_feed] + before_action :set_submission, except: %i[feed export_feed search a11_chart a11_analysis responses_per_day responses_by_status performance_gov submissions_table] + + def show; end + + def update + respond_to do |format| + if @submission.update(status_params) + Event.log_event(Event.names[:response_status_changed], 'Submission', @submission.id, "Submission #{@submission.id} changed status to #{status_params[:aasm_state]} at #{DateTime.now}", current_user.id) + + format.html do + redirect_to admin_form_submission_path(@form, @submission), notice: 'Response was successfully updated.' + end + format.json { render :show, status: :ok, location: @form } + else + format.html do + redirect_to admin_form_submission_path(@form, @submission), alert: 'Response could not be updated.' + end + format.json { render json: @form.errors, status: :unprocessable_entity } + end + end + end - format.html { - redirect_to admin_form_submission_path(@form, @submission), notice: 'Response was successfully updated.' - } - format.json { render :show, status: :ok, location: @form } + def search + @all_submissions = @form.submissions + @all_submissions = @all_submissions.tagged_with(params[:tag]) if params[:tag] + if params[:archived] + @submissions = @all_submissions.order('submissions.created_at DESC').page params[:page] else - format.html { - redirect_to admin_form_submission_path(@form, @submission), alert: 'Response could not be updated.' - } - format.json { render json: @form.errors, status: :unprocessable_entity } + @submissions = @all_submissions.non_archived.order('submissions.created_at DESC').page params[:page] end end - end - def search - @all_submissions = @form.submissions - if params[:tag] - @all_submissions = @all_submissions.tagged_with(params[:tag]) + def flag + Event.log_event(Event.names[:response_flagged], 'Submission', @submission.id, "Submission #{@submission.id} flagged at #{DateTime.now}", current_user.id) + @submission.update(flagged: true) end - if params[:archived] - @submissions = @all_submissions.order("submissions.created_at DESC").page params[:page] - else - @submissions = @all_submissions.non_archived.order("submissions.created_at DESC").page params[:page] - end - end - - def flag - Event.log_event(Event.names[:response_flagged], "Submission", @submission.id, "Submission #{@submission.id} flagged at #{DateTime.now}", current_user.id) - @submission.update(flagged: true) - end - def unflag - Event.log_event(Event.names[:response_unflagged], "Submission", @submission.id, "Submission #{@submission.id} unflagged at #{DateTime.now}", current_user.id) - @submission.update(flagged: false) - end + def unflag + Event.log_event(Event.names[:response_unflagged], 'Submission', @submission.id, "Submission #{@submission.id} unflagged at #{DateTime.now}", current_user.id) + @submission.update(flagged: false) + end - def add_tag - @submission.tag_list.add(admin_submission_params[:tag_list].split(',')) - @submission.save! - end + def add_tag + @submission.tag_list.add(admin_submission_params[:tag_list].split(',')) + @submission.save! + end - def remove_tag - @submission.tag_list.remove(admin_submission_params[:tag_list].split(',')) - @submission.save! - end + def remove_tag + @submission.tag_list.remove(admin_submission_params[:tag_list].split(',')) + @submission.save! + end - def a11_analysis - @report = FormCache.fetch_a11_analysis(@form.short_uuid) - end + def a11_analysis + @report = FormCache.fetch_a11_analysis(@form.short_uuid) + end - def a11_chart - @report = FormCache.fetch_a11_analysis(@form.short_uuid) - end + def a11_chart + @report = FormCache.fetch_a11_analysis(@form.short_uuid) + end - def responses_per_day - @dates = (45.days.ago.to_date..Date.today).map{ |date| date } - @response_groups = @form.submissions.group("date(created_at)").size.sort.last(45) - # Add in 0 count days to fetched analytics - @dates.each do | date | - @response_groups << [date, 0] unless @response_groups.detect{ | row | row[0].strftime("%m %d %Y") == date.strftime("%m %d %Y")} + def responses_per_day + @dates = (45.days.ago.to_date..Date.today).map { |date| date } + @response_groups = @form.submissions.group('date(created_at)').size.sort.last(45) + # Add in 0 count days to fetched analytics + @dates.each do |date| + @response_groups << [date, 0] unless @response_groups.detect { |row| row[0].strftime('%m %d %Y') == date.strftime('%m %d %Y') } + end + @response_groups = @response_groups.sort end - @response_groups = @response_groups.sort - end - def responses_by_status - end + def responses_by_status; end - def performance_gov - @report = FormCache.fetch_performance_gov_analysis(@form.short_uuid) - end - - def submissions_table - @show_archived = true if params[:archived] - @all_submissions = @form.submissions - if params[:tag] - @all_submissions = @all_submissions.tagged_with(params[:tag]) + def performance_gov + @report = FormCache.fetch_performance_gov_analysis(@form.short_uuid) end - if params[:archived] - @submissions = @all_submissions.order("submissions.created_at DESC").page params[:page] - else - @submissions = @all_submissions.non_archived.order("submissions.created_at DESC").page params[:page] + + def submissions_table + @show_archived = true if params[:archived] + @all_submissions = @form.submissions + @all_submissions = @all_submissions.tagged_with(params[:tag]) if params[:tag] + if params[:archived] + @submissions = @all_submissions.order('submissions.created_at DESC').page params[:page] + else + @submissions = @all_submissions.non_archived.order('submissions.created_at DESC').page params[:page] + end end - end - def archive - ensure_form_manager(form: @form) + def archive + ensure_form_manager(form: @form) - Event.log_event(Event.names[:response_archived], "Submission", @submission.id, "Submission #{@submission.id} archived at #{DateTime.now}", current_user.id) - @submission.update(archived: true) - end + Event.log_event(Event.names[:response_archived], 'Submission', @submission.id, "Submission #{@submission.id} archived at #{DateTime.now}", current_user.id) + @submission.update(archived: true) + end - def unarchive - ensure_form_manager(form: @form) + def unarchive + ensure_form_manager(form: @form) - Event.log_event(Event.names[:response_unarchived], "Submission", @submission.id, "Submission #{@submission.id} unarchived at #{DateTime.now}", current_user.id) - @submission.update(archived: false) - end + Event.log_event(Event.names[:response_unarchived], 'Submission', @submission.id, "Submission #{@submission.id} unarchived at #{DateTime.now}", current_user.id) + @submission.update(archived: false) + end - def destroy - ensure_form_manager(form: @form) + def destroy + ensure_form_manager(form: @form) - Event.log_event(Event.names[:response_deleted], "Submission", @submission.id, "Submission #{@submission.id} deleted at #{DateTime.now}", current_user.id) + Event.log_event(Event.names[:response_deleted], 'Submission', @submission.id, "Submission #{@submission.id} deleted at #{DateTime.now}", current_user.id) - @submission.destroy - respond_to do |format| - format.js { render :destroy } + @submission.destroy + respond_to do |format| + format.js { render :destroy } + end end - end - - def feed - @days_limit = (params[:days_limit].present? ? params[:days_limit].to_i : 1) - @feed = get_feed_data(@days_limit) - end - def export_feed - @days_limit = (params[:days_limit].present? ? params[:days_limit].to_i : 1) - @feed = get_feed_data(@days_limit) - respond_to do |format| - format.csv { - send_data to_csv(@feed), :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=touchpoints-feed-#{Date.today}.csv" - } - format.json { - render json: @feed.to_json - } + def feed + @days_limit = (params[:days_limit].present? ? params[:days_limit].to_i : 1) + @feed = get_feed_data(@days_limit) end - end - def to_csv(hash_rows) - CSV.generate(headers: true) do |csv| - csv << hash_rows.first.keys - hash_rows.each do | hash_row | - csv << hash_row.values + def export_feed + @days_limit = (params[:days_limit].present? ? params[:days_limit].to_i : 1) + @feed = get_feed_data(@days_limit) + respond_to do |format| + format.csv do + send_data to_csv(@feed), type: 'text/csv; charset=utf-8; header=present', disposition: "attachment; filename=touchpoints-feed-#{Date.today}.csv" + end + format.json do + render json: @feed.to_json + end end end - end - def get_feed_data(days_limit) - all_question_responses = [] - - Form.all.each do |form| - submissions = form.submissions - submissions = submissions.where("created_at >= ?",days_limit.days.ago) if days_limit > 0 - submissions.each do |submission| - form.questions.each do |question| - question_text = question.text.to_s - answer_text = Logstop.scrub(submission.send(question.answer_field.to_sym).to_s) - @hash = { - organization_id: form.organization_id, - organization_name: form.organization.name, - form_id: form.id, - form_name: form.name, - submission_id: submission.id, - question_id: question.id, - user_id: submission.user_id, - question_text: question_text, - response_text: answer_text, - question_with_response_text: question_text + ': ' + answer_text, - created_at: submission.created_at - } - all_question_responses << @hash + def to_csv(hash_rows) + CSV.generate(headers: true) do |csv| + csv << hash_rows.first.keys + hash_rows.each do |hash_row| + csv << hash_row.values end end end - all_question_responses - end + def get_feed_data(days_limit) + all_question_responses = [] + + Form.all.each do |form| + submissions = form.submissions + submissions = submissions.where('created_at >= ?', days_limit.days.ago) if days_limit.positive? + submissions.each do |submission| + form.questions.each do |question| + question_text = question.text.to_s + answer_text = Logstop.scrub(submission.send(question.answer_field.to_sym).to_s) + @hash = { + organization_id: form.organization_id, + organization_name: form.organization.name, + form_id: form.id, + form_name: form.name, + submission_id: submission.id, + question_id: question.id, + user_id: submission.user_id, + question_text:, + response_text: answer_text, + question_with_response_text: "#{question_text}: #{answer_text}", + created_at: submission.created_at, + } + all_question_responses << @hash + end + end + end + + all_question_responses + end - private + private def set_form if admin_permissions? @@ -193,9 +190,11 @@ def set_submission end def status_params - params.require(:submission).permit(:aasm_state) + params.require(:submission).permit(:aasm_state) end + def admin_submission_params params.require(:submission).permit(:tag_list) end + end end diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index 239751ae7..a7892e885 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -1,129 +1,133 @@ -class Admin::UsersController < AdminController - before_action :ensure_admin, except: [:deactivate] - before_action :set_user, only: [:show, :edit, :update, :destroy] - - def index - if current_user.admin? && params[:scope] == :all - @users = User.all.includes(:organization).order("inactive DESC", :organization_id, :email) - elsif current_user.admin? && params[:scope] == :inactive - @users = User.all.includes(:organization).where("current_sign_in_at < ? OR current_sign_in_at ISNULL", Time.now - 90.days).order(:organization_id, :email) - elsif current_user.admin? - @users = User.active.includes(:organization).order("inactive DESC", :organization_id, :email) - else - organization = current_user.organization - @users = organization.users.active.includes(:organization).order(:organization_id, :email) +# frozen_string_literal: true + +module Admin + class UsersController < AdminController + before_action :ensure_admin, except: [:deactivate] + before_action :set_user, only: %i[show edit update destroy] + + def index + if current_user.admin? && params[:scope] == :all + @users = User.all.includes(:organization).order('inactive DESC', :organization_id, :email) + elsif current_user.admin? && params[:scope] == :inactive + @users = User.all.includes(:organization).where('last_sign_in_at < ? OR last_sign_in_at ISNULL', 90.days.ago).order(:organization_id, :email) + elsif current_user.admin? + @users = User.active.includes(:organization).order('inactive DESC', :organization_id, :email) + else + organization = current_user.organization + @users = organization.users.active.includes(:organization).order(:organization_id, :email) + end + + respond_to do |format| + format.csv { send_data @users.to_csv, filename: "users-#{Date.today}.csv" } + format.html { render :index } + end end - respond_to do |format| - format.csv { send_data @users.to_csv, filename: "users-#{Date.today}.csv" } - format.html { render :index } + def admins + @users = User.all + @admins = @users.select(&:admin?) + @service_managers = @users.select(&:service_manager?) + @performance_managers = @users.select(&:performance_manager?) + @registry_managers = @users.select(&:registry_manager?) + @website_managers = @users.select(&:organizational_website_manager?) end - end - def admins - @users = User.all - @admins = @users.select { |u| u.admin? } - @service_managers = @users.select { |u| u.service_manager? } - @performance_managers = @users.select { |u| u.performance_manager? } - @registry_managers = @users.select { |u| u.registry_manager? } - @website_managers = @users.select { |u| u.organizational_website_manager? } - end + def inactivate! + User.deactivate_inactive_accounts! + redirect_to admin_users_path, notice: 'Users inactivated successfully.' + end - def inactivate! - User.deactivate_inactive_accounts! - redirect_to admin_users_path, notice: 'Users inactivated successfully.' - end + def show + @forms = @user.forms + @websites = Website.where(site_owner_email: @user.email) + @collections = @user.collections.order(:year, :quarter) + @user_events = Event.limit(100).where(user_id: @user.id).order('created_at DESC') + @digital_products = DigitalProduct.with_role(:contact, @user) + @digital_service_accounts = DigitalServiceAccount.with_role(:contact, @user) + end - def show - @forms = @user.forms - @websites = Website.where(site_owner_email: @user.email) - @collections = @user.collections.order(:year, :quarter) - @user_events = Event.limit(100).where(user_id: @user.id).order("created_at DESC") - @digital_products = DigitalProduct.with_role(:contact, @user) - @digital_service_accounts = DigitalServiceAccount.with_role(:contact, @user) - end + def new + @user = User.new + end - def new - @user = User.new - end + def edit; end - def edit - end + def create + @user = User.new(user_params) - def create - @user = User.new(user_params) + respond_to do |format| + if @user.save + format.html { redirect_to admin_user_path(@user), notice: 'User was successfully created.' } + format.json { render :show, status: :created, location: @user } + else + format.html { render :new } + format.json { render json: @user.errors, status: :unprocessable_entity } + end + end + end - respond_to do |format| - if @user.save - format.html { redirect_to admin_user_path(@user), notice: 'User was successfully created.' } - format.json { render :show, status: :created, location: @user } - else - format.html { render :new } - format.json { render json: @user.errors, status: :unprocessable_entity } + def update + respond_to do |format| + if @user.update(user_params) + Event.log_event(Event.names[:user_update], 'User', @user.id, "User #{@user.email} was updated by #{current_user.email} on #{Date.today}") + format.html { redirect_to admin_user_path(@user), notice: 'User was successfully updated.' } + format.json { render :show, status: :ok, location: @user } + else + format.html { render :edit } + format.json { render json: @user.errors, status: :unprocessable_entity } + end end end - end - def update - respond_to do |format| - if @user.update(user_params) - Event.log_event(Event.names[:user_update], "User", @user.id, "User #{@user.email} was updated by #{current_user.email} on #{Date.today}") - format.html { redirect_to admin_user_path(@user), notice: 'User was successfully updated.' } - format.json { render :show, status: :ok, location: @user } - else - format.html { render :edit } - format.json { render json: @user.errors, status: :unprocessable_entity } + def destroy + ensure_admin + redirect_to(edit_admin_user_path(@user), alert: "Can't delete yourself") and return if @user == current_user + + @user.destroy + Event.log_event(Event.names[:user_deleted], 'User', @user.id, "User #{@user.email} was deleted by #{current_user.email} on #{Date.today}") + respond_to do |format| + format.html { redirect_to admin_users_url, notice: 'User was successfully destroyed.' } + format.json { head :no_content } end end - end - def destroy - ensure_admin - redirect_to(edit_admin_user_path(@user), alert: "Can't delete yourself") and return if @user == current_user + def deactivate + uuid = get_uuid_from_request + render json: { errors: 'Request must come from valid login.gov source', status: 403 } and return unless uuid - @user.destroy - Event.log_event(Event.names[:user_deleted], "User", @user.id, "User #{@user.email} was deleted by #{current_user.email} on #{Date.today}") - respond_to do |format| - format.html { redirect_to admin_users_url, notice: 'User was successfully destroyed.' } - format.json { head :no_content } + user = User.where(uid: uuid).first + # Do we care if the user account deleted from login.gov was not found in touchpoints? + user&.deactivate! + Event.log_event(Event.names[:user_deactivated], 'User', user.id, "User #{user.email} was deactivated on #{Date.today}") + render json: { msg: 'User successfully deactivated.' } end - end - def deactivate - uuid = get_uuid_from_request - render json: { "errors": "Request must come from valid login.gov source", "status": 403} and return if !uuid - user = User.where(uid: uuid).first - # Do we care if the user account deleted from login.gov was not found in touchpoints? - user.deactivate! if user - Event.log_event(Event.names[:user_deactivated], "User", user.id, "User #{user.email} was deactivated on #{Date.today}") - render json: { "msg": "User successfully deactivated." } - end + private - private def get_uuid_from_request - return nil if !request.headers["HTTP_AUTHORIZATION"].present? + return nil if request.headers['HTTP_AUTHORIZATION'].blank? + begin - decoded = JWT.decode http_token, login_gov_public_key, true, { algorithm: "RS256" } + decoded = JWT.decode http_token, login_gov_public_key, true, { algorithm: 'RS256' } payload = decoded.first - uuid = payload["events"]["https://schemas.openid.net/secevent/risc/event-type/account-purged"]["subject"]["sub"] - rescue + uuid = payload['events']['https://schemas.openid.net/secevent/risc/event-type/account-purged']['subject']['sub'] + rescue StandardError nil end end def login_gov_public_key - return OpenSSL::PKey::RSA.new(ENV["LOGIN_GOV_PUBLIC_KEY"]) if ENV["LOGIN_GOV_PUBLIC_KEY"].present? - jwks_raw = Net::HTTP.get URI(ENV["LOGIN_GOV_OPENID_CERT_URL"]) - jwks_key = JSON.parse(jwks_raw)["keys"].first - jwks_key["alg": "RS256"] + return OpenSSL::PKey::RSA.new(ENV['LOGIN_GOV_PUBLIC_KEY']) if ENV['LOGIN_GOV_PUBLIC_KEY'].present? + + jwks_raw = Net::HTTP.get URI(ENV.fetch('LOGIN_GOV_OPENID_CERT_URL', nil)) + jwks_key = JSON.parse(jwks_raw)['keys'].first + jwks_key[alg: 'RS256'] jwk = JSON::JWK.new(jwks_key) public_key = jwk.to_key end def http_token - if request.headers['HTTP_AUTHORIZATION'].present? - request.headers['HTTP_AUTHORIZATION'].split(' ').last - end + request.headers['HTTP_AUTHORIZATION'].split.last if request.headers['HTTP_AUTHORIZATION'].present? end def set_user @@ -146,4 +150,5 @@ def user_params :inactive, ) end + end end diff --git a/app/controllers/admin/websites_controller.rb b/app/controllers/admin/websites_controller.rb index 081774449..5a70c5f70 100644 --- a/app/controllers/admin/websites_controller.rb +++ b/app/controllers/admin/websites_controller.rb @@ -1,318 +1,311 @@ -class Admin::WebsitesController < AdminController - before_action :ensure_organizational_website_manager, only: [ - :collection_preview, - :collection_request, - :export_versions - ] - before_action :set_paper_trail_whodunnit - - before_action :set_website, only: [ - :show, :costs, :statuscard, :edit, :update, :destroy, :collection_request, - :approve, - :deny, - :events, - :dendrogram, - :add_tag, - :remove_tag, - :versions, - :export_versions, - :add_website_manager, - :remove_website_manager, - :add_website_persona, - :remove_website_persona, - ] - - before_action :set_website_manager_options, only: [ - :new, - :create, - :edit, - :update, - :add_website_manager, - :remove_website_manager, - ] - - before_action :set_website_persona_options, only: [ - :new, - :create, - :edit, - :update, - ] - - def index - if params[:all] - @websites = Website.all.order(:production_status, :domain) - else - @websites = Website.active.order(:production_status, :domain) +# frozen_string_literal: true + +module Admin + class WebsitesController < AdminController + before_action :ensure_organizational_website_manager, only: %i[ + collection_preview + collection_request + export_versions + ] + before_action :set_paper_trail_whodunnit + + before_action :set_website, only: %i[ + show costs statuscard edit update destroy collection_request + approve + deny + events + dendrogram + add_tag + remove_tag + versions + export_versions + add_website_manager + remove_website_manager + add_website_persona + remove_website_persona + ] + + before_action :set_website_manager_options, only: %i[ + new + create + edit + update + add_website_manager + remove_website_manager + ] + + before_action :set_website_persona_options, only: %i[ + new + create + edit + update + ] + + def index + if params[:all] + @websites = Website.all.order(:production_status, :domain) + else + @websites = Website.active.order(:production_status, :domain) + end + @tags = Website.tag_counts_by_name end - @tags = Website.tag_counts_by_name - end - def review - @websites = Website.where(production_status: "newly_requested").order(:production_status, :domain) - @tags = Website.tag_counts_by_name - end + def review + @websites = Website.where(production_status: 'newly_requested').order(:production_status, :domain) + @tags = Website.tag_counts_by_name + end - def versions - @versions = @website.versions.limit(500).order("created_at DESC").page params[:page] - end + def versions + @versions = @website.versions.limit(500).order('created_at DESC').page params[:page] + end - def export_versions - ensure_admin - ExportVersionsJob.perform_later(params[:uuid], @website, 'touchpoints-website-versions.csv') - render json: { result: :ok } - end + def export_versions + ensure_admin + ExportVersionsJob.perform_later(params[:uuid], @website, 'touchpoints-website-versions.csv') + render json: { result: :ok } + end - def dendrogram - end + def dendrogram; end - def dendrogram_json + def dendrogram_json + if params['office'] == 'true' + dendrogram_json_by_office + else + # default + dendrogram_json_by_domain + end - if params["office"] == "true" - dendrogram_json_by_office - else - # default - dendrogram_json_by_domain + respond_to do |format| + format.json do + render 'dendrogram_json' + end + end end - respond_to do |format| - format.json { - render "dendrogram_json" - } - end - end + def dendrogram_json_by_domain + @websites = [] - def dendrogram_json_by_domain - @websites = [] + # loop all sites and build a list of top-level domains + @active_websites = Website.active + @active_websites.each do |website| + next unless website.tld? - # loop all sites and build a list of top-level domains - @active_websites = Website.active - @active_websites.each do |website| - if website.tld? @websites << { name: website.domain, - children: [ - ] + children: [], } end - end - @active_websites.each do |website| - selected_website = @websites.select { |w| w[:name] == website[:domain] || w[:name] == website[:parent_domain] }.first - next unless selected_website.present? + @active_websites.each do |website| + selected_website = @websites.select { |w| w[:name] == website[:domain] || w[:name] == website[:parent_domain] }.first + next if selected_website.blank? + + next if website.tld? - if !website.tld? selected_website[:children] << { - name: website.domain || "N/A", - value: 1 + name: website.domain || 'N/A', + value: 1, } end + @websites end - return @websites - end - def dendrogram_json_by_office - @websites = [] + def dendrogram_json_by_office + @websites = [] - # loop all sites and build a list of top-level domains - @active_websites = Website.active - @active_websites.collect(&:office).uniq.each do |office| - @websites << { - name: office, - office: office, - children: [] - } - end + # loop all sites and build a list of top-level domains + @active_websites = Website.active + @active_websites.collect(&:office).uniq.each do |office| + @websites << { + name: office, + office:, + children: [], + } + end - @active_websites.each do |website| - selected_website = @websites.select { |w| w[:office] == website[:office] || w[:sub_office] == website[:sub_office] }.first - next unless selected_website.present? + @active_websites.each do |website| + selected_website = @websites.select { |w| w[:office] == website[:office] || w[:sub_office] == website[:sub_office] }.first + next if selected_website.blank? - selected_website[:children] << { - name: website.domain || "N/A", - value: 1 - } + selected_website[:children] << { + name: website.domain || 'N/A', + value: 1, + } + end + @websites end - return @websites - end - - def export_csv - @websites = Website.all - send_data @websites.to_csv, filename: "touchpoints-websites-#{Date.today}.csv" - end - def statuscard - end + def export_csv + @websites = Website.all + send_data @websites.to_csv, filename: "touchpoints-websites-#{Date.today}.csv" + end - def search - search_text = params[:search] - tag_name = params[:tag] - if search_text.present? - search_text = '%' + search_text + '%' - managed_sites = Website.where(id: Website.ids_by_manager_search(search_text)) - @websites = Website.where(' domain ilike ? or office ilike ? or sub_office ilike ? or production_status ilike ? or site_owner_email ilike ? ', search_text, search_text, search_text, search_text, search_text).or(managed_sites).order( - :production_status, :domain - ) - elsif tag_name.present? - @websites = Website.tagged_with(tag_name).order(:production_status, :domain) - else - @websites = Website.all.order(:production_status, :domain) + def statuscard; end + + def search + search_text = params[:search] + tag_name = params[:tag] + if search_text.present? + search_text = "%#{search_text}%" + managed_sites = Website.where(id: Website.ids_by_manager_search(search_text)) + @websites = Website.where(' domain ilike ? or office ilike ? or sub_office ilike ? or production_status ilike ? or site_owner_email ilike ? ', search_text, search_text, search_text, search_text, search_text).or(managed_sites).order( + :production_status, :domain + ) + elsif tag_name.present? + @websites = Website.tagged_with(tag_name).order(:production_status, :domain) + else + @websites = Website.all.order(:production_status, :domain) + end end - end - def gsa - @websites = Website.active.order(:production_status, :domain) - end + def gsa + @websites = Website.active.order(:production_status, :domain) + end - def show - end + def show; end - def collection_preview - ensure_admin - @websites = Website.active.order(:site_owner_email, :domain) - end + def collection_preview + ensure_admin + @websites = Website.active.order(:site_owner_email, :domain) + end - def collection_request - # fetch all websites for site owner - @websites = Website.active.where(site_owner_email: @website.site_owner_email) - # only include websites which are missing data - @websites = @websites.select { | ws | ws.requiresDataCollection? } - UserMailer.website_data_collection(@website.site_owner_email, @websites).deliver_later if @website.site_owner_email.present? - UserMailer.website_data_collection(current_user.email, @websites).deliver_later - redirect_to admin_websites_url, notice: "Website data collection request was successfully sent for #{@website.domain}" - end + def collection_request + # fetch all websites for site owner + @websites = Website.active.where(site_owner_email: @website.site_owner_email) + # only include websites which are missing data + @websites = @websites.select(&:requiresDataCollection?) + UserMailer.website_data_collection(@website.site_owner_email, @websites).deliver_later if @website.site_owner_email.present? + UserMailer.website_data_collection(current_user.email, @websites).deliver_later + redirect_to admin_websites_url, notice: "Website data collection request was successfully sent for #{@website.domain}" + end - def new - @website = Website.new - @website.site_owner_email = current_user.email - @website.contact_email = current_user.email - end + def new + @website = Website.new + @website.site_owner_email = current_user.email + @website.contact_email = current_user.email + end - def edit - ensure_website_admin(website: @website, user: current_user) - end + def edit + ensure_website_admin(website: @website, user: current_user) + end - def costs - ensure_website_admin(website: @website, user: current_user) - end + def costs + ensure_website_admin(website: @website, user: current_user) + end - def create - @website = Website.new(admin_website_params) + def create + @website = Website.new(admin_website_params) - if @website.save - Event.log_event(Event.names[:website_created], "Website", @website.id, "Website #{@website.domain} created at #{DateTime.now}", current_user.id) - UserMailer.website_created(website: @website).deliver_later - redirect_to admin_website_url(@website), notice: 'Website was successfully created.' - else - render :new + if @website.save + Event.log_event(Event.names[:website_created], 'Website', @website.id, "Website #{@website.domain} created at #{DateTime.now}", current_user.id) + UserMailer.website_created(website: @website).deliver_later + redirect_to admin_website_url(@website), notice: 'Website was successfully created.' + else + render :new + end end - end - def update - ensure_website_admin(website: @website, user: current_user) - current_state = @website.production_status - if @website.update(admin_website_params) - log_update(current_state) - redirect_to admin_website_url(@website), notice: 'Website was successfully updated.' - else - render :edit + def update + ensure_website_admin(website: @website, user: current_user) + current_state = @website.production_status + if @website.update(admin_website_params) + log_update(current_state) + redirect_to admin_website_url(@website), notice: 'Website was successfully updated.' + else + render :edit + end end - end - def approve - ensure_website_admin(website: @website, user: current_user) - @website.approve - if @website.save - Event.log_event(Event.names[:website_approved], "Website", @website.id, "Website #{@website.domain} approved at #{DateTime.now}", current_user.id) - redirect_to admin_website_url(@website), notice: "Website #{@website.domain} was approved." - else - render :edit + def approve + ensure_website_admin(website: @website, user: current_user) + @website.approve + if @website.save + Event.log_event(Event.names[:website_approved], 'Website', @website.id, "Website #{@website.domain} approved at #{DateTime.now}", current_user.id) + redirect_to admin_website_url(@website), notice: "Website #{@website.domain} was approved." + else + render :edit + end end - end - def deny - ensure_website_admin(website: @website, user: current_user) - @website.deny - if @website.save - Event.log_event(Event.names[:website_denied], "Website", @website.id, "Website #{@website.domain} denied at #{DateTime.now}", current_user.id) - redirect_to admin_website_url(@website), notice: "Website #{@website.domain} was denied." - else - render :edit + def deny + ensure_website_admin(website: @website, user: current_user) + @website.deny + if @website.save + Event.log_event(Event.names[:website_denied], 'Website', @website.id, "Website #{@website.domain} denied at #{DateTime.now}", current_user.id) + redirect_to admin_website_url(@website), notice: "Website #{@website.domain} was denied." + else + render :edit + end end - end - def destroy - ensure_admin + def destroy + ensure_admin - @website.destroy - Event.log_event(Event.names[:website_deleted], "Website", @website.id, "Website #{@website.domain} deleted at #{DateTime.now}", current_user.id) - redirect_to admin_websites_url, notice: 'Website was successfully destroyed.' - end + @website.destroy + Event.log_event(Event.names[:website_deleted], 'Website', @website.id, "Website #{@website.domain} deleted at #{DateTime.now}", current_user.id) + redirect_to admin_websites_url, notice: 'Website was successfully destroyed.' + end - def events - @events = Event.where(object_type: "Website", object_id: @website.id).order(:created_at) - end + def events + @events = Event.where(object_type: 'Website', object_id: @website.id).order(:created_at) + end - def add_tag - @website.tag_list.add(admin_website_params[:tag_list].split(',')) - @website.save - end + def add_tag + @website.tag_list.add(admin_website_params[:tag_list].split(',')) + @website.save + end - def remove_tag - @website.tag_list.remove(admin_website_params[:tag_list].split(',')) - @website.save - end + def remove_tag + @website.tag_list.remove(admin_website_params[:tag_list].split(',')) + @website.save + end - def add_website_manager - @manager = User.find(params[:user_id]) - @manager.add_role :website_manager, @website unless @manager.has_role?(:website_manager, @website) - end + def add_website_manager + @manager = User.find(params[:user_id]) + @manager.add_role :website_manager, @website unless @manager.has_role?(:website_manager, @website) + end - def remove_website_manager - @manager = User.find(params[:user_id]) - @manager.remove_role :website_manager, @website - end + def remove_website_manager + @manager = User.find(params[:user_id]) + @manager.remove_role :website_manager, @website + end - def add_website_persona - @website.persona_list.add(params[:persona_id]) - @website.save - set_website_persona_options - end + def add_website_persona + @website.persona_list.add(params[:persona_id]) + @website.save + set_website_persona_options + end - def remove_website_persona - @website.persona_list.remove(params[:persona_id]) - @website.save - set_website_persona_options - end + def remove_website_persona + @website.persona_list.remove(params[:persona_id]) + @website.save + set_website_persona_options + end + + private - private def set_website_manager_options if admin_permissions? - @website_manager_options = User.active.order("email") - elsif @website && @website.organization - @website_manager_options = @website.organization.users.active.order("email") + @website_manager_options = User.active.order('email') + elsif @website&.organization + @website_manager_options = @website.organization.users.active.order('email') elsif current_user.organization - @website_manager_options = current_user.organization.users.active.order("email") + @website_manager_options = current_user.organization.users.active.order('email') else [] end - if @website_manager_options && @website - @website_manager_options = @website_manager_options - @website.website_managers - end + @website_manager_options -= @website.website_managers if @website_manager_options && @website end def set_website_persona_options @website_persona_options = Persona.all.order(:name) - if @website_persona_options && @website - @website_persona_options = @website_persona_options - @website.website_personas - end + @website_persona_options -= @website.website_personas if @website_persona_options && @website end def log_update(current_state) - Event.log_event(Event.names[:website_updated], "Website", @website.id, "Website #{@website.domain} updated at #{DateTime.now}", current_user.id) - if admin_website_params[:production_status] != current_state - Event.log_event(Event.names[:website_state_changed], "Website", @website.id, "Website #{@website.domain} state changed to #{admin_website_params[:production_status]} at #{DateTime.now}", current_user.id) - end + Event.log_event(Event.names[:website_updated], 'Website', @website.id, "Website #{@website.domain} updated at #{DateTime.now}", current_user.id) + Event.log_event(Event.names[:website_state_changed], 'Website', @website.id, "Website #{@website.domain} state changed to #{admin_website_params[:production_status]} at #{DateTime.now}", current_user.id) if admin_website_params[:production_status] != current_state end def set_website @@ -321,19 +314,20 @@ def set_website def admin_website_params params.require(:website).permit(:domain, :office, :office_id, :sub_office, :suboffice_id, :contact_email, :site_owner_email, :production_status, :type_of_site, :digital_brand_category, :redirects_to, :status_code, :cms_platform, :required_by_law_or_policy, :has_dap, :dap_gtm_code, :cost_estimator_url, :modernization_plan_url, :annual_baseline_cost, - :modernization_cost, - :modernization_cost_2021, - :modernization_cost_2022, - :modernization_cost_2023, - :analytics_url, - :https, - :uswds_version, - :uses_feedback, :feedback_tool, :sitemap_url, :mobile_friendly, :has_search, :uses_tracking_cookies, - :hosting_platform, - :has_authenticated_experience, - :authentication_tool, - :repository_url, - :notes, - :tag_list) + :modernization_cost, + :modernization_cost_2021, + :modernization_cost_2022, + :modernization_cost_2023, + :analytics_url, + :https, + :uswds_version, + :uses_feedback, :feedback_tool, :sitemap_url, :mobile_friendly, :has_search, :uses_tracking_cookies, + :hosting_platform, + :has_authenticated_experience, + :authentication_tool, + :repository_url, + :notes, + :tag_list) end + end end diff --git a/app/controllers/admin_controller.rb b/app/controllers/admin_controller.rb index d542eb0e2..b0ea22469 100644 --- a/app/controllers/admin_controller.rb +++ b/app/controllers/admin_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class AdminController < ::ApplicationController include ApplicationHelper diff --git a/app/controllers/api/v0/forms_controller.rb b/app/controllers/api/v0/forms_controller.rb index 11032b06a..eab5d1c68 100644 --- a/app/controllers/api/v0/forms_controller.rb +++ b/app/controllers/api/v0/forms_controller.rb @@ -1,54 +1,59 @@ -class Api::V0::FormsController < ::ApiController - def index - respond_to do |format| - format.json { - render json: { forms: current_user.forms.limit(100) } - } - end - end +# frozen_string_literal: true - def show - form = current_user.forms.find_by_short_uuid(params[:id]) - page = (params[:page].present? ? params[:page].to_i : 0) - size = (params[:size].present? ? params[:size].to_i : 500) - size = 5000 if size > 5000 - # Date filter defaults to 1 year ago and 1 day from now - # Is there ever a case where we'd want to see submissions older than a year via the API? - begin - start_date = params[:start_date] ? Date.parse(params[:start_date]).to_date : 1.year.ago - end_date = params[:end_date] ? Date.parse(params[:end_date]).to_date : 1.day.from_now - rescue - render json: { error: { message: "invalid date format, should be 'YYYY-MM-DD'", status: 400 } }, status: 400 and return - end +module Api + module V0 + class FormsController < ::ApiController + def index + respond_to do |format| + format.json do + render json: { forms: current_user.forms.limit(100) } + end + end + end - respond_to do |format| - format.json { - if form - render json: { - form: form, - responses: form.submissions.where('created_at BETWEEN ? AND ?',start_date,end_date).limit(size).offset(size * page), - links: links(form, page, size) - } - else - render json: { error: { message: "no form with Short UUID of #{params[:id]}", status: 404 } }, status: 404 + def show + form = current_user.forms.find_by_short_uuid(params[:id]) + page = (params[:page].present? ? params[:page].to_i : 0) + size = (params[:size].present? ? params[:size].to_i : 500) + size = 5000 if size > 5000 + # Date filter defaults to 1 year ago and 1 day from now + # Is there ever a case where we'd want to see submissions older than a year via the API? + begin + start_date = params[:start_date] ? Date.parse(params[:start_date]).to_date : 1.year.ago + end_date = params[:end_date] ? Date.parse(params[:end_date]).to_date : 1.day.from_now + rescue StandardError + render json: { error: { message: "invalid date format, should be 'YYYY-MM-DD'", status: 400 } }, status: :bad_request and return end - } - end - end - def links(form, page, size) - ret = {} - if params[:page].present? - ret["first"] = request.original_url.gsub(/page=[0-9]+/i,"page=0") - ret["next"] = request.original_url.gsub(/page=[0-9]+/i,"page=" + (page + 1).to_s) if (form.submissions.size > ( (page + 1) * size)) - ret["prev"] = request.original_url.gsub(/page=[0-9]+/i,"page=" + (page - 1).to_s) if page > 0 - ret["last"] = request.original_url.gsub(/page=[0-9]+/i,"page=" + (form.submissions.size / size).floor.to_s) - else - ret["first"] = request.original_url + "&page=0" - ret["next"] = request.original_url + "&page=1" if form.submissions.size > size - ret["last"] = request.original_url + "&page=" + (form.submissions.size / size).floor.to_s + respond_to do |format| + format.json do + if form + render json: { + form:, + responses: form.submissions.where('created_at BETWEEN ? AND ?', start_date, end_date).limit(size).offset(size * page), + links: links(form, page, size), + } + else + render json: { error: { message: "no form with Short UUID of #{params[:id]}", status: 404 } }, status: :not_found + end + end + end + end + + def links(form, page, size) + ret = {} + if params[:page].present? + ret['first'] = request.original_url.gsub(/page=[0-9]+/i, 'page=0') + ret['next'] = request.original_url.gsub(/page=[0-9]+/i, "page=#{page + 1}") if form.submissions.size > ((page + 1) * size) + ret['prev'] = request.original_url.gsub(/page=[0-9]+/i, "page=#{page - 1}") if page.positive? + ret['last'] = request.original_url.gsub(/page=[0-9]+/i, "page=#{(form.submissions.size / size).floor}") + else + ret['first'] = "#{request.original_url}&page=0" + ret['next'] = "#{request.original_url}&page=1" if form.submissions.size > size + ret['last'] = "#{request.original_url}&page=#{(form.submissions.size / size).floor}" + end + ret + end end - ret end - end diff --git a/app/controllers/api/v1/collections_controller.rb b/app/controllers/api/v1/collections_controller.rb index 1a6988254..8431d6f35 100644 --- a/app/controllers/api/v1/collections_controller.rb +++ b/app/controllers/api/v1/collections_controller.rb @@ -1,9 +1,15 @@ -class Api::V1::CollectionsController < ::ApiController - def index - respond_to do |format| - format.json { - render json: Collection.all.order(:id), each_serializer: CollectionSerializer - } +# frozen_string_literal: true + +module Api + module V1 + class CollectionsController < ::ApiController + def index + respond_to do |format| + format.json do + render json: Collection.all.order(:id), each_serializer: CollectionSerializer + end + end + end end end end diff --git a/app/controllers/api/v1/digital_products_controller.rb b/app/controllers/api/v1/digital_products_controller.rb index ccfe3f5d4..f5af0d246 100644 --- a/app/controllers/api/v1/digital_products_controller.rb +++ b/app/controllers/api/v1/digital_products_controller.rb @@ -1,19 +1,25 @@ -class Api::V1::DigitalProductsController < ::UnauthenticatedApiController - def index - respond_to do |format| - format.json { - render json: DigitalProduct.all.order(:id), each_serializer: DigitalProductSerializer - } - end - end +# frozen_string_literal: true + +module Api + module V1 + class DigitalProductsController < ::UnauthenticatedApiController + def index + respond_to do |format| + format.json do + render json: DigitalProduct.all.order(:id), each_serializer: DigitalProductSerializer + end + end + end - def show - @digital_product = DigitalProduct.find(params[:id]) + def show + @digital_product = DigitalProduct.find(params[:id]) - respond_to do |format| - format.json { - render json: @digital_product, serializer: DigitalProductSerializer - } + respond_to do |format| + format.json do + render json: @digital_product, serializer: DigitalProductSerializer + end + end + end end end end diff --git a/app/controllers/api/v1/digital_service_accounts_controller.rb b/app/controllers/api/v1/digital_service_accounts_controller.rb index a5dc3476e..4dfb892ef 100644 --- a/app/controllers/api/v1/digital_service_accounts_controller.rb +++ b/app/controllers/api/v1/digital_service_accounts_controller.rb @@ -1,43 +1,49 @@ -class Api::V1::DigitalServiceAccountsController < ::UnauthenticatedApiController - def index - page = (params[:page].present? ? params[:page].to_i : 0) - size = (params[:size].present? ? params[:size].to_i : 100) - size = 100 if size > 100 +# frozen_string_literal: true - respond_to do |format| - format.json { - render json: DigitalServiceAccount.limit(100).order(:id), - each_serializer: DigitalServiceAccountSerializer, - links: links(form, page, size), - page: page, - size: size - } - end - end +module Api + module V1 + class DigitalServiceAccountsController < ::UnauthenticatedApiController + def index + page = (params[:page].present? ? params[:page].to_i : 0) + size = (params[:size].present? ? params[:size].to_i : 100) + size = 100 if size > 100 - def show - @digital_service_account = DigitalServiceAccount.find(params[:id]) + respond_to do |format| + format.json do + render json: DigitalServiceAccount.limit(100).order(:id), + each_serializer: DigitalServiceAccountSerializer, + links: links(form, page, size), + page:, + size: + end + end + end - respond_to do |format| - format.json { - render json: @digital_service_account, - serializer: DigitalServiceAccountSerializer - } - end - end + def show + @digital_service_account = DigitalServiceAccount.find(params[:id]) + + respond_to do |format| + format.json do + render json: @digital_service_account, + serializer: DigitalServiceAccountSerializer + end + end + end - def links(form, page, size) - ret = {} - if params[:page].present? - ret["first"] = request.original_url.gsub(/page=[0-9]+/i,"page=0") - ret["next"] = request.original_url.gsub(/page=[0-9]+/i,"page=" + (page + 1).to_s) if (form.submissions.size > ( (page + 1) * size)) - ret["prev"] = request.original_url.gsub(/page=[0-9]+/i,"page=" + (page - 1).to_s) if page > 0 - ret["last"] = request.original_url.gsub(/page=[0-9]+/i,"page=" + (form.submissions.size / size).floor.to_s) - else - ret["first"] = request.original_url + "&page=0" - ret["next"] = request.original_url + "&page=1" if form.submissions.size > size - ret["last"] = request.original_url + "&page=" + (form.submissions.size / size).floor.to_s + def links(form, page, size) + ret = {} + if params[:page].present? + ret['first'] = request.original_url.gsub(/page=[0-9]+/i, 'page=0') + ret['next'] = request.original_url.gsub(/page=[0-9]+/i, "page=#{page + 1}") if form.submissions.size > ((page + 1) * size) + ret['prev'] = request.original_url.gsub(/page=[0-9]+/i, "page=#{page - 1}") if page.positive? + ret['last'] = request.original_url.gsub(/page=[0-9]+/i, "page=#{(form.submissions.size / size).floor}") + else + ret['first'] = "#{request.original_url}&page=0" + ret['next'] = "#{request.original_url}&page=1" if form.submissions.size > size + ret['last'] = "#{request.original_url}&page=#{(form.submissions.size / size).floor}" + end + ret + end end - ret end end diff --git a/app/controllers/api/v1/forms_controller.rb b/app/controllers/api/v1/forms_controller.rb index 04b83738a..8aaba7568 100644 --- a/app/controllers/api/v1/forms_controller.rb +++ b/app/controllers/api/v1/forms_controller.rb @@ -1,48 +1,54 @@ -class Api::V1::FormsController < ::ApiController - def index - respond_to do |format| - format.json { - render json: current_user.forms.limit(100), each_serializer: FormSerializer - } - end - end +# frozen_string_literal: true - def show - form = current_user.forms.find_by_short_uuid(params[:id]) - page = (params[:page].present? ? params[:page].to_i : 0) - size = (params[:size].present? ? params[:size].to_i : 500) - size = 5000 if size > 5000 - # Date filter defaults to 1 year ago and 1 day from now - # Is there ever a case where we'd want to see submissions older than a year via the API? - begin - start_date = params[:start_date] ? Date.parse(params[:start_date]).to_date : 1.year.ago - end_date = params[:end_date] ? Date.parse(params[:end_date]).to_date : 1.day.from_now - rescue - render json: { error: { message: "invalid date format, should be 'YYYY-MM-DD'", status: 400 } }, status: 400 and return - end - respond_to do |format| - format.json { - if form - render json: form, include: [:questions, :submissions], serializer: FullFormSerializer, links: links(form,page,size), page: page, size: size, start_date: start_date, end_date: end_date - else - render json: { error: { message: "no form with Short UUID of #{params[:id]}", status: 404 } }, status: 404 +module Api + module V1 + class FormsController < ::ApiController + def index + respond_to do |format| + format.json do + render json: current_user.forms.limit(100), each_serializer: FormSerializer + end end - } - end - end + end - def links(form, page, size) - ret = {} - if params[:page].present? - ret["first"] = request.original_url.gsub(/page=[0-9]+/i,"page=0") - ret["next"] = request.original_url.gsub(/page=[0-9]+/i,"page=" + (page + 1).to_s) if (form.submissions.size > ( (page + 1) * size)) - ret["prev"] = request.original_url.gsub(/page=[0-9]+/i,"page=" + (page - 1).to_s) if page > 0 - ret["last"] = request.original_url.gsub(/page=[0-9]+/i,"page=" + (form.submissions.size / size).floor.to_s) - else - ret["first"] = request.original_url + "&page=0" - ret["next"] = request.original_url + "&page=1" if form.submissions.size > size - ret["last"] = request.original_url + "&page=" + (form.submissions.size / size).floor.to_s + def show + form = current_user.forms.find_by_short_uuid(params[:id]) + page = (params[:page].present? ? params[:page].to_i : 0) + size = (params[:size].present? ? params[:size].to_i : 500) + size = 5000 if size > 5000 + # Date filter defaults to 1 year ago and 1 day from now + # Is there ever a case where we'd want to see submissions older than a year via the API? + begin + start_date = params[:start_date] ? Date.parse(params[:start_date]).to_date : 1.year.ago + end_date = params[:end_date] ? Date.parse(params[:end_date]).to_date : 1.day.from_now + rescue StandardError + render json: { error: { message: "invalid date format, should be 'YYYY-MM-DD'", status: 400 } }, status: :bad_request and return + end + respond_to do |format| + format.json do + if form + render json: form, include: %i[questions submissions], serializer: FullFormSerializer, links: links(form, page, size), page: page, size: size, start_date: start_date, end_date: end_date + else + render json: { error: { message: "no form with Short UUID of #{params[:id]}", status: 404 } }, status: :not_found + end + end + end + end + + def links(form, page, size) + ret = {} + if params[:page].present? + ret['first'] = request.original_url.gsub(/page=[0-9]+/i, 'page=0') + ret['next'] = request.original_url.gsub(/page=[0-9]+/i, "page=#{page + 1}") if form.submissions.size > ((page + 1) * size) + ret['prev'] = request.original_url.gsub(/page=[0-9]+/i, "page=#{page - 1}") if page.positive? + ret['last'] = request.original_url.gsub(/page=[0-9]+/i, "page=#{(form.submissions.size / size).floor}") + else + ret['first'] = "#{request.original_url}&page=0" + ret['next'] = "#{request.original_url}&page=1" if form.submissions.size > size + ret['last'] = "#{request.original_url}&page=#{(form.submissions.size / size).floor}" + end + ret + end end - ret end end diff --git a/app/controllers/api/v1/goals_controller.rb b/app/controllers/api/v1/goals_controller.rb index be6020bf7..1f51ab7b2 100644 --- a/app/controllers/api/v1/goals_controller.rb +++ b/app/controllers/api/v1/goals_controller.rb @@ -1,9 +1,15 @@ -class Api::V1::GoalsController < ::ApiController - def index - respond_to do |format| - format.json { - render json: Goal.all.order(:id), each_serializer: GoalSerializer - } +# frozen_string_literal: true + +module Api + module V1 + class GoalsController < ::ApiController + def index + respond_to do |format| + format.json do + render json: Goal.all.order(:id), each_serializer: GoalSerializer + end + end + end end end end diff --git a/app/controllers/api/v1/objectives_controller.rb b/app/controllers/api/v1/objectives_controller.rb index 660336782..60dd19b81 100644 --- a/app/controllers/api/v1/objectives_controller.rb +++ b/app/controllers/api/v1/objectives_controller.rb @@ -1,9 +1,15 @@ -class Api::V1::ObjectivesController < ::ApiController - def index - respond_to do |format| - format.json { - render json: Objective.all.order(:id), each_serializer: ObjectiveSerializer - } +# frozen_string_literal: true + +module Api + module V1 + class ObjectivesController < ::ApiController + def index + respond_to do |format| + format.json do + render json: Objective.all.order(:id), each_serializer: ObjectiveSerializer + end + end + end end end end diff --git a/app/controllers/api/v1/omb_cx_reporting_collections_controller.rb b/app/controllers/api/v1/omb_cx_reporting_collections_controller.rb index ebfa2089e..2e424d76a 100644 --- a/app/controllers/api/v1/omb_cx_reporting_collections_controller.rb +++ b/app/controllers/api/v1/omb_cx_reporting_collections_controller.rb @@ -1,9 +1,15 @@ -class Api::V1::OmbCxReportingCollectionsController < ::ApiController - def index - respond_to do |format| - format.json { - render json: OmbCxReportingCollection.all.order(:id), each_serializer: OmbCxReportingCollectionSerializer - } +# frozen_string_literal: true + +module Api + module V1 + class OmbCxReportingCollectionsController < ::ApiController + def index + respond_to do |format| + format.json do + render json: OmbCxReportingCollection.all.order(:id), each_serializer: OmbCxReportingCollectionSerializer + end + end + end end end end diff --git a/app/controllers/api/v1/organizations_controller.rb b/app/controllers/api/v1/organizations_controller.rb index fa81d9797..6c13ad592 100644 --- a/app/controllers/api/v1/organizations_controller.rb +++ b/app/controllers/api/v1/organizations_controller.rb @@ -1,9 +1,15 @@ -class Api::V1::OrganizationsController < ::ApiController - def index - respond_to do |format| - format.json { - render json: Organization.all.order(:id), each_serializer: OrganizationSerializer - } +# frozen_string_literal: true + +module Api + module V1 + class OrganizationsController < ::ApiController + def index + respond_to do |format| + format.json do + render json: Organization.all.order(:id), each_serializer: OrganizationSerializer + end + end + end end end end diff --git a/app/controllers/api/v1/service_providers_controller.rb b/app/controllers/api/v1/service_providers_controller.rb index 6bba962d8..91b5c3d9c 100644 --- a/app/controllers/api/v1/service_providers_controller.rb +++ b/app/controllers/api/v1/service_providers_controller.rb @@ -1,9 +1,15 @@ -class Api::V1::ServiceProvidersController < ::ApiController - def index - respond_to do |format| - format.json { - render json: ServiceProvider.all.includes(:organization).order("organizations.name", :name), each_serializer: ServiceProviderSerializer - } +# frozen_string_literal: true + +module Api + module V1 + class ServiceProvidersController < ::ApiController + def index + respond_to do |format| + format.json do + render json: ServiceProvider.all.includes(:organization).order('organizations.name', :name), each_serializer: ServiceProviderSerializer + end + end + end end end end diff --git a/app/controllers/api/v1/services_controller.rb b/app/controllers/api/v1/services_controller.rb index 0d5e6940d..cce5bc97a 100644 --- a/app/controllers/api/v1/services_controller.rb +++ b/app/controllers/api/v1/services_controller.rb @@ -1,9 +1,15 @@ -class Api::V1::ServicesController < ::ApiController - def index - respond_to do |format| - format.json { - render json: Service.all.order(:id), each_serializer: ServiceSerializer - } +# frozen_string_literal: true + +module Api + module V1 + class ServicesController < ::ApiController + def index + respond_to do |format| + format.json do + render json: Service.all.order(:id), each_serializer: ServiceSerializer + end + end + end end end end diff --git a/app/controllers/api/v1/users_controller.rb b/app/controllers/api/v1/users_controller.rb index 3ca78fc28..8be152a28 100644 --- a/app/controllers/api/v1/users_controller.rb +++ b/app/controllers/api/v1/users_controller.rb @@ -1,9 +1,15 @@ -class Api::V1::UsersController < ::ApiController - def index - respond_to do |format| - format.json { - render json: User.active, each_serializer: UserSerializer - } +# frozen_string_literal: true + +module Api + module V1 + class UsersController < ::ApiController + def index + respond_to do |format| + format.json do + render json: User.active, each_serializer: UserSerializer + end + end + end end end end diff --git a/app/controllers/api/v1/websites_controller.rb b/app/controllers/api/v1/websites_controller.rb index 3b665ed03..7fa3d8071 100644 --- a/app/controllers/api/v1/websites_controller.rb +++ b/app/controllers/api/v1/websites_controller.rb @@ -1,9 +1,15 @@ -class Api::V1::WebsitesController < ::ApiController - def index - respond_to do |format| - format.json { - render json: Website.active, each_serializer: WebsiteSerializer - } +# frozen_string_literal: true + +module Api + module V1 + class WebsitesController < ::ApiController + def index + respond_to do |format| + format.json do + render json: Website.active, each_serializer: WebsiteSerializer + end + end + end end end end diff --git a/app/controllers/api_controller.rb b/app/controllers/api_controller.rb index a5de28c96..dbf865fff 100644 --- a/app/controllers/api_controller.rb +++ b/app/controllers/api_controller.rb @@ -1,20 +1,20 @@ +# frozen_string_literal: true + class ApiController < ::ApplicationController - http_basic_authenticate_with name: ENV.fetch("API_HTTP_USERNAME"), password: ENV.fetch("API_HTTP_PASSWORD") + http_basic_authenticate_with name: ENV.fetch('API_HTTP_USERNAME'), password: ENV.fetch('API_HTTP_PASSWORD') before_action :set_current_user def set_current_user - api_key = request.headers["X-Api-Key"].present? ? request.headers["X-Api-Key"] : params["API_KEY"] - unless api_key.present? - render json: { error: { message: "Invalid request. No ?API_KEY= was passed in." } }, status: 400 - else + api_key = request.headers['X-Api-Key'].presence || params['API_KEY'] + if api_key.present? @current_user = User.find_by_api_key(api_key) - unless @current_user - render json: { error: { message: "The API_KEY #{api_key} is not valid." } }, status: 401 - end + render json: { error: { message: "The API_KEY #{api_key} is not valid." } }, status: :unauthorized unless @current_user + else + render json: { error: { message: 'Invalid request. No ?API_KEY= was passed in.' } }, status: :bad_request end end def api_params - params.require("API_KEY") + params.require('API_KEY') end end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 6fde21923..904ff75d3 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,12 +1,13 @@ -class ApplicationController < ActionController::Base +# frozen_string_literal: true +class ApplicationController < ActionController::Base LEGACY_TOUCHPOINTS_URL_MAP = LegacyTouchpointUrlMap.map around_action :switch_locale - def switch_locale(&action) + def switch_locale(&) locale = params[:locale] || I18n.default_locale - I18n.with_locale(locale, &action) + I18n.with_locale(locale, &) end def fiscal_year(date) @@ -25,7 +26,7 @@ def fiscal_quarter(date) end end - def after_sign_in_path_for(resource) + def after_sign_in_path_for(_resource) admin_root_path end @@ -34,142 +35,145 @@ def after_sign_in_path_for(resource) # `ensure_` methods are responsible for checking permissions and redirecting if necessary # def ensure_user - if !current_user + unless current_user store_location_for(:user, request.fullpath) - redirect_to(index_path, notice: "Authorization is Required") + redirect_to(index_path, notice: 'Authorization is Required') end end def ensure_admin return true if admin_permissions? - redirect_to(index_path, notice: "Authorization is Required") + redirect_to(index_path, notice: 'Authorization is Required') end def ensure_admin_or_contact(obj) return true if admin_permissions? - if current_user.present? - return true if current_user.has_role?(:contact, obj) - end - redirect_to(index_path, notice: "Authorization is Required") + + return true if current_user.present? && current_user.has_role?(:contact, obj) + + redirect_to(index_path, notice: 'Authorization is Required') end def ensure_performance_manager_permissions return true if performance_manager_permissions? - redirect_to(index_path, notice: "Authorization is Required") + redirect_to(index_path, notice: 'Authorization is Required') end def ensure_collection_owner(collection:) - return false unless collection.present? + return false if collection.blank? return true if admin_permissions? - return true if collection_permissions?(collection: collection) + return true if collection_permissions?(collection:) - redirect_to(index_path, notice: "Authorization is Required") + redirect_to(index_path, notice: 'Authorization is Required') end def ensure_form_manager(form:) - return false unless form.present? - return true if form_permissions?(form: form) + return false if form.blank? + return true if form_permissions?(form:) - redirect_to(index_path, notice: "Authorization is Required") + redirect_to(index_path, notice: 'Authorization is Required') end def ensure_response_viewer(form:) - return false unless form.present? + return false if form.blank? return true if admin_permissions? - return true if form_permissions?(form: form) - return true if response_viewer_permissions?(form: form) + return true if form_permissions?(form:) + return true if response_viewer_permissions?(form:) - redirect_to(index_path, notice: "Authorization is Required") + redirect_to(index_path, notice: 'Authorization is Required') end def ensure_service_manager_permissions return true if service_manager_permissions? - redirect_to(admin_services_path, notice: "Authorization is Required") + redirect_to(admin_services_path, notice: 'Authorization is Required') end def ensure_service_owner(service:, user:) - return false unless user.present? - return true if service_permissions?(service: service) + return false if user.blank? + return true if service_permissions?(service:) - redirect_to(admin_services_path, notice: "Authorization is Required") + redirect_to(admin_services_path, notice: 'Authorization is Required') end def ensure_website_admin(website:, user:) - return false unless user.present? - return true if website.admin?(user: user) + return false if user.blank? + return true if website.admin?(user:) - redirect_to(admin_websites_path, notice: "Authorization is Required") + redirect_to(admin_websites_path, notice: 'Authorization is Required') end def ensure_organizational_website_manager - return false unless current_user.present? + return false if current_user.blank? return true if organizational_website_manager_permissions?(user: current_user) - redirect_to(admin_root_path, notice: "Authorization is Required") + redirect_to(admin_root_path, notice: 'Authorization is Required') end def ensure_registry_manager - return false unless current_user.present? + return false if current_user.blank? return true if registry_manager_permissions?(user: current_user) - redirect_to(admin_root_path, notice: "Authorization is Required") + redirect_to(admin_root_path, notice: 'Authorization is Required') end def ensure_digital_service_account_permissions(digital_service_account:) - return false unless current_user.present? - return true if digital_service_account_permissions?(digital_service_account: digital_service_account, user: current_user) + return false if current_user.blank? + return true if digital_service_account_permissions?(digital_service_account:, user: current_user) - redirect_to(admin_root_path, notice: "Authorization is Required") + redirect_to(admin_root_path, notice: 'Authorization is Required') end def ensure_digital_product_permissions(digital_product:) - return false unless current_user.present? - return true if digital_product_permissions?(digital_product: digital_product, user: current_user) + return false if current_user.blank? + return true if digital_product_permissions?(digital_product:, user: current_user) - redirect_to(admin_root_path, notice: "Authorization is Required") + redirect_to(admin_root_path, notice: 'Authorization is Required') end - # Define Permissions helper_method :admin_permissions? def admin_permissions? - current_user && current_user.admin? + current_user&.admin? end helper_method :performance_manager_permissions? def performance_manager_permissions? - return false unless current_user.present? + return false if current_user.blank? return true if admin_permissions? + current_user.performance_manager? end helper_method :collection_permissions? def collection_permissions?(collection:) - return false unless collection.present? + return false if collection.blank? return true if performance_manager_permissions? + collection.organization == current_user.organization end helper_method :organizational_website_manager_permissions? def organizational_website_manager_permissions?(user:) - return false unless user.present? + return false if user.blank? return true if admin_permissions? + user.organizational_website_manager? end helper_method :registry_manager_permissions? def registry_manager_permissions?(user:) - return false unless user.present? + return false if user.blank? return true if admin_permissions? + user.registry_manager? end helper_method :digital_service_account_permissions? def digital_service_account_permissions?(digital_service_account:, user:) - return false unless user.present? + return false if user.blank? return true if registry_manager_permissions?(user: current_user) user.has_role?(:contact, digital_service_account) @@ -177,15 +181,15 @@ def digital_service_account_permissions?(digital_service_account:, user:) helper_method :digital_product_permissions? def digital_product_permissions?(digital_product:, user:) - return false unless user.present? - return true if registry_manager_permissions?(user: user) + return false if user.blank? + return true if registry_manager_permissions?(user:) user.has_role?(:contact, digital_product) end helper_method :service_permissions? def service_permissions?(service:) - return false unless service.present? + return false if service.blank? return true if current_user.has_role?(:service_manager, service) return true if service_manager_permissions? return true if admin_permissions? @@ -195,55 +199,57 @@ def service_permissions?(service:) helper_method :service_manager_permissions? def service_manager_permissions? - return false unless current_user.present? + return false if current_user.blank? return true if current_user.service_manager? return true if admin_permissions? - return false + + false end helper_method :form_permissions? def form_permissions?(form:) - return false unless form.present? + return false if form.blank? return true if admin_permissions? return true if current_user.has_role?(:form_manager, form) + (form.user_role?(user: current_user) == UserRole::Role::FormManager) end helper_method :response_viewer_permissions? def response_viewer_permissions?(form:) - return false unless form.present? + return false if form.blank? - (form.user_role?(user: current_user) == UserRole::Role::ResponseViewer) || form_permissions?(form: form) + (form.user_role?(user: current_user) == UserRole::Role::ResponseViewer) || form_permissions?(form:) end - # Helpers def timestamp_string - Time.now.strftime('%Y-%m-%d_%H-%M-%S') + Time.zone.now.strftime('%Y-%m-%d_%H-%M-%S') end def paginate(scope, default_per_page = 20) collection = scope.page(params[:page]).per((params[:per_page] || default_per_page).to_i) - current, total, per_page = collection.current_page, collection.num_pages, collection.limit_value + current = collection.current_page + total = collection.num_pages + per_page = collection.limit_value - return [{ + [{ pagination: { - current: current, + current:, previous: (current > 1 ? (current - 1) : nil), - next: (current == total ? nil : (current + 1)), - per_page: per_page, - pages: total, - count: collection.total_count - } + next: (current == total ? nil : (current + 1)), + per_page:, + pages: total, + count: collection.total_count, + }, }, collection] end - private # For Devise - def after_sign_out_path_for(resource_or_scope) + def after_sign_out_path_for(_resource_or_scope) index_path end diff --git a/app/controllers/errors_controller.rb b/app/controllers/errors_controller.rb index 3d2abd68b..b2bd6160f 100644 --- a/app/controllers/errors_controller.rb +++ b/app/controllers/errors_controller.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + class ErrorsController < ApplicationController protect_from_forgery with: :null_session - layout "public" + layout 'public' def not_found - render(status: 404) + render(status: :not_found) end def internal_server_error - render(status: 500) + render(status: :internal_server_error) end end diff --git a/app/controllers/profile_controller.rb b/app/controllers/profile_controller.rb index 512bf4e93..01802eeca 100644 --- a/app/controllers/profile_controller.rb +++ b/app/controllers/profile_controller.rb @@ -1,20 +1,21 @@ +# frozen_string_literal: true + class ProfileController < ApplicationController before_action :ensure_user - def show - end + def show; end def update if current_user.update(user_params) - redirect_to profile_path, notice: "User profile updated" + redirect_to profile_path, notice: 'User profile updated' else render :show, status: :unprocessable_entity end end -private + private def user_params - params.require(:user).permit(:time_zone, :api_key) + params.require(:user).permit(:time_zone, :api_key) end end diff --git a/app/controllers/site_controller.rb b/app/controllers/site_controller.rb index 94b20fce9..ed9a39599 100644 --- a/app/controllers/site_controller.rb +++ b/app/controllers/site_controller.rb @@ -1,25 +1,22 @@ +# frozen_string_literal: true + class SiteController < ApplicationController def index - if current_user - redirect_to admin_root_path - end + redirect_to admin_root_path if current_user end - def agencies - end + def agencies; end - def registry - end + def registry; end def status render json: { status: :success, services: { - database: :operational - } + database: :operational, + }, } end - def hello_stimulus - end + def hello_stimulus; end end diff --git a/app/controllers/submissions_controller.rb b/app/controllers/submissions_controller.rb index 292c29d85..ffa6b47e8 100644 --- a/app/controllers/submissions_controller.rb +++ b/app/controllers/submissions_controller.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + class SubmissionsController < ApplicationController protect_from_forgery only: [] - before_action :set_form, only: [:new, :create] + before_action :set_form, only: %i[new create] layout 'public', only: :new @@ -30,27 +32,27 @@ def create # Prevent the Submission if this is a published Form and if: if @form && - request.referer && - # is not from the Form's whitelist URL - (@form.whitelist_url.present? ? !request.referer.start_with?(@form.whitelist_url) : true) && - # is not from the Form's test whitelist URL - (@form.whitelist_test_url.present? ? !request.referer.start_with?(@form.whitelist_test_url) : true) && - # is not from the Touchpoints app - !request.referer.start_with?(root_url) && - # is not from the Organization URL - !request.referer.start_with?(@form.organization.url) + request.referer && + # is not from the Form's whitelist URL + (@form.whitelist_url.present? ? !request.referer.start_with?(@form.whitelist_url) : true) && + # is not from the Form's test whitelist URL + (@form.whitelist_test_url.present? ? !request.referer.start_with?(@form.whitelist_test_url) : true) && + # is not from the Touchpoints app + !request.referer.start_with?(root_url) && + # is not from the Organization URL + !request.referer.start_with?(@form.organization.url) error_options = { custom_params: { - referer: request.referer + referer: request.referer, }, - expected: true + expected: true, } NewRelic::Agent.notice_error(ArgumentError, error_options) render json: { status: :unprocessable_entity, - messages: { submission: [t('errors.request.unauthorized_host')] } + messages: { submission: [t('errors.request.unauthorized_host')] }, }, status: :unprocessable_entity and return end @@ -66,67 +68,61 @@ def create private - def create_in_local_database(submission) - respond_to do |format| - if submission.save - format.html do - redirect_to submit_touchpoint_path(submission.form), - notice: 'Thank You. Response was submitted successfully.' - end - format.json do - render json: { - submission: { - id: submission.id, - first_name: submission.answer_01, - last_name: submission.answer_02, - email: submission.answer_03, - phone_number: submission.answer_04, - form: { - id: submission.form.uuid, - name: submission.form.name, - organization_name: submission.organization_name - } - } - }, - status: :created - end - else - format.html do - end - format.json do - render json: { - status: :unprocessable_entity, - messages: submission.errors - }, status: :unprocessable_entity - end + def create_in_local_database(submission) + respond_to do |format| + if submission.save + format.html do + redirect_to submit_touchpoint_path(submission.form), + notice: 'Thank You. Response was submitted successfully.' end - end - end - - def set_form - if params[:form] - @short_uuid = params[:id].to_s - if LEGACY_TOUCHPOINTS_URL_MAP.has_key?(params[:id].to_s) - @short_uuid = LEGACY_TOUCHPOINTS_URL_MAP[params[:id].to_s] + format.json do + render json: { + submission: { + id: submission.id, + first_name: submission.answer_01, + last_name: submission.answer_02, + email: submission.answer_03, + phone_number: submission.answer_04, + form: { + id: submission.form.uuid, + name: submission.form.name, + organization_name: submission.organization_name, + }, + }, + }, + status: :created end - elsif params[:form_id] - @short_uuid = params[:form_id].to_s - if LEGACY_TOUCHPOINTS_URL_MAP.has_key?(params[:form_id].to_s) - @short_uuid = LEGACY_TOUCHPOINTS_URL_MAP[params[:form_id].to_s] + else + format.html do end - elsif params[:touchpoint_id] - @short_uuid = params[:touchpoint_id].to_s - if LEGACY_TOUCHPOINTS_URL_MAP.has_key?(params[:touchpoint_id].to_s) - @short_uuid = LEGACY_TOUCHPOINTS_URL_MAP[params[:touchpoint_id].to_s] + format.json do + render json: { + status: :unprocessable_entity, + messages: submission.errors, + }, status: :unprocessable_entity end end - @form = FormCache.fetch(@short_uuid) - raise ActiveRecord::RecordNotFound, "no form with ID of #{@short_uuid}" unless @form.present? end + end - def submission_params - permitted_fields = @form.questions.collect(&:answer_field) - permitted_fields << %i[language location_code referer page fba_directive] - params.require(:submission).permit(permitted_fields) + def set_form + if params[:form] + @short_uuid = params[:id].to_s + @short_uuid = LEGACY_TOUCHPOINTS_URL_MAP[params[:id].to_s] if LEGACY_TOUCHPOINTS_URL_MAP.key?(params[:id].to_s) + elsif params[:form_id] + @short_uuid = params[:form_id].to_s + @short_uuid = LEGACY_TOUCHPOINTS_URL_MAP[params[:form_id].to_s] if LEGACY_TOUCHPOINTS_URL_MAP.key?(params[:form_id].to_s) + elsif params[:touchpoint_id] + @short_uuid = params[:touchpoint_id].to_s + @short_uuid = LEGACY_TOUCHPOINTS_URL_MAP[params[:touchpoint_id].to_s] if LEGACY_TOUCHPOINTS_URL_MAP.key?(params[:touchpoint_id].to_s) end + @form = FormCache.fetch(@short_uuid) + raise ActiveRecord::RecordNotFound, "no form with ID of #{@short_uuid}" if @form.blank? + end + + def submission_params + permitted_fields = @form.questions.collect(&:answer_field) + permitted_fields << %i[language location_code referer page fba_directive] + params.require(:submission).permit(permitted_fields) + end end diff --git a/app/controllers/touchpoints_controller.rb b/app/controllers/touchpoints_controller.rb index 417da47c2..f7876e64d 100644 --- a/app/controllers/touchpoints_controller.rb +++ b/app/controllers/touchpoints_controller.rb @@ -1,30 +1,34 @@ +# frozen_string_literal: true + class TouchpointsController < ApplicationController skip_before_action :verify_authenticity_token before_action :set_touchpoint def show respond_to do |format| - format.html { + format.html do redirect_to submit_touchpoint_path(@form) # instead of rendering #show - } - format.js { + end + format.js do js - } + end end end def js @form.increment!(:survey_form_activations) - render(partial: "components/widget/fba", formats: :js, locals: { form: @form }) + render(partial: 'components/widget/fba', formats: :js, locals: { form: @form }) end - private - def set_touchpoint - @form = (params[:id].to_s.length == 8) ? # if short_uuid - (Form.find_by_legacy_touchpoints_uuid(params[:id]) || Form.find_by_short_uuid(params[:id])) : - (Form.find_by_legacy_touchpoints_id(params[:id])) - raise ActiveRecord::RecordNotFound, "no form with ID of #{params[:id]}" unless @form.present? - end + def set_touchpoint + @form = if params[:id].to_s.length == 8 + (Form.find_by_legacy_touchpoints_uuid(params[:id]) || Form.find_by_short_uuid(params[:id])) + else + Form.find_by_legacy_touchpoints_id(params[:id]) + end + + raise ActiveRecord::RecordNotFound, "no form with ID of #{params[:id]}" if @form.blank? + end end diff --git a/app/controllers/unauthenticated_api_controller.rb b/app/controllers/unauthenticated_api_controller.rb index 6b3499108..c8521a584 100644 --- a/app/controllers/unauthenticated_api_controller.rb +++ b/app/controllers/unauthenticated_api_controller.rb @@ -1,2 +1,4 @@ +# frozen_string_literal: true + class UnauthenticatedApiController < ::ApplicationController end diff --git a/app/controllers/users/omniauth_callbacks_controller.rb b/app/controllers/users/omniauth_callbacks_controller.rb index 0db93ba39..cb98adc27 100644 --- a/app/controllers/users/omniauth_callbacks_controller.rb +++ b/app/controllers/users/omniauth_callbacks_controller.rb @@ -1,46 +1,46 @@ -class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController - def login_dot_gov - @kind = "Login.gov" - if (auth_hash && auth_hash["info"]["email_verified"]) - @email = auth_hash["info"]["email"] - end - - login - end +# frozen_string_literal: true - def github - @kind = "GitHub" - redirect_to index_path, alert: "Invalid request" unless ENV["GITHUB_CLIENT_ID"].present? - @email = auth_hash["info"]["email"] - login - end +module Users + class OmniauthCallbacksController < Devise::OmniauthCallbacksController + def login_dot_gov + @kind = 'Login.gov' + @email = auth_hash['info']['email'] if auth_hash && auth_hash['info']['email_verified'] - def failure - Event.log_event(Event.names[:user_authentication_failure], "Event::Generic", 1, "Email #{@email} failed to authenticate on #{Date.today}. #{failure_message}") - redirect_to new_user_session_path, alert: "#{@kind} error: #{failure_message}" - end + login + end - private + def github + @kind = 'GitHub' + redirect_to index_path, alert: 'Invalid request' if ENV['GITHUB_CLIENT_ID'].blank? + @email = auth_hash['info']['email'] + login + end - def auth_hash - request.env["omniauth.auth"] - end + def failure + Event.log_event(Event.names[:user_authentication_failure], 'Event::Generic', 1, "Email #{@email} failed to authenticate on #{Date.today}. #{failure_message}") + redirect_to new_user_session_path, alert: "#{@kind} error: #{failure_message}" + end - def login - Event.log_event(Event.names[:user_authentication_attempt], "Event::Generic", 1, "Email #{@email} attempted to authenticate on #{Date.today}") + private - if @email.present? - @user = User.from_omniauth(auth_hash) + def auth_hash + request.env['omniauth.auth'] end - # If user exists - # Else, if valid email and no user, we create an account. - if !@user.errors.present? - Event.log_event(Event.names[:user_authentication_successful], "User", @user.id, "User #{@user.email} successfully authenticated on #{Date.today}", @user.id) - sign_in_and_redirect(:user, @user) - elsif @user.errors.present? - Event.log_event(Event.names[:user_authentication_failure], "Event::Generic", 1, "Email #{@email} failed to authenticate on #{Date.today}. #{@user.errors.full_messages}") - redirect_to index_path, alert: @user.errors.full_messages.join(",") + def login + Event.log_event(Event.names[:user_authentication_attempt], 'Event::Generic', 1, "Email #{@email} attempted to authenticate on #{Date.today}") + + @user = User.from_omniauth(auth_hash) if @email.present? + + # If user exists + # Else, if valid email and no user, we create an account. + if @user.errors.blank? + Event.log_event(Event.names[:user_authentication_successful], 'User', @user.id, "User #{@user.email} successfully authenticated on #{Date.today}", @user.id) + sign_in_and_redirect(:user, @user) + elsif @user.errors.present? + Event.log_event(Event.names[:user_authentication_failure], 'Event::Generic', 1, "Email #{@email} failed to authenticate on #{Date.today}. #{@user.errors.full_messages}") + redirect_to index_path, alert: @user.errors.full_messages.join(',') + end end end end diff --git a/app/helpers/admin/digital_product_versions_helper.rb b/app/helpers/admin/digital_product_versions_helper.rb index e1bb768d0..8f7b1a254 100644 --- a/app/helpers/admin/digital_product_versions_helper.rb +++ b/app/helpers/admin/digital_product_versions_helper.rb @@ -1,2 +1,6 @@ -module Admin::DigitalProductVersionsHelper +# frozen_string_literal: true + +module Admin + module DigitalProductVersionsHelper + end end diff --git a/app/helpers/admin/offerings_helper.rb b/app/helpers/admin/offerings_helper.rb index d289a5efa..74969c5c1 100644 --- a/app/helpers/admin/offerings_helper.rb +++ b/app/helpers/admin/offerings_helper.rb @@ -1,2 +1,6 @@ -module Admin::OfferingsHelper +# frozen_string_literal: true + +module Admin + module OfferingsHelper + end end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 02730e3b9..37367c2b3 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,15 +1,15 @@ +# frozen_string_literal: true + require 'kramdown' module ApplicationHelper - def suppress_main_layout_flash? - if flash && ["User successfully added", "User successfully removed"].include?(flash.notice) - return true - end + return true if flash && ['User successfully added', 'User successfully removed'].include?(flash.notice) end def to_markdown(text) - return nil unless text.present? + return nil if text.blank? + raw(sanitize(Kramdown::Document.new(text).to_html)) end @@ -19,23 +19,24 @@ def organization_dropdown_options def hisp_questions_key { - "1" => "satisfaction", - "2" => "trust", - "3" => "effectiveness", - "4" => "ease", - "5" => "efficiency", - "6" => "transparency", - "7" => "employee", + '1' => 'satisfaction', + '2' => 'trust', + '3' => 'effectiveness', + '4' => 'ease', + '5' => 'efficiency', + '6' => 'transparency', + '7' => 'employee', } end def collection_rating_label(rating:) - if rating == "TRUE" - "🟢" - elsif rating == "FALSE" - "🔴" - elsif rating == "PARTIAL" - "🟡" + case rating + when 'TRUE' + '🟢' + when 'FALSE' + '🔴' + when 'PARTIAL' + '🟡' end end @@ -43,9 +44,9 @@ def collection_rating_label(rating:) # value = sort order def collection_rating_sort_values { - "FALSE" => "1", - "PARTIAL" => "2", - "TRUE" => "3" + 'FALSE' => '1', + 'PARTIAL' => '2', + 'TRUE' => '3', } end @@ -53,11 +54,11 @@ def collection_rating_sort_values # value = sort order def service_status_sort_values { - "created" => "1", - "submitted" => "2", - "approved" => "3", - "verified" => "4", - "archived" => "5" + 'created' => '1', + 'submitted' => '2', + 'approved' => '3', + 'verified' => '4', + 'archived' => '5', } end @@ -65,68 +66,68 @@ def service_status_sort_values # value = sort order def website_status_sort_values { - "newly_requested" => "1", - "request_approved" => "2", - "request_denied" => "3", - "in_development" => "4", - "production" => "5", - "being_decommissioned" => "6", - "redirect" => "7", - "archived" => "8", - "decommissioned" => "9", + 'newly_requested' => '1', + 'request_approved' => '2', + 'request_denied' => '3', + 'in_development' => '4', + 'production' => '5', + 'being_decommissioned' => '6', + 'redirect' => '7', + 'archived' => '8', + 'decommissioned' => '9', } end def website_status_label_tags(status) { - "newly_requested" => "bg-primary-light", - "request_approved" => "bg-primary", - "request_denied" => "bg-red", - "in_development" => "bg-blue", - "production" => "bg-mint", - "being_decommissioned" => "bg-accent-warm-dark", - "redirect" => "bg-accent-warm-light", - "archived" => "bg-gray-30", - "decommissioned" => "bg-black", + 'newly_requested' => 'bg-primary-light', + 'request_approved' => 'bg-primary', + 'request_denied' => 'bg-red', + 'in_development' => 'bg-blue', + 'production' => 'bg-mint', + 'being_decommissioned' => 'bg-accent-warm-dark', + 'redirect' => 'bg-accent-warm-light', + 'archived' => 'bg-gray-30', + 'decommissioned' => 'bg-black', }[status] end # Returns javascript to capture form input for one Form Question def question_type_javascript_params(question) - if question.question_type == "text_field" + if question.question_type == 'text_field' "form.querySelector(\"##{question.answer_field}\") && form.querySelector(\"##{question.answer_field}\").value" - elsif question.question_type == "hidden_field" + elsif question.question_type == 'hidden_field' "form.querySelector(\"##{question.answer_field}\") && form.querySelector(\"##{question.answer_field}\").value" - elsif question.question_type == "date_select" + elsif question.question_type == 'date_select' "form.querySelector(\"##{question.answer_field}\") && form.querySelector(\"##{question.answer_field}\").value" - elsif question.question_type == "text_email_field" + elsif question.question_type == 'text_email_field' "form.querySelector(\"##{question.answer_field}\") && form.querySelector(\"##{question.answer_field}\").value" - elsif question.question_type == "text_phone_field" + elsif question.question_type == 'text_phone_field' "form.querySelector(\"##{question.answer_field}\") && form.querySelector(\"##{question.answer_field}\").value" - elsif question.question_type == "textarea" + elsif question.question_type == 'textarea' "form.querySelector(\"##{question.answer_field}\") && form.querySelector(\"##{question.answer_field}\").value" - elsif question.question_type == "radio_buttons" + elsif question.question_type == 'radio_buttons' "form.querySelector(\"input[name=#{question.answer_field}]:checked\") && form.querySelector(\"input[name=#{question.answer_field}]:checked\").value" - elsif question.question_type == "star_radio_buttons" + elsif question.question_type == 'star_radio_buttons' "form.querySelector(\"input[name=#{question.answer_field}]:checked\") && form.querySelector(\"input[name=#{question.answer_field}]:checked\").value" - elsif question.question_type == "thumbs_up_down_buttons" + elsif question.question_type == 'thumbs_up_down_buttons' "form.querySelector(\"input[name=#{question.answer_field}]:checked\") && form.querySelector(\"input[name=#{question.answer_field}]:checked\").value" - elsif question.question_type == "yes_no_buttons" + elsif question.question_type == 'yes_no_buttons' "form.querySelector(\"input[name=#{question.answer_field}]\") && form.querySelector(\"input[name=#{question.answer_field}]\").value" - elsif question.question_type == "checkbox" + elsif question.question_type == 'checkbox' "form.querySelector(\"input[name=#{question.answer_field}]:checked\") && Array.apply(null,form.querySelectorAll(\"input[name=#{question.answer_field}]:checked\")).map(function(x) {return x.value;}).join(',')" - elsif ["dropdown", "states_dropdown"].include?(question.question_type) + elsif %w[dropdown states_dropdown].include?(question.question_type) "form.querySelector(\"##{question.answer_field}\") && form.querySelector(\"##{question.answer_field}\").value" - elsif question.question_type == "text_display" - "null" - elsif question.question_type == "custom_text_display" + elsif question.question_type == 'text_display' + 'null' + elsif question.question_type == 'custom_text_display' "form.querySelector(\"input[name=#{question.answer_field}]:checked\") && form.querySelector(\"input[name=#{question.answer_field}]:checked\").value" end end def is_at_least_form_manager?(user:, form:) user.admin? || - form.user_role?(user: user) == UserRole::Role::FormManager + form.user_role?(user:) == UserRole::Role::FormManager end def current_path @@ -134,33 +135,33 @@ def current_path end def answer_fields - [ - "answer_01", - "answer_02", - "answer_03", - "answer_04", - "answer_05", - "answer_06", - "answer_07", - "answer_08", - "answer_09", - "answer_10", - "answer_11", - "answer_12", - "answer_13", - "answer_14", - "answer_15", - "answer_16", - "answer_17", - "answer_18", - "answer_19", - "answer_20" + %w[ + answer_01 + answer_02 + answer_03 + answer_04 + answer_05 + answer_06 + answer_07 + answer_08 + answer_09 + answer_10 + answer_11 + answer_12 + answer_13 + answer_14 + answer_15 + answer_16 + answer_17 + answer_18 + answer_19 + answer_20 ] end # Legacy route from before the Form model was merged with the Touchpoint model def submit_touchpoint_uuid_url(form) - return "#{root_url}touchpoints/#{form.short_uuid}/submit" + "#{root_url}touchpoints/#{form.short_uuid}/submit" end def format_time(time, timezone) @@ -168,7 +169,7 @@ def format_time(time, timezone) end def form_integrity_checksum(form:) - data_to_encode = render(partial: "components/widget/fba", formats: :js, locals: { form: form }) + data_to_encode = render(partial: 'components/widget/fba', formats: :js, locals: { form: }) Digest::SHA256.base64digest(data_to_encode) end end diff --git a/app/helpers/digital_product_versions_helper.rb b/app/helpers/digital_product_versions_helper.rb index 1466f9c44..7896f1277 100644 --- a/app/helpers/digital_product_versions_helper.rb +++ b/app/helpers/digital_product_versions_helper.rb @@ -1,2 +1,4 @@ +# frozen_string_literal: true + module DigitalProductVersionsHelper end diff --git a/app/helpers/websites_helper.rb b/app/helpers/websites_helper.rb index 55f032b59..5e0b6a174 100644 --- a/app/helpers/websites_helper.rb +++ b/app/helpers/websites_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module WebsitesHelper include ActsAsTaggableOn::TagsHelper -end \ No newline at end of file +end diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb index a009ace51..d92ffddcb 100644 --- a/app/jobs/application_job.rb +++ b/app/jobs/application_job.rb @@ -1,2 +1,4 @@ +# frozen_string_literal: true + class ApplicationJob < ActiveJob::Base end diff --git a/app/jobs/export_events_job.rb b/app/jobs/export_events_job.rb index b734f8944..eccabbbbc 100644 --- a/app/jobs/export_events_job.rb +++ b/app/jobs/export_events_job.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + class ExportEventsJob < ApplicationJob queue_as :default - def perform(session_uuid, filename = "touchpoints-system-events-#{Time.now.to_s}.csv") + def perform(session_uuid, filename = "touchpoints-system-events-#{Time.zone.now}.csv") csv_content = Event.to_csv ActionCable.server.broadcast( - "exports_channel_#{session_uuid}", { csv: csv_content, filename: filename } + "exports_channel_#{session_uuid}", { csv: csv_content, filename: } ) end end diff --git a/app/jobs/export_job.rb b/app/jobs/export_job.rb index aaa02230c..458a4ddb8 100644 --- a/app/jobs/export_job.rb +++ b/app/jobs/export_job.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + class ExportJob < ApplicationJob queue_as :default - def perform(session_uuid, form_short_uuid, start_date, end_date, filename = "export-#{Time.now.to_s}.csv") - csv_content = Form.find_by_short_uuid(form_short_uuid).to_csv(start_date: start_date, end_date: end_date) + def perform(session_uuid, form_short_uuid, start_date, end_date, filename = "export-#{Time.zone.now}.csv") + csv_content = Form.find_by_short_uuid(form_short_uuid).to_csv(start_date:, end_date:) ActionCable.server.broadcast( - "exports_channel_#{session_uuid}", { csv: csv_content, filename: filename } + "exports_channel_#{session_uuid}", { csv: csv_content, filename: } ) end end diff --git a/app/jobs/export_versions_job.rb b/app/jobs/export_versions_job.rb index c81bd9898..3b2636da6 100644 --- a/app/jobs/export_versions_job.rb +++ b/app/jobs/export_versions_job.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + class ExportVersionsJob < ApplicationJob queue_as :default - def perform(session_uuid, versionable, filename = "touchpoints-versions-#{Time.now.to_s}.csv") + def perform(session_uuid, versionable, filename = "touchpoints-versions-#{Time.zone.now}.csv") csv_content = Version.to_csv(versionable) ActionCable.server.broadcast( - "exports_channel_#{session_uuid}", { csv: csv_content, filename: filename } + "exports_channel_#{session_uuid}", { csv: csv_content, filename: } ) end end diff --git a/app/lib/api_key.rb b/app/lib/api_key.rb index e698a4f68..5f5adf293 100644 --- a/app/lib/api_key.rb +++ b/app/lib/api_key.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + # lib/api_key.rb module ApiKey def self.generator SecureRandom.base64.tr('+/=', 'Qrt') end -end \ No newline at end of file +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb index 18d90305d..ef75f304b 100644 --- a/app/mailers/application_mailer.rb +++ b/app/mailers/application_mailer.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + class ApplicationMailer < ActionMailer::Base - default from: ENV.fetch("TOUCHPOINTS_EMAIL_SENDER") + default from: ENV.fetch('TOUCHPOINTS_EMAIL_SENDER') layout 'mailer' @@header_logo = File.read("#{Rails.root}/app/assets/images/touchpoints-logo-@2x.png") def set_logo - attachments.inline["logo.png"] = @@header_logo + attachments.inline['logo.png'] = @@header_logo end end diff --git a/app/mailers/user_mailer.rb b/app/mailers/user_mailer.rb index 901c91ed1..5a529c7e9 100644 --- a/app/mailers/user_mailer.rb +++ b/app/mailers/user_mailer.rb @@ -1,18 +1,19 @@ -class UserMailer < ApplicationMailer +# frozen_string_literal: true +class UserMailer < ApplicationMailer # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.user_mailer.submission_notification.subject # - def notification(title: "", body: "", path: "", emails: []) + def notification(title: '', body: '', path: '', emails: []) set_logo @body = body @path = path mail subject: "Touchpoints notification: #{title}", - to: emails + to: emails end def submission_notification(submission_id:, emails: []) @@ -20,47 +21,50 @@ def submission_notification(submission_id:, emails: []) @submission = Submission.find(submission_id) @form = @submission.form mail subject: "New Submission to #{@form.name}", - to: emails + to: emails end - def social_media_account_created_notification(digital_service_account:, link: ) + def social_media_account_created_notification(digital_service_account:, link:) set_logo @digital_service_account = digital_service_account @link = link - mail subject: "Touchpoints social media account has been created", - to: UserMailer.registry_manager_emails + mail subject: 'Touchpoints social media account has been created', + to: UserMailer.registry_manager_emails end - def service_event_notification(subject:, service:, event:, link: "") + def service_event_notification(subject:, service:, event:, link: '') set_logo @subject = subject @service = service @event = event @link = link mail subject: "Touchpoints event notification: #{subject}", - to: (ENV.fetch("TOUCHPOINTS_ADMIN_EMAILS").split(',') + User.service_managers.collect(&:email)).uniq + to: (ENV.fetch('TOUCHPOINTS_ADMIN_EMAILS').split(',') + User.service_managers.collect(&:email)).uniq end def collection_notification(collection_id:) set_logo @collection = Collection.find(collection_id) mail subject: "Data Collection notification to #{@collection.name}", - to: (ENV.fetch("TOUCHPOINTS_ADMIN_EMAILS").split(',') + User.performance_managers.collect(&:email)).uniq + to: (ENV.fetch('TOUCHPOINTS_ADMIN_EMAILS').split(',') + User.performance_managers.collect(&:email)).uniq end def submissions_digest(form_id, begin_day) - return unless ENV["ENABLE_EMAIL_NOTIFICATIONS"] == "true" + return unless ENV['ENABLE_EMAIL_NOTIFICATIONS'] == 'true' + @begin_day = begin_day @form = Form.find(form_id) return unless @form.send_notifications? + set_logo - @submissions = Submission.where(id: form_id).where("created_at > ?",@begin_day).order("created_at desc") + @submissions = Submission.where(id: form_id).where('created_at > ?', @begin_day).order('created_at desc') emails = @form.notification_emails.split(',') mail subject: "New Submissions to #{@form.name} since #{@begin_day}", to: emails end def account_deactivation_scheduled_notification(email, active_days) - return unless ENV["ENABLE_EMAIL_NOTIFICATIONS"] == "true" + return unless ENV['ENABLE_EMAIL_NOTIFICATIONS'] == 'true' + @active_days = active_days set_logo @@ -74,9 +78,9 @@ def account_deactivation_scheduled_notification(email, active_days) # def admin_summary set_logo - @greeting = "Hi, admin_summary" + @greeting = 'Hi, admin_summary' - mail to: ENV.fetch("TOUCHPOINTS_ADMIN_EMAILS").split(',') + mail to: ENV.fetch('TOUCHPOINTS_ADMIN_EMAILS').split(',') end # Subject can be set in your I18n file at config/locales/en.yml @@ -86,9 +90,9 @@ def admin_summary # def webmaster_summary set_logo - @greeting = "Hi, webmaster_summary" + @greeting = 'Hi, webmaster_summary' - mail to: ENV.fetch("TOUCHPOINTS_ADMIN_EMAILS").split(',') + mail to: ENV.fetch('TOUCHPOINTS_ADMIN_EMAILS').split(',') end def website_created(website:) @@ -96,8 +100,8 @@ def website_created(website:) set_logo @website = website - @emails = (ENV.fetch("TOUCHPOINTS_ADMIN_EMAILS").split(',') + User.organizational_website_managers.collect(&:email)).uniq - mail subject: "Touchpoints notification: Website created", to: @emails + @emails = (ENV.fetch('TOUCHPOINTS_ADMIN_EMAILS').split(',') + User.organizational_website_managers.collect(&:email)).uniq + mail subject: 'Touchpoints notification: Website created', to: @emails end def website_data_collection(email, websites) @@ -107,65 +111,63 @@ def website_data_collection(email, websites) @greeting = "Hi, #{email}" @email = email @websites = websites - mail subject: "Website Data Collection Request", to: email + mail subject: 'Website Data Collection Request', to: email end def new_user_notification(user) set_logo @user = user - mail subject: "New user account created", - to: UserMailer.touchpoints_team + mail subject: 'New user account created', + to: UserMailer.touchpoints_team end def form_expiring_notification(form) set_logo @form = form mail subject: "Form #{@form.name} expiring on #{@form.expiration_date}", - to: ENV.fetch("TOUCHPOINTS_ADMIN_EMAILS").split(',') + to: ENV.fetch('TOUCHPOINTS_ADMIN_EMAILS').split(',') end def org_user_notification(user, org_admin) set_logo @user = user @org_admin = org_admin - mail subject: "New user added to organization", - to: org_admin.email + mail subject: 'New user added to organization', + to: org_admin.email end def no_org_notification(user) set_logo @user = user - mail subject: "New user account creation failed", - to: UserMailer.touchpoints_support + mail subject: 'New user account creation failed', + to: UserMailer.touchpoints_support end def account_deactivated_notification(user) set_logo @user = user - mail subject: "User account deactivated", - to: UserMailer.touchpoints_team + mail subject: 'User account deactivated', + to: UserMailer.touchpoints_team end def invite(user, invitee) set_logo - Event.log_event(Event.names[:user_send_invitation], "User", user.id, "User #{user.email} invited #{invitee} at #{Time.now.to_s}") - attachments.inline["logo.png"] = @@header_logo + Event.log_event(Event.names[:user_send_invitation], 'User', user.id, "User #{user.email} invited #{invitee} at #{Time.zone.now}") + attachments.inline['logo.png'] = @@header_logo @user = user @invitee = invitee - mail subject: "Touchpoints invite", to: @invitee + mail subject: 'Touchpoints invite', to: @invitee end - private - def self.registry_manager_emails - User.registry_managers.collect { |u| u.email }.join(",") + User.registry_managers.collect(&:email).join(',') end def self.touchpoints_team - ENV.fetch('TOUCHPOINTS_TEAM') { 'feedback-analytics@gsa.gov' } + ENV.fetch('TOUCHPOINTS_TEAM', 'feedback-analytics@gsa.gov') end def self.touchpoints_support - ENV.fetch('TOUCHPOINTS_SUPPORT') { 'feedback-analytics@gsa.gov' } + ENV.fetch('TOUCHPOINTS_SUPPORT', 'feedback-analytics@gsa.gov') end end diff --git a/app/models/application_record.rb b/app/models/application_record.rb index 3194d4e94..58b95955c 100644 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -1,8 +1,9 @@ +# frozen_string_literal: true + class ApplicationRecord < ActiveRecord::Base self.abstract_class = true def self.tag_counts_by_name - ActsAsTaggableOn::Tag.joins(:taggings).select('tags.id, tags.name, COUNT(taggings.id) as taggings_count').group('tags.id, tags.name').where("taggings.taggable_type = ? and taggings.context = ? ",self.name,'tags') + ActsAsTaggableOn::Tag.joins(:taggings).select('tags.id, tags.name, COUNT(taggings.id) as taggings_count').group('tags.id, tags.name').where('taggings.taggable_type = ? and taggings.context = ? ', name, 'tags') end - end diff --git a/app/models/barrier.rb b/app/models/barrier.rb index 2f4f762fb..ab874c685 100644 --- a/app/models/barrier.rb +++ b/app/models/barrier.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Barrier < ApplicationRecord has_many :service_stage_barriers has_many :service_stages, through: :service_stage_barriers diff --git a/app/models/collection.rb b/app/models/collection.rb index 2f80146eb..1016faf48 100644 --- a/app/models/collection.rb +++ b/app/models/collection.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Collection < ApplicationRecord include AASM @@ -13,7 +15,7 @@ class Collection < ApplicationRecord validates :reflection, length: { maximum: 5000 } def omb_control_number - "omb_control_number" + 'omb_control_number' end aasm do @@ -24,11 +26,11 @@ def omb_control_number state :archived event :submit do - transitions from: [:draft, :change_requested], to: :submitted + transitions from: %i[draft change_requested], to: :submitted end event :publish do - transitions from: :submitted, to: :published + transitions from: :submitted, to: :published end event :request_change do @@ -42,13 +44,12 @@ def omb_control_number event :reset do transitions to: :draft end - end def duplicate!(new_user:) - new_collection = self.dup + new_collection = dup new_collection.user = new_user - new_collection.name = "Copy of #{self.name}" + new_collection.name = "Copy of #{name}" new_collection.start_date = nil new_collection.end_date = nil new_collection.reflection = nil @@ -57,7 +58,7 @@ def duplicate!(new_user:) new_collection.save # Loop OMB CX Reporting Collections to create them for new_collection - self.omb_cx_reporting_collections.each do |omb_cx_reporting_collection| + omb_cx_reporting_collections.each do |omb_cx_reporting_collection| new_omb_cx_reporting_collection = omb_cx_reporting_collection.dup new_omb_cx_reporting_collection.collection = new_collection new_omb_cx_reporting_collection.volume_of_customers = 0 @@ -121,7 +122,7 @@ def duplicate!(new_user:) new_omb_cx_reporting_collection.save! end - return new_collection + new_collection end def totals @@ -129,7 +130,7 @@ def totals @volume_of_customers_provided_survey_opportunity = 0 @volume_of_respondents = 0 - self.omb_cx_reporting_collections.each do |omb_cx_reporting_collection| + omb_cx_reporting_collections.each do |omb_cx_reporting_collection| @volume_of_customers += omb_cx_reporting_collection.volume_of_customers.to_i @volume_of_customers_provided_survey_opportunity += omb_cx_reporting_collection.volume_of_customers_provided_survey_opportunity.to_i @volume_of_respondents += omb_cx_reporting_collection.volume_of_respondents.to_i @@ -138,19 +139,13 @@ def totals { volume_of_customers: @volume_of_customers, volume_of_customers_provided_survey_opportunity: @volume_of_customers_provided_survey_opportunity, - volume_of_respondents: @volume_of_respondents + volume_of_respondents: @volume_of_respondents, } end - def organization_name - self.organization.name - end + delegate :name, to: :organization, prefix: true - def organization_abbreviation - self.organization.abbreviation - end + delegate :abbreviation, to: :organization, prefix: true - def service_provider_name - self.service_provider.name - end + delegate :name, to: :service_provider, prefix: true end diff --git a/app/models/digital_product.rb b/app/models/digital_product.rb index ab8ef9c54..77ff8ded6 100644 --- a/app/models/digital_product.rb +++ b/app/models/digital_product.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'json' require 'open-uri' @@ -38,20 +40,20 @@ class DigitalProduct < ApplicationRecord def self.load_digital_products DigitalProduct.delete_all - url = "https://usdigitalregistry.digitalgov.gov/digital-registry/v1/mobile_apps?page_size=10000" + url = 'https://usdigitalregistry.digitalgov.gov/digital-registry/v1/mobile_apps?page_size=10000' response = URI.open(url).read json = JSON.parse(response) - products = json["results"] - puts "Found #{products.size} Products" + products = json['results'] + Rails.logger.debug { "Found #{products.size} Products" } products.each do |product| hash = { - name: product["name"], - short_description: product["short_description"], - long_description: product["long_description"], - language: product["language"], + name: product['name'], + short_description: product['short_description'], + long_description: product['long_description'], + language: product['language'], organization: Organization.first, user: User.first, @@ -60,25 +62,25 @@ def self.load_digital_products # agencies = [] # tags = [] # versions = [] - # { - # "store_url": "http://itunes.apple.com/us/app/..., - # "platform": "iOS", - # "version_number": "", - # "publish_date": "2012-10-04T00:00:00.000Z", - # "screenshot": "", - # "device": "App - Phone/Tablet", - # "average_rating": "4.5", - # "number_of_ratings": 21 - # } + # { + # "store_url": "http://itunes.apple.com/us/app/..., + # "platform": "iOS", + # "version_number": "", + # "publish_date": "2012-10-04T00:00:00.000Z", + # "screenshot": "", + # "device": "App - Phone/Tablet", + # "average_rating": "4.5", + # "number_of_ratings": 21 + # } # icon_url } DigitalProduct.create!(hash) end - puts "Loaded DigitalServiceAccounts" + Rails.logger.debug 'Loaded DigitalServiceAccounts' end def sponsoring_agencies - Organization.where(id: self.organization_list) + Organization.where(id: organization_list) end end diff --git a/app/models/digital_product_version.rb b/app/models/digital_product_version.rb index ec402e10c..ce8a92ab0 100644 --- a/app/models/digital_product_version.rb +++ b/app/models/digital_product_version.rb @@ -1,7 +1,8 @@ +# frozen_string_literal: true + class DigitalProductVersion < ApplicationRecord belongs_to :digital_product - validates_presence_of :platform - validates_presence_of :version_number - + validates :platform, presence: true + validates :version_number, presence: true end diff --git a/app/models/digital_service_account.rb b/app/models/digital_service_account.rb index 8f79078bf..977c1e4f2 100644 --- a/app/models/digital_service_account.rb +++ b/app/models/digital_service_account.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'json' require 'open-uri' @@ -19,7 +21,7 @@ class DigitalServiceAccount < ApplicationRecord state :archived event :submit do - transitions from: [:created, :updated], to: :submitted + transitions from: %i[created updated], to: :submitted end event :publish do transitions from: [:submitted], to: :published @@ -36,7 +38,7 @@ class DigitalServiceAccount < ApplicationRecord end def sponsoring_agencies - Organization.where(id: self.organization_list) + Organization.where(id: organization_list) end def contacts @@ -46,24 +48,24 @@ def contacts def self.load_service_accounts DigitalServiceAccount.delete_all - url = "https://usdigitalregistry.digitalgov.gov/digital-registry/v1/social_media?page_size=10000" + url = 'https://usdigitalregistry.digitalgov.gov/digital-registry/v1/social_media?page_size=10000' response = URI.open(url).read json = JSON.parse(response) - accounts = json["results"] - puts "Found #{accounts.size} Accounts" + accounts = json['results'] + Rails.logger.debug { "Found #{accounts.size} Accounts" } accounts.each do |account| hash = { - name: account["service_display_name"], - short_description: account["short_description"], - long_description: account["long_description"], - service_url: account["service_url"], - language: account["language"], - account: account["account"], - service: account["service_key"], + name: account['service_display_name'], + short_description: account['short_description'], + long_description: account['long_description'], + service_url: account['service_url'], + language: account['language'], + account: account['account'], + service: account['service_key'], organization: Organization.first, user: User.first, @@ -78,6 +80,6 @@ def self.load_service_accounts DigitalServiceAccount.create!(hash) end - puts "Loaded DigitalServiceAccount" + Rails.logger.debug 'Loaded DigitalServiceAccount' end end diff --git a/app/models/event.rb b/app/models/event.rb index a3a9f5e09..07b2e4015 100644 --- a/app/models/event.rb +++ b/app/models/event.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'csv' class Event < ApplicationRecord @@ -71,7 +73,7 @@ class Generic } def self.log_event(ename, otype, oid, desc, uid = nil) - e = self.new + e = new e.name = ename e.object_type = otype e.object_id = oid @@ -89,20 +91,20 @@ def self.valid_events end def self.to_csv - attributes = [ - :name, - :object_type, - :object_id, - :description, - :user_id, - :created_at, - :updated_at + attributes = %i[ + name + object_type + object_id + description + user_id + created_at + updated_at ] CSV.generate(headers: true) do |csv| csv << attributes - Event.all.each do |event| + Event.all.find_each do |event| csv << attributes.map { |attr| event.send(attr) } end end diff --git a/app/models/form.rb b/app/models/form.rb index dc6db1f58..808ba19f2 100644 --- a/app/models/form.rb +++ b/app/models/form.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'csv' class Form < ApplicationRecord @@ -15,7 +17,7 @@ class Form < ApplicationRecord has_many :users, through: :user_roles, primary_key: :form_id validates :name, presence: true - validates_length_of :disclaimer_text, in: 0..500, allow_blank: true + validates :disclaimer_text, length: { in: 0..500, allow_blank: true } validates :delivery_method, presence: true validates :anticipated_delivery_count, numericality: true, allow_nil: true validate :omb_number_with_expiration_date @@ -23,6 +25,7 @@ class Form < ApplicationRecord validate :ensure_modal_text before_create :set_uuid + after_create :create_first_form_section before_destroy :ensure_no_responses scope :non_templates, -> { where(template: false) } @@ -31,59 +34,51 @@ class Form < ApplicationRecord mount_uploader :logo, LogoUploader def target_for_delivery_method - if self.delivery_method == "custom-button-modal" || self.delivery_method == "inline" - if self.element_selector == "" - errors.add(:element_selector, "can't be blank for an inline form") - end - end + errors.add(:element_selector, "can't be blank for an inline form") if (delivery_method == 'custom-button-modal' || delivery_method == 'inline') && (element_selector == '') end def ensure_modal_text - if self.delivery_method == "modal" - if self.modal_button_text.empty? - errors.add(:modal_button_text, "can't be blank for an modal form") - end - end + errors.add(:modal_button_text, "can't be blank for an modal form") if delivery_method == 'modal' && modal_button_text.empty? end def ensure_no_responses - if submissions.count > 0 - errors.add(:response_count_error, "This form cannot be deleted because it has responses") + if submissions.count.positive? + errors.add(:response_count_error, 'This form cannot be deleted because it has responses') throw(:abort) end end - after_create :create_first_form_section - after_commit do |form| FormCache.invalidate(form.short_uuid) end DELIVERY_METHODS = [ - ["touchpoints-hosted-only", "Hosted only on the Touchpoints site"], - ["modal", "Tab button & modal"], - ["custom-button-modal", "Custom button & modal"], - ["inline", "Embedded inline on your site"] - ] - + ['touchpoints-hosted-only', 'Hosted only on the Touchpoints site'], + ['modal', 'Tab button & modal'], + ['custom-button-modal', 'Custom button & modal'], + ['inline', 'Embedded inline on your site'], + ].freeze def suppress_submit_button - self.questions.collect(&:question_type).include?("yes_no_buttons") || self.questions.collect(&:question_type).include?("custom_text_display") + questions.collect(&:question_type).include?('yes_no_buttons') || questions.collect(&:question_type).include?('custom_text_display') end def self.find_by_short_uuid(short_uuid) return nil unless short_uuid && short_uuid.length == 8 - where("uuid LIKE ?", "#{short_uuid}%").first + + where('uuid LIKE ?', "#{short_uuid}%").first end def self.find_by_legacy_touchpoints_id(id) return nil unless id && id.length < 4 + where(legacy_touchpoint_id: id).first end def self.find_by_legacy_touchpoints_uuid(short_uuid) return nil unless short_uuid && short_uuid.length == 8 - where("legacy_touchpoint_uuid LIKE ?", "#{short_uuid}%").first + + where('legacy_touchpoint_uuid LIKE ?', "#{short_uuid}%").first end def to_param @@ -95,11 +90,11 @@ def short_uuid end def send_notifications? - self.notification_emails.present? + notification_emails.present? end def create_first_form_section - self.form_sections.create(title: (I18n.t 'form.page_1'), position: 1) + form_sections.create(title: (I18n.t 'form.page_1'), position: 1) end # def to_param @@ -110,20 +105,19 @@ def short_uuid uuid[0..7] end - aasm do state :in_development, initial: true state :live # manual state :archived # after End Date, or manual event :develop do - transitions from: [:live, :archived], to: :in_development + transitions from: %i[live archived], to: :in_development end event :publish do transitions from: [:in_development], to: :live end event :archive do - transitions from: [:in_development, :live], to: :archived + transitions from: %i[in_development live], to: :archived end event :reset do transitions to: :in_development @@ -131,16 +125,16 @@ def short_uuid end def transitionable_states - self.aasm.states(permitted: true) + aasm.states(permitted: true) end def all_states - self.aasm.states + aasm.states end def duplicate!(new_user:) - new_form = self.dup - new_form.name = "Copy of #{self.name}" + new_form = dup + new_form.name = "Copy of #{name}" new_form.title = new_form.name new_form.survey_form_activations = 0 new_form.response_count = 0 @@ -158,7 +152,7 @@ def duplicate!(new_user:) new_form.form_sections.destroy_all # Loop Form Sections to create them for new_form - self.form_sections.each do |section| + form_sections.each do |section| new_form_section = section.dup new_form_section.form = new_form new_form_section.save @@ -179,36 +173,36 @@ def duplicate!(new_user:) end end - return new_form + new_form end def check_expired - if !self.archived? and self.expiration_date.present? and self.expiration_date <= Date.today - self.archive! - Event.log_event(Event.names[:form_archived], "Touchpoint",self.id, "Touchpoint #{self.name} archived on #{Date.today}") + if !archived? && expiration_date.present? && (expiration_date <= Date.today) + archive! + Event.log_event(Event.names[:form_archived], 'Touchpoint', id, "Touchpoint #{name} archived on #{Date.today}") end end def set_uuid - self.uuid = SecureRandom.uuid if !self.uuid.present? + self.uuid = SecureRandom.uuid if uuid.blank? end def deployable_form? - self.live? + live? end # returns javascript text that can be used standalone # or injected into a GTM Container Tag def touchpoints_js_string - ApplicationController.new.render_to_string(partial: "components/widget/fba", formats: :js, locals: { touchpoint: self }) + ApplicationController.new.render_to_string(partial: 'components/widget/fba', formats: :js, locals: { touchpoint: self }) end def to_csv(start_date: nil, end_date: nil) - non_flagged_submissions = self.submissions.non_flagged.where("created_at >= ?", start_date).where("created_at <= ?", end_date).order("created_at") - return nil unless non_flagged_submissions.present? + non_flagged_submissions = submissions.non_flagged.where('created_at >= ?', start_date).where('created_at <= ?', end_date).order('created_at') + return nil if non_flagged_submissions.blank? - header_attributes = self.hashed_fields_for_export.values - attributes = self.fields_for_export + header_attributes = hashed_fields_for_export.values + attributes = fields_for_export CSV.generate(headers: true) do |csv| csv << header_attributes @@ -220,7 +214,7 @@ def to_csv(start_date: nil, end_date: nil) end def user_role?(user:) - role = self.user_roles.find_by_user_id(user.id) + role = user_roles.find_by_user_id(user.id) role.present? ? role.role : nil end @@ -229,26 +223,26 @@ def user_role?(user:) # Generates 1 of 2 exported files for the A11 # This is a one record metadata file def to_a11_header_csv(start_date:, end_date:) - non_flagged_submissions = self.submissions.non_flagged.where("created_at >= ?", start_date).where("created_at <= ?", end_date) - return nil unless non_flagged_submissions.present? + non_flagged_submissions = submissions.non_flagged.where('created_at >= ?', start_date).where('created_at <= ?', end_date) + return nil if non_flagged_submissions.blank? header_attributes = [ - "submission comment", - "survey_instrument_reference", - "agency_poc_name", - "agency_poc_email", - "department", - "bureau", - "service", - "transaction_point", - "mode", - "start_date", - "end_date", - "total_volume", - "survey_opp_volume", - "response_count", - "OMB_control_number", - "federal_register_url" + 'submission comment', + 'survey_instrument_reference', + 'agency_poc_name', + 'agency_poc_email', + 'department', + 'bureau', + 'service', + 'transaction_point', + 'mode', + 'start_date', + 'end_date', + 'total_volume', + 'survey_opp_volume', + 'response_count', + 'OMB_control_number', + 'federal_register_url', ] CSV.generate(headers: true) do |csv| @@ -278,22 +272,22 @@ def to_a11_header_csv(start_date:, end_date:) # Generates the 2nd of 2 exported files for the A11 # This is a 7 record detail file; one for each question def to_a11_submissions_csv(start_date:, end_date:) - non_flagged_submissions = self.submissions.non_flagged.where("created_at >= ?", start_date).where("created_at <= ?", end_date) - return nil unless non_flagged_submissions.present? - - header_attributes = [ - "standardized_question_number", - "standardized_question_identifier", - "customized_question_text", - "likert_scale_1", - "likert_scale_2", - "likert_scale_3", - "likert_scale_4", - "likert_scale_5", - "response_volume", - "notes", - "start_date", - "end_date" + non_flagged_submissions = submissions.non_flagged.where('created_at >= ?', start_date).where('created_at <= ?', end_date) + return nil if non_flagged_submissions.blank? + + header_attributes = %w[ + standardized_question_number + standardized_question_identifier + customized_question_text + likert_scale_1 + likert_scale_2 + likert_scale_3 + likert_scale_4 + likert_scale_5 + response_volume + notes + start_date + end_date ] @hash = { @@ -303,16 +297,14 @@ def to_a11_submissions_csv(start_date:, end_date:) answer_04: Hash.new(0), answer_05: Hash.new(0), answer_06: Hash.new(0), - answer_07: Hash.new(0) + answer_07: Hash.new(0), } # Aggregate likert scale responses non_flagged_submissions.each do |submission| - @hash.keys.each do |field| + @hash.each_key do |field| response = submission.send(field) - if response.present? - @hash[field][submission.send(field)] += 1 - end + @hash[field][submission.send(field)] += 1 if response.present? end end @@ -321,40 +313,41 @@ def to_a11_submissions_csv(start_date:, end_date:) csv << header_attributes @hash.each_pair do |key, values| - @question_text = "123" - if key == :answer_01 + @question_text = '123' + case key + when :answer_01 question = questions.where(answer_field: key).first - response_volume = values.values.collect { |v| v.to_i }.sum + response_volume = values.values.collect(&:to_i).sum @question_text = question.text standardized_question_number = 1 - elsif key == :answer_02 + when :answer_02 question = questions.where(answer_field: key).first - response_volume = values.values.collect { |v| v.to_i }.sum + response_volume = values.values.collect(&:to_i).sum @question_text = question.text standardized_question_number = 2 - elsif key == :answer_03 + when :answer_03 question = questions.where(answer_field: key).first - response_volume = values.values.collect { |v| v.to_i }.sum + response_volume = values.values.collect(&:to_i).sum @question_text = question.text standardized_question_number = 3 - elsif key == :answer_04 + when :answer_04 question = questions.where(answer_field: key).first - response_volume = values.values.collect { |v| v.to_i }.sum + response_volume = values.values.collect(&:to_i).sum @question_text = question.text standardized_question_number = 4 - elsif key == :answer_05 + when :answer_05 question = questions.where(answer_field: key).first - response_volume = values.values.collect { |v| v.to_i }.sum + response_volume = values.values.collect(&:to_i).sum @question_text = question.text standardized_question_number = 5 - elsif key == :answer_06 + when :answer_06 question = questions.where(answer_field: key).first - response_volume = values.values.collect { |v| v.to_i }.sum + response_volume = values.values.collect(&:to_i).sum @question_text = question.text standardized_question_number = 6 - elsif key == :answer_07 + when :answer_07 question = questions.where(answer_field: key).first - response_volume = values.values.collect { |v| v.to_i }.sum + response_volume = values.values.collect(&:to_i).sum @question_text = question.text standardized_question_number = 7 end @@ -363,46 +356,45 @@ def to_a11_submissions_csv(start_date:, end_date:) standardized_question_number, key, @question_text, - values["1"], - values["2"], - values["3"], - values["4"], - values["5"], + values['1'], + values['2'], + values['3'], + values['4'], + values['5'], response_volume, - "", # Empty field for the user to enter their own notes + '', # Empty field for the user to enter their own notes start_date, - end_date + end_date, ] end - end end def fields_for_export - self.hashed_fields_for_export.keys + hashed_fields_for_export.keys end # TODO: Move to /models/submission.rb # a map of { Submission field names (to access the data) => the Header (to display) } def hashed_fields_for_export hash = { - uuid: "UUID" + uuid: 'UUID', } - self.ordered_questions.map { |q| hash[q.answer_field] = q.text } + ordered_questions.map { |q| hash[q.answer_field] = q.text } hash.merge!({ - location_code: "Location Code", - user_agent: "User Agent", - page: "Page", - referer: "Referrer", - created_at: "Created At" - }) - - if self.organization.enable_ip_address? + location_code: 'Location Code', + user_agent: 'User Agent', + page: 'Page', + referer: 'Referrer', + created_at: 'Created At', + }) + + if organization.enable_ip_address? hash.merge!({ - ip_address: "IP Address" - }) + ip_address: 'IP Address', + }) end hash @@ -410,41 +402,36 @@ def hashed_fields_for_export def ordered_questions array = [] - self.form_sections.each do |section| + form_sections.each do |section| array.concat(section.questions.ordered.entries) end array end def omb_number_with_expiration_date - if omb_approval_number.present? && !expiration_date.present? - errors.add(:expiration_date, "required with an OMB Number") - end - if expiration_date.present? && !omb_approval_number.present? - errors.add(:omb_approval_number, "required with an Expiration Date") - end + errors.add(:expiration_date, 'required with an OMB Number') if omb_approval_number.present? && expiration_date.blank? + errors.add(:omb_approval_number, 'required with an Expiration Date') if expiration_date.present? && omb_approval_number.blank? end def completion_rate - if self.survey_form_activations == 0 - "N/A" + if survey_form_activations.zero? + 'N/A' else - "#{((self.response_count / self.survey_form_activations.to_f) * 100).round(0)}%" + "#{((response_count / survey_form_activations.to_f) * 100).round(0)}%" end end def average_answer(answer) - responses = self.submissions.select(answer).where("#{answer} is not null").collect(&answer) - responses = responses.map { |string| string.to_i } + responses = submissions.select(answer).where("#{answer} is not null").collect(&answer) + responses = responses.map(&:to_i) response_total = responses.sum responses_count = responses.size average = response_total / responses_count.to_f { - response_total: response_total, + response_total:, response_count: responses_count, - average: average.round(2) + average: average.round(2), } end - end diff --git a/app/models/form_cache.rb b/app/models/form_cache.rb index fcb9b061a..f9ca4841f 100644 --- a/app/models/form_cache.rb +++ b/app/models/form_cache.rb @@ -1,22 +1,23 @@ -class FormCache +# frozen_string_literal: true - NAMESPACE = "namespace:form-" +class FormCache + NAMESPACE = 'namespace:form-' # Cache Store fetch will return the cached item # or run the block if the cached item does not exist def self.fetch(short_uuid) - return false unless short_uuid.present? + return false if short_uuid.blank? Rails.cache.fetch(NAMESPACE + short_uuid.to_s, expires_in: 1.day) do # Pull in all objects required to build a touchpoint - Form.includes([:questions, form_sections: [questions: [:question_options]]], :organization).find_by_short_uuid(short_uuid) + Form.includes([:questions, { form_sections: [questions: [:question_options]] }], :organization).find_by_short_uuid(short_uuid) end end def self.fetch_a11_analysis(short_uuid) - return false unless short_uuid.present? + return false if short_uuid.blank? - Rails.cache.fetch(NAMESPACE + '-a11-analysis-' + short_uuid.to_s, expires_in: 1.day) do + Rails.cache.fetch("#{NAMESPACE}-a11-analysis-#{short_uuid}", expires_in: 1.day) do form = Form.find_by_short_uuid(short_uuid) report = {} report[:answer_01] = form.average_answer(:answer_01) @@ -31,16 +32,15 @@ def self.fetch_a11_analysis(short_uuid) end def self.fetch_performance_gov_analysis(short_uuid) - return false unless short_uuid.present? + return false if short_uuid.blank? - Rails.cache.fetch(NAMESPACE + '-performance-gov-analysis-' + short_uuid.to_s, expires_in: 1.day) do + Rails.cache.fetch("#{NAMESPACE}-performance-gov-analysis-#{short_uuid}", expires_in: 1.day) do form = Form.find_by_short_uuid(short_uuid) report = {} - report[:quarterly_submissions] = form.submissions.order(:created_at).entries.map { |e| e.attributes.merge(quarter: e.created_at.beginning_of_quarter.to_date, end_of_quarter: e.created_at.end_of_quarter ) } - report[:quarters] = report[:quarterly_submissions].collect { |e| e[:quarter] }.uniq + report[:quarterly_submissions] = form.submissions.order(:created_at).entries.map { |e| e.attributes.merge(quarter: e.created_at.beginning_of_quarter.to_date, end_of_quarter: e.created_at.end_of_quarter) } + report[:quarters] = report[:quarterly_submissions].pluck(:quarter).uniq report end - end def self.invalidate(short_uuid) @@ -48,8 +48,7 @@ def self.invalidate(short_uuid) end def self.invalidate_reports(short_uuid) - Rails.cache.delete(NAMESPACE + '-performance-gov-analysis-' + short_uuid.to_s) - Rails.cache.delete(NAMESPACE + '-a11-analysis-' + short_uuid.to_s) + Rails.cache.delete("#{NAMESPACE}-performance-gov-analysis-#{short_uuid}") + Rails.cache.delete("#{NAMESPACE}-a11-analysis-#{short_uuid}") end - end diff --git a/app/models/form_section.rb b/app/models/form_section.rb index a152cc44b..b964ac467 100644 --- a/app/models/form_section.rb +++ b/app/models/form_section.rb @@ -1,11 +1,12 @@ +# frozen_string_literal: true + class FormSection < ApplicationRecord belongs_to :form has_many :questions validates :position, presence: true - - after_commit do | form_section | + after_commit do |form_section| FormCache.invalidate(form_section.form.short_uuid) if form_section.form.present? end @@ -14,10 +15,9 @@ class FormSection < ApplicationRecord default_scope { order(position: :asc) } def ensure_no_questions - if questions.count > 0 - errors.add(:question_count_error, "This form section cannot be deleted because it still has one or more questions") + if questions.count.positive? + errors.add(:question_count_error, 'This form section cannot be deleted because it still has one or more questions') throw(:abort) end end - end diff --git a/app/models/goal.rb b/app/models/goal.rb index 8157f58a7..267259860 100644 --- a/app/models/goal.rb +++ b/app/models/goal.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Goal < ApplicationRecord belongs_to :organization has_many :milestones @@ -40,18 +42,14 @@ class Goal < ApplicationRecord 'Transportation infrastructure', 'Veterens benefits & services', 'Workforce benefits & services', - 'Workforce development & employment' - ] + 'Workforce development & employment', + ].freeze def subgoals - Goal.where(parent_id: self.id) + Goal.where(parent_id: id) end - def organization_name - self.organization.name - end + delegate :name, to: :organization, prefix: true - def organization_abbreviation - self.organization.abbreviation - end + delegate :abbreviation, to: :organization, prefix: true end diff --git a/app/models/goal_target.rb b/app/models/goal_target.rb index f99162e39..c76019cbf 100644 --- a/app/models/goal_target.rb +++ b/app/models/goal_target.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class GoalTarget < ApplicationRecord belongs_to :goal diff --git a/app/models/legacy_touchpoint_url_map.rb b/app/models/legacy_touchpoint_url_map.rb index a817c47bc..760d9fde2 100644 --- a/app/models/legacy_touchpoint_url_map.rb +++ b/app/models/legacy_touchpoint_url_map.rb @@ -1,16 +1,13 @@ -class LegacyTouchpointUrlMap +# frozen_string_literal: true +class LegacyTouchpointUrlMap ## Create a hash map of legacy Touchpoint id and short_uuid routes to new Form.short_uuid def self.map legacy_map = {} - Form.all.each do |form| - if form.legacy_touchpoint_id - legacy_map[form.legacy_touchpoint_id.to_s] = form.short_uuid - end + Form.all.find_each do |form| + legacy_map[form.legacy_touchpoint_id.to_s] = form.short_uuid if form.legacy_touchpoint_id - if form.legacy_touchpoint_uuid - legacy_map[form.legacy_touchpoint_uuid[0..7].to_s] = form.short_uuid - end + legacy_map[form.legacy_touchpoint_uuid[0..7].to_s] = form.short_uuid if form.legacy_touchpoint_uuid end legacy_map diff --git a/app/models/milestone.rb b/app/models/milestone.rb index 45f623ce7..f45671ce6 100644 --- a/app/models/milestone.rb +++ b/app/models/milestone.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Milestone < ApplicationRecord belongs_to :organization belongs_to :goal, optional: true diff --git a/app/models/objective.rb b/app/models/objective.rb index 0e1f898a4..78486a482 100644 --- a/app/models/objective.rb +++ b/app/models/objective.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Objective < ApplicationRecord belongs_to :organization belongs_to :goal @@ -7,6 +9,6 @@ class Objective < ApplicationRecord validates :name, presence: true def organization_name - self.organization ? self.organization.name : nil + organization ? organization.name : nil end end diff --git a/app/models/offering.rb b/app/models/offering.rb index 850ae0b11..be86db45f 100644 --- a/app/models/offering.rb +++ b/app/models/offering.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + class Offering < ApplicationRecord belongs_to :service, optional: true acts_as_taggable_on :personas def offering_personas - Persona.where(id: self.persona_list) + Persona.where(id: persona_list) end end diff --git a/app/models/omb_cx_reporting_collection.rb b/app/models/omb_cx_reporting_collection.rb index e359a2c7d..5abd31efd 100644 --- a/app/models/omb_cx_reporting_collection.rb +++ b/app/models/omb_cx_reporting_collection.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class OmbCxReportingCollection < ApplicationRecord belongs_to :collection belongs_to :service @@ -11,19 +13,19 @@ class OmbCxReportingCollection < ApplicationRecord end def answer_points(question:) - self.send("#{question}_1") * 1.0 + - self.send("#{question}_2") * 2.0 + - self.send("#{question}_3") * 3.0 + - self.send("#{question}_4") * 4.0 + - self.send("#{question}_5") * 5.0 + (send("#{question}_1") * 1.0) + + (send("#{question}_2") * 2.0) + + (send("#{question}_3") * 3.0) + + (send("#{question}_4") * 4.0) + + (send("#{question}_5") * 5.0) end def omb_control_number - super || "OMB Control Number" + super || 'OMB Control Number' end def federal_register_url - super || "Federal Register URL" + super || 'Federal Register URL' end def q1_point_scale @@ -104,11 +106,11 @@ def q11_point_scale end def question_total(question: nil) - self.send("#{question}_1") + - self.send("#{question}_2") + - self.send("#{question}_3") + - self.send("#{question}_4") + - self.send("#{question}_5") + send("#{question}_1") + + send("#{question}_2") + + send("#{question}_3") + + send("#{question}_4") + + send("#{question}_5") end def q1_total @@ -156,44 +158,24 @@ def q11_total end def volume_total - self.q1_total + self.q2_total + self.q3_total + self.q4_total + self.q5_total + self.q6_total + self.q7_total + self.q8_total + self.q9_total + self.q10_total + self.q11_total - end - - def organization - self.collection.organization + q1_total + q2_total + q3_total + q4_total + q5_total + q6_total + q7_total + q8_total + q9_total + q10_total + q11_total end - def organization_id - organization.id - end - - def organization_name - organization.name - end + delegate :organization, to: :collection - def organization_abbreviation - organization.abbreviation - end + delegate :id, to: :organization, prefix: true - def collection_name - self.collection.name - end + delegate :name, to: :organization, prefix: true - def collection_year - self.collection.year - end + delegate :abbreviation, to: :organization, prefix: true - def collection_quarter - self.collection.quarter - end + delegate :name, to: :collection, prefix: true - def service_name - self.service.name - end + delegate :year, to: :collection, prefix: true - def service_slug - self.service.service_slug - end + delegate :quarter, to: :collection, prefix: true + delegate :name, to: :service, prefix: true + delegate :service_slug, to: :service end diff --git a/app/models/organization.rb b/app/models/organization.rb index a3bd59066..c84b796e0 100644 --- a/app/models/organization.rb +++ b/app/models/organization.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + class Organization < ApplicationRecord acts_as_taggable_on :tags - + has_many :users has_many :services has_many :forms @@ -19,7 +21,7 @@ class Organization < ApplicationRecord validates :abbreviation, uniqueness: true def slug - self.abbreviation.downcase + abbreviation.downcase end def to_param diff --git a/app/models/persona.rb b/app/models/persona.rb index dcd5ed1a3..062ff320f 100644 --- a/app/models/persona.rb +++ b/app/models/persona.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + class Persona < ApplicationRecord validates :name, presence: true has_paper_trail def websites - Website.tagged_with(self.id, on: :personas) + Website.tagged_with(id, on: :personas) end end diff --git a/app/models/pra_form.rb b/app/models/pra_form.rb index 0c70cd019..8ef29265a 100644 --- a/app/models/pra_form.rb +++ b/app/models/pra_form.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class PraForm def self.part_a(form:) organization = form.organization @@ -23,7 +25,7 @@ def self.part_a(form:) end docx.style do - id 'indented-p' # sets the internal identifier for the style. + id 'indented-p' # sets the internal identifier for the style. name 'heading 1' # sets the friendly name of the style. type 'paragraph' # sets the style type. accepts `paragraph` or `character` # font 'Palantino' # sets the font family. @@ -31,7 +33,7 @@ def self.part_a(form:) # size 28 # sets the font size. units in half points. # bold false # sets the font weight. # italic false # sets the font style. - underline true # sets whether or not to underline the text. + underline true # sets whether or not to underline the text. # caps false # sets whether or not text should be rendered in all capital letters. # align :left # sets the alignment. accepts :left, :center, :right, and :both. # line 360 # sets the line height. units in twips. @@ -58,8 +60,8 @@ def self.part_a(form:) text 'FOR PAPERWORK REDUCTION ACT SUBMISSION' end docx.p do - text "Clearance for Customer Experience Feedback Survey in Support of OMB Circular A-11 Section 280: Centralized Feedback Survey Administered by the General Services Administration on behalf of " - text organization.name, underline: true, highlight_color: "yellow" + text 'Clearance for Customer Experience Feedback Survey in Support of OMB Circular A-11 Section 280: Centralized Feedback Survey Administered by the General Services Administration on behalf of ' + text organization.name, underline: true, highlight_color: 'yellow' br end @@ -79,11 +81,11 @@ def self.part_a(form:) text 'In March 2018, the Administration of President Trump launched the President’s Management Agenda (PMA) and established new Cross-Agency Priority (CAP) Goals. Excellent service was established as a core component of the mission, service, stewardship model that frames the entire PMA, embedding a customer-focused approach in all of the PMA’s initiatives. This model was also included in the 2018 update of the Federal Performance Framework in Circular A-11, ensuring ‘excellent service’ as a focus in future agency strategic planning efforts. The PMA included a CAP Goal on Improving Customer Experience with Federal Services, with a primary strategy to drive improvements within 25 of the nation’s highest impact programs. This effort is supported by an interagency team and guidance in Circular A-11 requiring the collection of customer feedback data and increasing the use of industry best practices to conduct customer research.' br br - text "These Presidential actions and requirements establish an ongoing process of collecting customer insights and using them to improve services. This new request will enable " - text organization.name, underline: true, highlight_color: "yellow" - text " (hereafter “the Agency”) to act in accordance with OMB Circular A-11 Section 280 to ultimately transform the experience of its customers to improve both efficiency and mission delivery, and increase accountability by communicating about these efforts with the public. These collections allow for ongoing, collaborative and actionable communications between " - text organization.name, underline: true, highlight_color: "yellow" - text " and its customers and stakeholders. it will also allow feedback to contribute directly to the improvement of program management." + text 'These Presidential actions and requirements establish an ongoing process of collecting customer insights and using them to improve services. This new request will enable ' + text organization.name, underline: true, highlight_color: 'yellow' + text ' (hereafter “the Agency”) to act in accordance with OMB Circular A-11 Section 280 to ultimately transform the experience of its customers to improve both efficiency and mission delivery, and increase accountability by communicating about these efforts with the public. These collections allow for ongoing, collaborative and actionable communications between ' + text organization.name, underline: true, highlight_color: 'yellow' + text ' and its customers and stakeholders. it will also allow feedback to contribute directly to the improvement of program management.' br end diff --git a/app/models/question.rb b/app/models/question.rb index 72de4e5d5..a2ae71eb8 100644 --- a/app/models/question.rb +++ b/app/models/question.rb @@ -1,36 +1,38 @@ +# frozen_string_literal: true + class Question < ApplicationRecord - belongs_to :form, required: true - belongs_to :form_section, required: true + belongs_to :form, optional: false + belongs_to :form_section, optional: false has_many :question_options, dependent: :destroy validates :question_type, presence: true validate :validate_question_types - validates_uniqueness_of :answer_field, scope: :form_id + validates :answer_field, uniqueness: { scope: :form_id } default_scope { order(position: :asc) } scope :ordered, -> { order(position: :asc) } - MAX_CHARACTERS = 100000 + MAX_CHARACTERS = 100_000 QUESTION_TYPES = [ # Standard elements - "text_field", - "text_email_field", - "text_phone_field", - "textarea", - "checkbox", - "radio_buttons", - "dropdown", + 'text_field', + 'text_email_field', + 'text_phone_field', + 'textarea', + 'checkbox', + 'radio_buttons', + 'dropdown', # Custom elements - "text_display", - "custom_text_display", - "states_dropdown", - "star_radio_buttons", - "thumbs_up_down_buttons", - "yes_no_buttons", - "hidden_field", - "date_select" - ] + 'text_display', + 'custom_text_display', + 'states_dropdown', + 'star_radio_buttons', + 'thumbs_up_down_buttons', + 'yes_no_buttons', + 'hidden_field', + 'date_select', + ].freeze validates :answer_field, presence: true validates :character_limit, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: MAX_CHARACTERS, allow_nil: true } @@ -40,13 +42,12 @@ class Question < ApplicationRecord end def max_length - return character_limit if character_limit.present? - MAX_CHARACTERS + return character_limit if character_limit.present? + + MAX_CHARACTERS end def validate_question_types - if !QUESTION_TYPES.include?(question_type) - errors.add(:question_type, "Invalid question type '#{question_type}'. Valid types include: #{QUESTION_TYPES.to_sentence}.") - end + errors.add(:question_type, "Invalid question type '#{question_type}'. Valid types include: #{QUESTION_TYPES.to_sentence}.") unless QUESTION_TYPES.include?(question_type) end end diff --git a/app/models/question_option.rb b/app/models/question_option.rb index 099a5b2ad..75a91ef5d 100644 --- a/app/models/question_option.rb +++ b/app/models/question_option.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class QuestionOption < ApplicationRecord belongs_to :question @@ -7,9 +9,7 @@ class QuestionOption < ApplicationRecord validates :position, presence: true def set_default_value_from_text - unless self.value? - self.value = self.text - end + self.value = text unless value? end after_commit do |question_option| diff --git a/app/models/role.rb b/app/models/role.rb index 4ada89de0..e8d16495b 100644 --- a/app/models/role.rb +++ b/app/models/role.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Role < ApplicationRecord has_and_belongs_to_many :users, join_table: :users_roles has_and_belongs_to_many :organizations, join_table: :organizations_roles diff --git a/app/models/scheduled_task.rb b/app/models/scheduled_task.rb index 3ba931490..e03c0152c 100644 --- a/app/models/scheduled_task.rb +++ b/app/models/scheduled_task.rb @@ -1,18 +1,16 @@ -class ScheduledTask - - def self.check_expiring_forms - forms = Form.where(expiration_date: Date.today + 7).or(Form.where(expiration_date: ScheduledTask.skip_weekends(Date.today))) - forms.each do |f| - UserMailer.form_expiring_notification(f).deliver_later - end - end +# frozen_string_literal: true - def self.skip_weekends(date, inc = 1) - date += inc - while date.wday == 0 || date.wday == 6 - date += inc - end - date - end +class ScheduledTask + def self.check_expiring_forms + forms = Form.where(expiration_date: Date.today + 7).or(Form.where(expiration_date: ScheduledTask.skip_weekends(Date.today))) + forms.each do |f| + UserMailer.form_expiring_notification(f).deliver_later + end + end + def self.skip_weekends(date, inc = 1) + date += inc + date += inc while date.wday.zero? || date.wday == 6 + date + end end diff --git a/app/models/service.rb b/app/models/service.rb index 2418a5ad4..ce371a9da 100644 --- a/app/models/service.rb +++ b/app/models/service.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'csv' class Service < ApplicationRecord @@ -11,7 +13,7 @@ class Service < ApplicationRecord has_many :omb_cx_reporting_collections has_many :collections, through: :omb_cx_reporting_collections has_many :forms - + acts_as_taggable_on :tags validates :name, presence: true @@ -47,9 +49,9 @@ class Service < ApplicationRecord end def create_default_service_stages - self.service_stages.create(position: 10, name: :start) - self.service_stages.create(position: 20, name: :process) - self.service_stages.create(position: 100, name: :end) + service_stages.create(position: 10, name: :start) + service_stages.create(position: 20, name: :process) + service_stages.create(position: 100, name: :end) end def create_roles @@ -59,13 +61,13 @@ def create_roles def owner?(user:) return false unless user - user.admin? || self.service_owner_id == user.id + user.admin? || service_owner_id == user.id end def service_owner - return nil unless self.service_owner_id + return nil unless service_owner_id - User.find_by_id(self.service_owner_id) + User.find_by_id(service_owner_id) end def service_managers @@ -73,23 +75,19 @@ def service_managers end def service_owner_email - service_owner && service_owner.try(:email) + service_owner&.try(:email) end - def organization_name - self.organization.name - end + delegate :name, to: :organization, prefix: true - def organization_abbreviation - self.organization.abbreviation - end + delegate :abbreviation, to: :organization, prefix: true def service_provider_name - self.service_provider ? self.service_provider.name : nil + service_provider ? service_provider.name : nil end def self.to_csv - services = Service.order("organizations.name").includes(:organization) + services = Service.order('organizations.name').includes(:organization) example_service_attributes = Service.new.attributes attributes = example_service_attributes.keys diff --git a/app/models/service_provider.rb b/app/models/service_provider.rb index f6a59f264..c0c449626 100644 --- a/app/models/service_provider.rb +++ b/app/models/service_provider.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class ServiceProvider < ApplicationRecord resourcify belongs_to :organization @@ -8,17 +10,17 @@ class ServiceProvider < ApplicationRecord validates :name, presence: true validates :slug, presence: true - scope :active, -> { where("inactive ISNULL or inactive = false") } + scope :active, -> { where('inactive ISNULL or inactive = false') } def service_provider_managers User.with_role(:service_provider_manager, self) end def organization_name - self.organization ? self.organization.name : nil + organization ? organization.name : nil end def organization_abbreviation - self.organization ? self.organization.abbreviation : nil + organization ? organization.abbreviation : nil end end diff --git a/app/models/service_stage.rb b/app/models/service_stage.rb index 2acf01311..cc354195e 100644 --- a/app/models/service_stage.rb +++ b/app/models/service_stage.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class ServiceStage < ApplicationRecord belongs_to :service belongs_to :persona, optional: true diff --git a/app/models/service_stage_barrier.rb b/app/models/service_stage_barrier.rb index a1b8a9e19..4744548e9 100644 --- a/app/models/service_stage_barrier.rb +++ b/app/models/service_stage_barrier.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class ServiceStageBarrier < ApplicationRecord belongs_to :service_stage belongs_to :barrier diff --git a/app/models/social_media_account.rb b/app/models/social_media_account.rb index 9bd3448d0..0b83dbdd3 100644 --- a/app/models/social_media_account.rb +++ b/app/models/social_media_account.rb @@ -1,33 +1,35 @@ +# frozen_string_literal: true + class SocialMediaAccount def self.list [ - "Disqus", - "Eventbrite", - "Facebook", - "Flickr", - "Foursquare", - "Giphy", - "Github", - "Google plus", - "Ideascale", - "Instagram", - "Linkedin", - "Livestream", - "Medium", - "Myspace", - "Pinterest", - "Reddit", - "Scribd", - "Slideshare", - "Socrata", - "Storify", - "Tumblr", - "Twitter", - "Uservoice", - "Ustream", - "Vimeo", - "Yelp", - "Youtube" + 'Disqus', + 'Eventbrite', + 'Facebook', + 'Flickr', + 'Foursquare', + 'Giphy', + 'Github', + 'Google plus', + 'Ideascale', + 'Instagram', + 'Linkedin', + 'Livestream', + 'Medium', + 'Myspace', + 'Pinterest', + 'Reddit', + 'Scribd', + 'Slideshare', + 'Socrata', + 'Storify', + 'Tumblr', + 'Twitter', + 'Uservoice', + 'Ustream', + 'Vimeo', + 'Yelp', + 'Youtube', ] end end diff --git a/app/models/submission.rb b/app/models/submission.rb index 563007909..259734052 100644 --- a/app/models/submission.rb +++ b/app/models/submission.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Submission < ApplicationRecord acts_as_taggable_on :tags include AASM @@ -9,9 +11,8 @@ class Submission < ApplicationRecord validates :uuid, uniqueness: true before_create :set_uuid - after_commit :send_notifications, on: :create - after_create :update_form + after_commit :send_notifications, on: :create scope :archived, -> { where(archived: true) } scope :non_archived, -> { where(archived: false) } @@ -31,7 +32,7 @@ class Submission < ApplicationRecord transitions from: [:acknowledged], to: :dispatched end event :respond do - transitions from: [:dispatched, :archived], to: :responded + transitions from: %i[dispatched archived], to: :responded end event :archive do transitions to: :archived @@ -44,52 +45,47 @@ class Submission < ApplicationRecord def validate_custom_form @valid_form_condition = false - questions = self.form.questions + questions = form.questions # Isolate questions that were answered - answered_questions = self.attributes.select { |key, value| value.present? } + answered_questions = attributes.select { |_key, value| value.present? } # Filter out all non-question attributes - answered_questions.delete("touchpoint_id") - answered_questions.delete("form_id") - answered_questions.delete("user_agent") - answered_questions.delete("page") - answered_questions.delete("ip_address") - answered_questions.delete("language") - answered_questions.delete("referer") + answered_questions.delete('touchpoint_id') + answered_questions.delete('form_id') + answered_questions.delete('user_agent') + answered_questions.delete('page') + answered_questions.delete('ip_address') + answered_questions.delete('language') + answered_questions.delete('referer') # For each question # Run Custom Validations questions.each do |question| - if question.is_required && !answered_questions[question.answer_field] - errors.add(question.answer_field.to_sym, :blank, message: "is required") - end + errors.add(question.answer_field.to_sym, :blank, message: 'is required') if question.is_required && !answered_questions[question.answer_field] - if question.character_limit.present? && answered_questions[question.answer_field] && answered_questions[question.answer_field].length > question.character_limit - errors.add(question.answer_field.to_sym, :blank, message: "exceeds character limit of #{question.character_limit}") - end + errors.add(question.answer_field.to_sym, :blank, message: "exceeds character limit of #{question.character_limit}") if question.character_limit.present? && answered_questions[question.answer_field] && answered_questions[question.answer_field].length > question.character_limit end end def send_notifications - Event.log_event(Event.names[:touchpoint_form_submitted], 'Submission', self.id, "Submission received for organization '#{self.organization_name}' form '#{self.form.name}' ") - return unless ENV["ENABLE_EMAIL_NOTIFICATIONS"] == "true" - return unless self.form.send_notifications? - emails_to_notify = self.form.notification_emails.split(',') - if form.notification_frequency == "instant" - UserMailer.submission_notification(submission_id: self.id, emails: emails_to_notify.uniq).deliver_later - end + Event.log_event(Event.names[:touchpoint_form_submitted], 'Submission', id, "Submission received for organization '#{organization_name}' form '#{form.name}' ") + return unless ENV['ENABLE_EMAIL_NOTIFICATIONS'] == 'true' + return unless form.send_notifications? + + emails_to_notify = form.notification_emails.split(',') + UserMailer.submission_notification(submission_id: id, emails: emails_to_notify.uniq).deliver_later if form.notification_frequency == 'instant' end def self.send_daily_notifications - form_ids = Submission.where("created_at > ?", 1.day.ago).pluck(:form_id).uniq - form_ids.each do | form_id | + form_ids = Submission.where('created_at > ?', 1.day.ago).pluck(:form_id).uniq + form_ids.each do |form_id| UserMailer.submissions_digest(form_id, 1.day.ago).deliver_later end end def self.send_weekly_notifications - form_ids = Submission.where("created_at > ?", 7.days.ago).pluck(:form_id).uniq - form_ids.each do | form_id | + form_ids = Submission.where('created_at > ?', 7.days.ago).pluck(:form_id).uniq + form_ids.each do |form_id| UserMailer.submissions_digest(form_id, 7.days.ago).deliver_later end end @@ -99,24 +95,22 @@ def update_form end def to_rows - values = self.form.questions.collect(&:answer_field) - - values = values + [ - self.ip_address, - self.user_agent, - self.page, - self.referer, - self.created_at + values = form.questions.collect(&:answer_field) + + values + [ + ip_address, + user_agent, + page, + referer, + created_at, ] - - values end def organization_name - form.organization.present? ? form.organization.name : "Org Name" + form.organization.present? ? form.organization.name : 'Org Name' end def set_uuid - self.uuid = SecureRandom.uuid if !self.uuid.present? + self.uuid = SecureRandom.uuid if uuid.blank? end end diff --git a/app/models/us_state.rb b/app/models/us_state.rb index ba9978330..bb38cdf88 100644 --- a/app/models/us_state.rb +++ b/app/models/us_state.rb @@ -1,59 +1,60 @@ -class UsState +# frozen_string_literal: true +class UsState STATES = [ - { name: "Alabama", abbreviation: "AL" }, - { name: "Alaska", abbreviation: "AK" }, - { name: "Arizona", abbreviation: "AZ" }, - { name: "Arkansas", abbreviation: "AR" }, - { name: "California", abbreviation: "CA" }, - { name: "Colorado", abbreviation: "CO" }, - { name: "Connecticut", abbreviation: "CT" }, - { name: "Delaware", abbreviation: "DE" }, - { name: "District of Columbia", abbreviation: "DC" }, - { name: "Florida", abbreviation: "FL" }, - { name: "Georgia", abbreviation: "GA" }, - { name: "Hawaii", abbreviation: "HI" }, - { name: "Idaho", abbreviation: "ID" }, - { name: "Illinois", abbreviation: "IL" }, - { name: "Indiana", abbreviation: "IN" }, - { name: "Iowa", abbreviation: "IA" }, - { name: "Kansas", abbreviation: "KS" }, - { name: "Kentucky", abbreviation: "KY" }, - { name: "Louisiana", abbreviation: "LA" }, - { name: "Maine", abbreviation: "ME" }, - { name: "Montana", abbreviation: "MT" }, - { name: "Nebraska", abbreviation: "NE" }, - { name: "Nevada", abbreviation: "NV" }, - { name: "New Hampshire", abbreviation: "NH" }, - { name: "New Jersey", abbreviation: "NJ" }, - { name: "New Mexico", abbreviation: "NM" }, - { name: "New York", abbreviation: "NY" }, - { name: "North Carolina", abbreviation: "NC" }, - { name: "North Dakota", abbreviation: "ND" }, - { name: "Ohio", abbreviation: "OH" }, - { name: "Oklahoma", abbreviation: "OK" }, - { name: "Oregon", abbreviation: "OR" }, - { name: "Maryland", abbreviation: "MD" }, - { name: "Massachusetts", abbreviation: "MA" }, - { name: "Michigan", abbreviation: "MI" }, - { name: "Minnesota", abbreviation: "MN" }, - { name: "Mississippi", abbreviation: "MS" }, - { name: "Missouri", abbreviation: "MO" }, - { name: "Pennsylvania", abbreviation: "PA" }, - { name: "Puerto Rico", abbreviation: "PR" }, - { name: "Rhode Island", abbreviation: "RI" }, - { name: "South Carolina", abbreviation: "SC" }, - { name: "South Dakota", abbreviation: "SD" }, - { name: "Tennessee", abbreviation: "TN" }, - { name: "Texas", abbreviation: "TX" }, - { name: "Utah", abbreviation: "UT" }, - { name: "Vermont", abbreviation: "VT" }, - { name: "Virginia", abbreviation: "VA" }, - { name: "Washington", abbreviation: "WA" }, - { name: "West Virginia", abbreviation: "WV" }, - { name: "Wisconsin", abbreviation: "WI" }, - { name: "Wyoming", abbreviation: "WY" }, - ] + { name: 'Alabama', abbreviation: 'AL' }, + { name: 'Alaska', abbreviation: 'AK' }, + { name: 'Arizona', abbreviation: 'AZ' }, + { name: 'Arkansas', abbreviation: 'AR' }, + { name: 'California', abbreviation: 'CA' }, + { name: 'Colorado', abbreviation: 'CO' }, + { name: 'Connecticut', abbreviation: 'CT' }, + { name: 'Delaware', abbreviation: 'DE' }, + { name: 'District of Columbia', abbreviation: 'DC' }, + { name: 'Florida', abbreviation: 'FL' }, + { name: 'Georgia', abbreviation: 'GA' }, + { name: 'Hawaii', abbreviation: 'HI' }, + { name: 'Idaho', abbreviation: 'ID' }, + { name: 'Illinois', abbreviation: 'IL' }, + { name: 'Indiana', abbreviation: 'IN' }, + { name: 'Iowa', abbreviation: 'IA' }, + { name: 'Kansas', abbreviation: 'KS' }, + { name: 'Kentucky', abbreviation: 'KY' }, + { name: 'Louisiana', abbreviation: 'LA' }, + { name: 'Maine', abbreviation: 'ME' }, + { name: 'Montana', abbreviation: 'MT' }, + { name: 'Nebraska', abbreviation: 'NE' }, + { name: 'Nevada', abbreviation: 'NV' }, + { name: 'New Hampshire', abbreviation: 'NH' }, + { name: 'New Jersey', abbreviation: 'NJ' }, + { name: 'New Mexico', abbreviation: 'NM' }, + { name: 'New York', abbreviation: 'NY' }, + { name: 'North Carolina', abbreviation: 'NC' }, + { name: 'North Dakota', abbreviation: 'ND' }, + { name: 'Ohio', abbreviation: 'OH' }, + { name: 'Oklahoma', abbreviation: 'OK' }, + { name: 'Oregon', abbreviation: 'OR' }, + { name: 'Maryland', abbreviation: 'MD' }, + { name: 'Massachusetts', abbreviation: 'MA' }, + { name: 'Michigan', abbreviation: 'MI' }, + { name: 'Minnesota', abbreviation: 'MN' }, + { name: 'Mississippi', abbreviation: 'MS' }, + { name: 'Missouri', abbreviation: 'MO' }, + { name: 'Pennsylvania', abbreviation: 'PA' }, + { name: 'Puerto Rico', abbreviation: 'PR' }, + { name: 'Rhode Island', abbreviation: 'RI' }, + { name: 'South Carolina', abbreviation: 'SC' }, + { name: 'South Dakota', abbreviation: 'SD' }, + { name: 'Tennessee', abbreviation: 'TN' }, + { name: 'Texas', abbreviation: 'TX' }, + { name: 'Utah', abbreviation: 'UT' }, + { name: 'Vermont', abbreviation: 'VT' }, + { name: 'Virginia', abbreviation: 'VA' }, + { name: 'Washington', abbreviation: 'WA' }, + { name: 'West Virginia', abbreviation: 'WV' }, + { name: 'Wisconsin', abbreviation: 'WI' }, + { name: 'Wyoming', abbreviation: 'WY' }, + ].freeze def self.dropdown_options STATES.map { |hash| ["#{hash[:abbreviation]} - #{hash[:name]}", hash[:abbreviation]] } diff --git a/app/models/user.rb b/app/models/user.rb index c4e462045..95b28e524 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class User < ApplicationRecord rolify # Include default devise modules. Others available are: @@ -11,31 +13,27 @@ class User < ApplicationRecord belongs_to :organization, optional: true has_many :user_roles, dependent: :destroy - has_many :forms, through: :user_roles, primary_key: "form_id" + has_many :forms, through: :user_roles, primary_key: 'form_id' has_many :collections, through: :organization validate :api_key_format before_save :update_api_key_updated_at def update_api_key_updated_at - if self.api_key_changed? - self.api_key_updated_at = Time.now - end + self.api_key_updated_at = Time.zone.now if api_key_changed? end def api_key_format - if self.api_key.present? && self.api_key.length != 40 - errors.add(:api_key, "is not 40 characters, as expected from api.data.gov.") - end + errors.add(:api_key, 'is not 40 characters, as expected from api.data.gov.') if api_key.present? && api_key.length != 40 end after_create :send_new_user_notification - APPROVED_DOMAINS = [".gov", ".mil"] + APPROVED_DOMAINS = ['.gov', '.mil'].freeze validates :email, presence: true, if: :tld_check - scope :active, -> { where("inactive ISNULL or inactive = false") } + scope :active, -> { where('inactive ISNULL or inactive = false') } scope :admins, -> { where(admin: true) } scope :performance_managers, -> { where(performance_manager: true) } @@ -51,7 +49,7 @@ def self.from_omniauth(auth) # Set login_dot_gov as Provider for legacy TP Devise accounts # TODO: Remove once all accounts are migrated/have `provider` and `uid` set @existing_user = User.find_by_email(auth.info.email) - if @existing_user && !@existing_user.provider.present? + if @existing_user && @existing_user.provider.blank? @existing_user.provider = auth.provider @existing_user.uid = auth.uid @existing_user.save @@ -60,12 +58,12 @@ def self.from_omniauth(auth) # For login.gov native accounts where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.email = auth.info.email - user.password = Devise.friendly_token[0,24] + user.password = Devise.friendly_token[0, 24] end end def tld_check - unless ENV['GITHUB_CLIENT_ID'].present? or APPROVED_DOMAINS.any? { |word| email.end_with?(word) } + unless ENV['GITHUB_CLIENT_ID'].present? || APPROVED_DOMAINS.any? { |word| email.end_with?(word) } errors.add(:email, "is not from a valid TLD - #{APPROVED_DOMAINS.to_sentence} domains only") return false end @@ -80,39 +78,39 @@ def organization_name if organization.present? organization.name elsif admin? - "Admin" + 'Admin' end end def role - if self.admin? - "Admin" + if admin? + 'Admin' else - "User" + 'User' end end # For Devise # This determines whether a user is inactive or not def active_for_authentication? - self && !self.inactive? + self && !inactive? end # For Devise # This is the flash message shown to a user when inactive def inactive_message - "User account #{self.email} is inactive. Please contact #{ENV.fetch("TOUCHPOINTS_SUPPORT")}." + "User account #{email} is inactive. Please contact #{ENV.fetch('TOUCHPOINTS_SUPPORT')}." end def deactivate! - self.update!(inactive: true) + update!(inactive: true) UserMailer.account_deactivated_notification(self).deliver_later - Event.log_event(Event.names[:user_deactivated], "User", self.id, "User account #{self.email} deactivated on #{Date.today}") + Event.log_event(Event.names[:user_deactivated], 'User', id, "User account #{email} deactivated on #{Date.today}") end def self.send_account_deactivation_notifications(expire_days) users = User.deactivation_pending(expire_days) - users.each do | user | + users.each do |user| UserMailer.account_deactivation_scheduled_notification(user.email, expire_days).deliver_later end end @@ -120,27 +118,29 @@ def self.send_account_deactivation_notifications(expire_days) def self.deactivation_pending(expire_days) min_time = ((90 - expire_days) + 1).days.ago max_time = (90 - expire_days).days.ago - User.active.where("(current_sign_in_at ISNULL AND created_at BETWEEN ? AND ?) OR (current_sign_in_at BETWEEN ? AND ?)", min_time, max_time, min_time, max_time) + User.active.where('(current_sign_in_at ISNULL AND created_at BETWEEN ? AND ?) OR (current_sign_in_at BETWEEN ? AND ?)', min_time, max_time, min_time, max_time) end def self.deactivate_inactive_accounts! # Find all accounts scheduled to be deactivated in 14 days - users = User.active.where("(current_sign_in_at ISNULL AND created_at <= ?) OR (current_sign_in_at <= ?)", 90.days.ago, 90.days.ago) - users.each do | user | + users = User.active.where('(current_sign_in_at ISNULL AND created_at <= ?) OR (current_sign_in_at <= ?)', 90.days.ago, 90.days.ago) + users.each do |user| user.deactivate! end end def self.to_csv - active_users = self.order("email") + active_users = order('email') return nil unless active_users.present? - header_attributes = ["organization_name", "email", "current_sign_in_at"] - attributes = active_users.map { |u| { - organization_name: u.organization.name, - email: u.email, - current_sign_in_at: u.current_sign_in_at, - }} + header_attributes = %w[organization_name email current_sign_in_at] + attributes = active_users.map do |u| + { + organization_name: u.organization.name, + email: u.email, + current_sign_in_at: u.current_sign_in_at, + } + end CSV.generate(headers: true) do |csv| csv << header_attributes @@ -151,7 +151,7 @@ def self.to_csv end def set_api_key - update(api_key: ApiKey.generator, api_key_updated_at: Time.now) + update(api_key: ApiKey.generator, api_key_updated_at: Time.zone.now) end def unset_api_key @@ -160,35 +160,36 @@ def unset_api_key private - def parse_host_from_domain(string) - fragments = string.split(".") - if fragments.size == 2 - return string - elsif fragments.size == 3 - fragments.shift - return fragments.join(".") - elsif fragments.size == 4 - fragments.shift - fragments.shift - return fragments.join(".") - end + def parse_host_from_domain(string) + fragments = string.split('.') + case fragments.size + when 2 + string + when 3 + fragments.shift + fragments.join('.') + when 4 + fragments.shift + fragments.shift + fragments.join('.') end + end - def ensure_organization - return if organization_id.present? + def ensure_organization + return if organization_id.present? - email_address_domain = Mail::Address.new(self.email).domain - parsed_domain = parse_host_from_domain(email_address_domain) + email_address_domain = Mail::Address.new(email).domain + parsed_domain = parse_host_from_domain(email_address_domain) - if org = Organization.find_by_domain(parsed_domain) - self.organization_id = org.id - else - UserMailer.no_org_notification(self).deliver_later if self.id - errors.add(:organization, "'#{email_address_domain}' has not yet been configured for Touchpoints - Please contact the Feedback Analytics Team for assistance.") - end + if org = Organization.find_by_domain(parsed_domain) + self.organization_id = org.id + else + UserMailer.no_org_notification(self).deliver_later if id + errors.add(:organization, "'#{email_address_domain}' has not yet been configured for Touchpoints - Please contact the Feedback Analytics Team for assistance.") end + end - def send_new_user_notification - UserMailer.new_user_notification(self).deliver_later - end + def send_new_user_notification + UserMailer.new_user_notification(self).deliver_later + end end diff --git a/app/models/user_role.rb b/app/models/user_role.rb index 66d92b097..9f886a792 100644 --- a/app/models/user_role.rb +++ b/app/models/user_role.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + class UserRole < ApplicationRecord belongs_to :user belongs_to :form validates :role, presence: true - validates_uniqueness_of :user_id, scope: :form_id + validates :user_id, uniqueness: { scope: :form_id } module Role - FormManager = "form_manager" - ResponseViewer = "response_viewer" + FormManager = 'form_manager' + ResponseViewer = 'response_viewer' end ROLES = [ UserRole::Role::FormManager, - UserRole::Role::ResponseViewer - ] + UserRole::Role::ResponseViewer, + ].freeze def valid_role? - ROLES.include?(self.role) + ROLES.include?(role) end end diff --git a/app/models/version.rb b/app/models/version.rb index b2bce350e..449f1cc57 100644 --- a/app/models/version.rb +++ b/app/models/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'csv' class Version @@ -6,7 +8,7 @@ def self.to_csv(model) user_email_map = {} users.map { |user| user_email_map[user.id] = user.email } CSV.generate(headers: true) do |csv| - csv << ['Event','Created At','Whodunnit Id','Whodunnit Email','Changeset','Object state'] + csv << ['Event', 'Created At', 'Whodunnit Id', 'Whodunnit Email', 'Changeset', 'Object state'] model.versions.reverse.each do |version| csv << [version.event, version.created_at, version.whodunnit, user_email_map[version.whodunnit.to_i], version.changeset, version.object] diff --git a/app/models/website.rb b/app/models/website.rb index 71ccc942a..bbe426797 100644 --- a/app/models/website.rb +++ b/app/models/website.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'open-uri' class Website < ApplicationRecord @@ -16,37 +18,37 @@ class Website < ApplicationRecord scope :active, -> { where("production_status = 'production' OR production_status = 'newly_requested' OR production_status = 'request_approved'") } PRODUCTION_STATUSES = { - "newly_requested" => "Newly requested", - "request_approved" => "Request approved", - "request_denied" => "Request denied", - "in_development" => "In development", - "production" => "Production", - "being_decommissioned" => "Being decommissioned", - "redirect" => "Redirect", - "archived" => "Archived", - "decommissioned" => "Decommissioned", - } - - ACTIVE_PRODUCTION_STATUSES = [ - "Production", - "Staging" - ] + 'newly_requested' => 'Newly requested', + 'request_approved' => 'Request approved', + 'request_denied' => 'Request denied', + 'in_development' => 'In development', + 'production' => 'Production', + 'being_decommissioned' => 'Being decommissioned', + 'redirect' => 'Redirect', + 'archived' => 'Archived', + 'decommissioned' => 'Decommissioned', + }.freeze + + ACTIVE_PRODUCTION_STATUSES = %w[ + Production + Staging + ].freeze TYPE_OF_SITES = { - "API" => "Application Programming Interface", - "Application" => "Transactional site (web app/back-end system) with some front-end web content", - "Application Login" => "Login page to a back-end system", - "Critical infrastructure" => "Required to support a GSA or shared service", - "GitHub repo" => "Site decommissioned; URL redirects to a GitHub repo (status is redirect)", - "Google form" => "Site redirects to a Google form (status is redirect)", - "Informational" => "Informational (not transactional) site" - } + 'API' => 'Application Programming Interface', + 'Application' => 'Transactional site (web app/back-end system) with some front-end web content', + 'Application Login' => 'Login page to a back-end system', + 'Critical infrastructure' => 'Required to support a GSA or shared service', + 'GitHub repo' => 'Site decommissioned; URL redirects to a GitHub repo (status is redirect)', + 'Google form' => 'Site redirects to a Google form (status is redirect)', + 'Informational' => 'Informational (not transactional) site', + }.freeze DIGITAL_BRAND_CATEGORIES = { - "GSA Business" => "About a GSA program, product, or service", - "Hybrid" => "Managed by GSA in partnership with another agency or business partner; gov-wide or collaborative", - "External" => "Managed by GSA on behalf of another agency or business partner; not related to GSA business" - } + 'GSA Business' => 'About a GSA program, product, or service', + 'Hybrid' => 'Managed by GSA in partnership with another agency or business partner; gov-wide or collaborative', + 'External' => 'Managed by GSA on behalf of another agency or business partner; not related to GSA business', + }.freeze aasm :production_status do state :newly_requested, initial: true @@ -77,7 +79,7 @@ class Website < ApplicationRecord transitions from: [:production], to: :archived end event :decommission do - transitions from: [:production, :archived, :redirect], to: :decommissioned + transitions from: %i[production archived redirect], to: :decommissioned end event :reset do transitions to: :newly_requested @@ -89,64 +91,60 @@ def website_managers end def website_personas - Persona.where(id: self.persona_list) + Persona.where(id: persona_list) end def website_manager_emails - website_managers.collect{ | mgr | mgr.email }.join(", ") + website_managers.collect(&:email).join(', ') end # return all website_ids managed by users with email matching search string def self.ids_by_manager_search(search_text) - sql = %q( + sql = " select w.id from websites w, users_roles ur, roles r, users u where u.email ilike :search_text and u.id = ur.user_id and ur.role_id = r.id and r.resource_type = 'Website' and r.resource_id = w.id - and r.name = 'website_manager').gsub("\n","") - self.find_by_sql([sql,search_text: search_text]).collect{ | ws | ws.id } + and r.name = 'website_manager'".gsub("\n", '') + find_by_sql([sql, { search_text: }]).collect(&:id) end def admin?(user:) - raise ArgumentException unless user.class == User + raise ArgumentException unless user.instance_of?(User) - user.admin? || user.organizational_website_manager || self.contact_email == user.email || self.site_owner_email == user.email + user.admin? || user.organizational_website_manager || contact_email == user.email || site_owner_email == user.email end def blankFields - Website.column_names.select { | cn | self.send(cn).blank? } + Website.column_names.select { |cn| send(cn).blank? } end def requiresDataCollection? - blankFields.size > 0 + blankFields.size.positive? end def validate_domain_format - if self.domain.present? && !self.domain.include?(".") - errors.add(:domain, "domain must have a suffix, like .gov or .mil") - end + errors.add(:domain, 'domain must have a suffix, like .gov or .mil') if domain.present? && domain.exclude?('.') end def site_scanner_json_request - begin - url = "https://api.gsa.gov/technology/site-scanning/v1/websites/#{self.domain}?api_key=#{ENV.fetch("API_DATA_GOV_KEY")}&limit=10" - text = URI.open(url).read - rescue => e - "Error during Site Scanner API request for #{self.domain}.\n\n#{e}" - end + url = "https://api.gsa.gov/technology/site-scanning/v1/websites/#{domain}?api_key=#{ENV.fetch('API_DATA_GOV_KEY')}&limit=10" + text = URI.open(url).read + rescue StandardError => e + "Error during Site Scanner API request for #{domain}.\n\n#{e}" end def parent_domain - return nil unless self.domain? + return nil unless domain? - self.domain.split(".")[-2..-1].join(".") + domain.split('.')[-2..].join('.') end # has a domain name and suffix def tld? - self.domain.split(".").size == 2 + domain.split('.').size == 2 end def self.to_csv diff --git a/app/serializers/barrier_serializer.rb b/app/serializers/barrier_serializer.rb index 2d8d40836..d8d30986e 100644 --- a/app/serializers/barrier_serializer.rb +++ b/app/serializers/barrier_serializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class BarrierSerializer < ActiveModel::Serializer attributes :id, :name, :description end diff --git a/app/serializers/collection_serializer.rb b/app/serializers/collection_serializer.rb index 07496e8e6..7a59ebafa 100644 --- a/app/serializers/collection_serializer.rb +++ b/app/serializers/collection_serializer.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + class CollectionSerializer < ActiveModel::Serializer attributes :id, - :name, - :start_date, - :end_date, - :organization_id, - :organization_name, - :organization_abbreviation, - :year, - :quarter, - :service_provider_id, - :service_provider_name, - :integrity_hash, - :aasm_state, - :reflection, - :rating, - :user_id, - :updated_at + :name, + :start_date, + :end_date, + :organization_id, + :organization_name, + :organization_abbreviation, + :year, + :quarter, + :service_provider_id, + :service_provider_name, + :integrity_hash, + :aasm_state, + :reflection, + :rating, + :user_id, + :updated_at has_many :omb_cx_reporting_collections end diff --git a/app/serializers/digital_product_serializer.rb b/app/serializers/digital_product_serializer.rb index 2ef05cc09..138517975 100644 --- a/app/serializers/digital_product_serializer.rb +++ b/app/serializers/digital_product_serializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class DigitalProductSerializer < ActiveModel::Serializer attributes :id, :organization_id, :user_id, :service, :url, :code_repository_url, :language, :status, :aasm_state, :short_description, :long_description, :tags, :certified_at end diff --git a/app/serializers/digital_service_account_serializer.rb b/app/serializers/digital_service_account_serializer.rb index 27f07a7a0..9c8e699b4 100644 --- a/app/serializers/digital_service_account_serializer.rb +++ b/app/serializers/digital_service_account_serializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class DigitalServiceAccountSerializer < ActiveModel::Serializer attributes :page, :size, :links @@ -13,19 +15,18 @@ def links @instance_options[:links] end - attributes :id, - :name, - :organization_id, - :organization_name, - :organization_abbreviation, - :user_id, - :service, - :service_url, - :account, - :language, - :status, - :short_description, - :long_description, - :tags + :name, + :organization_id, + :organization_name, + :organization_abbreviation, + :user_id, + :service, + :service_url, + :account, + :language, + :status, + :short_description, + :long_description, + :tags end diff --git a/app/serializers/form_serializer.rb b/app/serializers/form_serializer.rb index eb0b809e8..eb6f3b880 100644 --- a/app/serializers/form_serializer.rb +++ b/app/serializers/form_serializer.rb @@ -1,51 +1,53 @@ +# frozen_string_literal: true + class FormSerializer < ActiveModel::Serializer attributes :id, - :name, - :title, - :instructions, - :disclaimer_text, - :kind, - :notes, - :status, - :created_at, - :updated_at, - :whitelist_url, - :whitelist_test_url, - :display_header_logo, - :success_text_heading, - :success_text, - :modal_button_text, - :display_header_square_logo, - :early_submission, - :user_id, - :template, - :uuid, - :short_uuid, - :organization_id, - :omb_approval_number, - :expiration_date, - :medium, - :federal_register_url, - :anticipated_delivery_count, - :service_name, - :data_submission_comment, - :survey_instrument_reference, - :agency_poc_email, - :agency_poc_name, - :department, - :bureau, - :notification_emails, - :start_date, - :end_date, - :aasm_state, - :delivery_method, - :element_selector, - :survey_form_activations, - :load_css, - :logo, - :time_zone, - :response_count, - :last_response_created_at + :name, + :title, + :instructions, + :disclaimer_text, + :kind, + :notes, + :status, + :created_at, + :updated_at, + :whitelist_url, + :whitelist_test_url, + :display_header_logo, + :success_text_heading, + :success_text, + :modal_button_text, + :display_header_square_logo, + :early_submission, + :user_id, + :template, + :uuid, + :short_uuid, + :organization_id, + :omb_approval_number, + :expiration_date, + :medium, + :federal_register_url, + :anticipated_delivery_count, + :service_name, + :data_submission_comment, + :survey_instrument_reference, + :agency_poc_email, + :agency_poc_name, + :department, + :bureau, + :notification_emails, + :start_date, + :end_date, + :aasm_state, + :delivery_method, + :element_selector, + :survey_form_activations, + :load_css, + :logo, + :time_zone, + :response_count, + :last_response_created_at has_many :questions belongs_to :service diff --git a/app/serializers/full_form_serializer.rb b/app/serializers/full_form_serializer.rb index 9cdc94300..d7ac83cc5 100644 --- a/app/serializers/full_form_serializer.rb +++ b/app/serializers/full_form_serializer.rb @@ -1,5 +1,6 @@ -class FullFormSerializer < ActiveModel::Serializer +# frozen_string_literal: true +class FullFormSerializer < ActiveModel::Serializer attributes :page, :size, :start_date, :end_date def page @@ -23,57 +24,57 @@ def links end attributes :id, - :name, - :title, - :instructions, - :disclaimer_text, - :kind, - :notes, - :status, - :created_at, - :updated_at, - :whitelist_url, - :whitelist_test_url, - :display_header_logo, - :success_text_heading, - :success_text, - :modal_button_text, - :display_header_square_logo, - :early_submission, - :user_id, - :template, - :uuid, - :short_uuid, - :organization_id, - :omb_approval_number, - :expiration_date, - :medium, - :federal_register_url, - :anticipated_delivery_count, - :service_name, - :data_submission_comment, - :survey_instrument_reference, - :agency_poc_email, - :agency_poc_name, - :department, - :bureau, - :notification_emails, - :start_date, - :end_date, - :aasm_state, - :delivery_method, - :element_selector, - :survey_form_activations, - :load_css, - :logo, - :time_zone, - :response_count, - :last_response_created_at + :name, + :title, + :instructions, + :disclaimer_text, + :kind, + :notes, + :status, + :created_at, + :updated_at, + :whitelist_url, + :whitelist_test_url, + :display_header_logo, + :success_text_heading, + :success_text, + :modal_button_text, + :display_header_square_logo, + :early_submission, + :user_id, + :template, + :uuid, + :short_uuid, + :organization_id, + :omb_approval_number, + :expiration_date, + :medium, + :federal_register_url, + :anticipated_delivery_count, + :service_name, + :data_submission_comment, + :survey_instrument_reference, + :agency_poc_email, + :agency_poc_name, + :department, + :bureau, + :notification_emails, + :start_date, + :end_date, + :aasm_state, + :delivery_method, + :element_selector, + :survey_form_activations, + :load_css, + :logo, + :time_zone, + :response_count, + :last_response_created_at has_many :questions has_many :submissions def submissions - object.submissions.where('created_at BETWEEN ? AND ?',start_date,end_date).limit(size).offset(size * page) + object.submissions.where('created_at BETWEEN ? AND ?', start_date, end_date).limit(size).offset(size * page) end end diff --git a/app/serializers/goal_serializer.rb b/app/serializers/goal_serializer.rb index dfd50b589..e60c9115b 100644 --- a/app/serializers/goal_serializer.rb +++ b/app/serializers/goal_serializer.rb @@ -1,17 +1,18 @@ +# frozen_string_literal: true + class GoalSerializer < ActiveModel::Serializer attributes :id, - :organization_id, - :organization_name, - :organization_abbreviation, - :name, - :description, - :tags, - :users, - :four_year_goal, - :position, - :goal_statement, - :challenge, - :opportunity, - :notes - + :organization_id, + :organization_name, + :organization_abbreviation, + :name, + :description, + :tags, + :users, + :four_year_goal, + :position, + :goal_statement, + :challenge, + :opportunity, + :notes end diff --git a/app/serializers/goal_target_serializer.rb b/app/serializers/goal_target_serializer.rb index f7b8e126a..7f2441af2 100644 --- a/app/serializers/goal_target_serializer.rb +++ b/app/serializers/goal_target_serializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class GoalTargetSerializer < ActiveModel::Serializer attributes :id, :goal, :target_date_at, :assertion, :kpi, :starting_value, :target_value, :current_value end diff --git a/app/serializers/milestone_serializer.rb b/app/serializers/milestone_serializer.rb index 975f45cba..6c8de951f 100644 --- a/app/serializers/milestone_serializer.rb +++ b/app/serializers/milestone_serializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class MilestoneSerializer < ActiveModel::Serializer attributes :id, :organization_id, :name, :description, :due_date, :status, :notes end diff --git a/app/serializers/objective_serializer.rb b/app/serializers/objective_serializer.rb index 13a17ae41..785d81fe4 100644 --- a/app/serializers/objective_serializer.rb +++ b/app/serializers/objective_serializer.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + class ObjectiveSerializer < ActiveModel::Serializer attributes :id, - :name, :description, - :organization_id, - :organization_name, - :goal_id, - :milestone_id, - :position, - :tags, - :users + :name, :description, + :organization_id, + :organization_name, + :goal_id, + :milestone_id, + :position, + :tags, + :users end diff --git a/app/serializers/omb_cx_reporting_collection_serializer.rb b/app/serializers/omb_cx_reporting_collection_serializer.rb index d2ed9f186..a77a021b2 100644 --- a/app/serializers/omb_cx_reporting_collection_serializer.rb +++ b/app/serializers/omb_cx_reporting_collection_serializer.rb @@ -1,101 +1,103 @@ +# frozen_string_literal: true + class OmbCxReportingCollectionSerializer < ActiveModel::Serializer attributes :id, - :organization_id, - :organization_name, - :organization_abbreviation, - :collection_id, - :collection_name, - :collection_year, - :collection_quarter, - :service_provided, - :transaction_point, - :channel, - :volume_of_customers, - :volume_of_customers_provided_survey_opportunity, - :volume_of_respondents, - :omb_control_number, - :federal_register_url, - :q1_text, - :q1_1, - :q1_2, - :q1_3, - :q1_4, - :q1_5, - :q1_point_scale, - :q2_text, - :q2_1, - :q2_2, - :q2_3, - :q2_4, - :q2_5, - :q2_point_scale, - :q3_text, - :q3_1, - :q3_2, - :q3_3, - :q3_4, - :q3_5, - :q3_point_scale, - :q4_text, - :q4_1, - :q4_2, - :q4_3, - :q4_4, - :q4_5, - :q4_point_scale, - :q5_text, - :q5_1, - :q5_2, - :q5_3, - :q5_4, - :q5_5, - :q5_point_scale, - :q6_text, - :q6_1, - :q6_2, - :q6_3, - :q6_4, - :q6_5, - :q6_point_scale, - :q7_text, - :q7_1, - :q7_2, - :q7_3, - :q7_4, - :q7_5, - :q7_point_scale, - :q8_text, - :q8_1, - :q8_2, - :q8_3, - :q8_4, - :q8_5, - :q8_point_scale, - :q9_text, - :q9_1, - :q9_2, - :q9_3, - :q9_4, - :q9_5, - :q9_point_scale, - :q10_text, - :q10_1, - :q10_2, - :q10_3, - :q10_4, - :q10_5, - :q10_point_scale, - :q11_text, - :q11_1, - :q11_2, - :q11_3, - :q11_4, - :q11_5, - :q11_point_scale, - :created_at, - :updated_at, - :operational_metrics, - :service_id, - :service_name, - :service_slug + :organization_id, + :organization_name, + :organization_abbreviation, + :collection_id, + :collection_name, + :collection_year, + :collection_quarter, + :service_provided, + :transaction_point, + :channel, + :volume_of_customers, + :volume_of_customers_provided_survey_opportunity, + :volume_of_respondents, + :omb_control_number, + :federal_register_url, + :q1_text, + :q1_1, + :q1_2, + :q1_3, + :q1_4, + :q1_5, + :q1_point_scale, + :q2_text, + :q2_1, + :q2_2, + :q2_3, + :q2_4, + :q2_5, + :q2_point_scale, + :q3_text, + :q3_1, + :q3_2, + :q3_3, + :q3_4, + :q3_5, + :q3_point_scale, + :q4_text, + :q4_1, + :q4_2, + :q4_3, + :q4_4, + :q4_5, + :q4_point_scale, + :q5_text, + :q5_1, + :q5_2, + :q5_3, + :q5_4, + :q5_5, + :q5_point_scale, + :q6_text, + :q6_1, + :q6_2, + :q6_3, + :q6_4, + :q6_5, + :q6_point_scale, + :q7_text, + :q7_1, + :q7_2, + :q7_3, + :q7_4, + :q7_5, + :q7_point_scale, + :q8_text, + :q8_1, + :q8_2, + :q8_3, + :q8_4, + :q8_5, + :q8_point_scale, + :q9_text, + :q9_1, + :q9_2, + :q9_3, + :q9_4, + :q9_5, + :q9_point_scale, + :q10_text, + :q10_1, + :q10_2, + :q10_3, + :q10_4, + :q10_5, + :q10_point_scale, + :q11_text, + :q11_1, + :q11_2, + :q11_3, + :q11_4, + :q11_5, + :q11_point_scale, + :created_at, + :updated_at, + :operational_metrics, + :service_id, + :service_name, + :service_slug end diff --git a/app/serializers/organization_serializer.rb b/app/serializers/organization_serializer.rb index e4c910723..554efeddd 100644 --- a/app/serializers/organization_serializer.rb +++ b/app/serializers/organization_serializer.rb @@ -1,15 +1,16 @@ +# frozen_string_literal: true + class OrganizationSerializer < ActiveModel::Serializer attributes :id, - :name, - :url, - :abbreviation, - :domain, - :logo, - :digital_analytics_path, - :mission_statement, - :mission_statement_url, - :performance_url, - :strategic_plan_url, - :learning_agenda_url - + :name, + :url, + :abbreviation, + :domain, + :logo, + :digital_analytics_path, + :mission_statement, + :mission_statement_url, + :performance_url, + :strategic_plan_url, + :learning_agenda_url end diff --git a/app/serializers/persona_serializer.rb b/app/serializers/persona_serializer.rb index 1e0a788ba..ff2b63dbe 100644 --- a/app/serializers/persona_serializer.rb +++ b/app/serializers/persona_serializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class PersonaSerializer < ActiveModel::Serializer attributes :id, :name, :description, :tags, :notes, :user_id end diff --git a/app/serializers/service_provider_serializer.rb b/app/serializers/service_provider_serializer.rb index 5676f4b37..fb2263416 100644 --- a/app/serializers/service_provider_serializer.rb +++ b/app/serializers/service_provider_serializer.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + class ServiceProviderSerializer < ActiveModel::Serializer attributes :id, - :organization_id, - :organization_abbreviation, - :organization_name, - :name, - :slug, - :description, - :notes, - :department, - :department_abbreviation, - :bureau, - :inactive, - :url, - :new + :organization_id, + :organization_abbreviation, + :organization_name, + :name, + :slug, + :description, + :notes, + :department, + :department_abbreviation, + :bureau, + :inactive, + :url, + :new end diff --git a/app/serializers/service_serializer.rb b/app/serializers/service_serializer.rb index 39a2ed80c..5390a5e1b 100644 --- a/app/serializers/service_serializer.rb +++ b/app/serializers/service_serializer.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + class ServiceSerializer < ActiveModel::Serializer attributes :id, - :name, - :description, - :organization_id, - :organization_abbreviation, - :organization_name, - :service_provider_id, - :service_provider_name, - :justification_text, - :kind, - :notes, - :hisp, - :department, - :bureau, - :service_abbreviation, - :service_slug, - :service_owner_email, - :url + :name, + :description, + :organization_id, + :organization_abbreviation, + :organization_name, + :service_provider_id, + :service_provider_name, + :justification_text, + :kind, + :notes, + :hisp, + :department, + :bureau, + :service_abbreviation, + :service_slug, + :service_owner_email, + :url end diff --git a/app/serializers/service_stage_barrier_serializer.rb b/app/serializers/service_stage_barrier_serializer.rb index 6f8f37df7..a0f9a25c1 100644 --- a/app/serializers/service_stage_barrier_serializer.rb +++ b/app/serializers/service_stage_barrier_serializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class ServiceStageBarrierSerializer < ActiveModel::Serializer attributes :id, :service_stage_id, :barrier_id end diff --git a/app/serializers/service_stage_serializer.rb b/app/serializers/service_stage_serializer.rb index 784df8afe..310c88c28 100644 --- a/app/serializers/service_stage_serializer.rb +++ b/app/serializers/service_stage_serializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class ServiceStageSerializer < ActiveModel::Serializer attributes :id, :name, :description, :service_id, :notes, :time, :total_eligible_population end diff --git a/app/serializers/submission_serializer.rb b/app/serializers/submission_serializer.rb index f4b2cc542..a06da1f06 100644 --- a/app/serializers/submission_serializer.rb +++ b/app/serializers/submission_serializer.rb @@ -1,36 +1,38 @@ +# frozen_string_literal: true + class SubmissionSerializer < ActiveModel::Serializer attributes :id, - :user_id, - :created_at, - :updated_at, - :referer, - :page, - :user_agent, - :answer_01, - :answer_02, - :answer_03, - :answer_04, - :answer_05, - :answer_06, - :answer_07, - :answer_08, - :answer_09, - :answer_10, - :answer_11, - :answer_12, - :answer_13, - :answer_14, - :answer_15, - :answer_16, - :answer_17, - :answer_18, - :answer_19, - :answer_20, - :ip_address, - :location_code, - :flagged, - :archived, - :aasm_state, - :language, - :uuid + :user_id, + :created_at, + :updated_at, + :referer, + :page, + :user_agent, + :answer_01, + :answer_02, + :answer_03, + :answer_04, + :answer_05, + :answer_06, + :answer_07, + :answer_08, + :answer_09, + :answer_10, + :answer_11, + :answer_12, + :answer_13, + :answer_14, + :answer_15, + :answer_16, + :answer_17, + :answer_18, + :answer_19, + :answer_20, + :ip_address, + :location_code, + :flagged, + :archived, + :aasm_state, + :language, + :uuid end diff --git a/app/serializers/user_serializer.rb b/app/serializers/user_serializer.rb index 514edc6f7..8eb86688d 100644 --- a/app/serializers/user_serializer.rb +++ b/app/serializers/user_serializer.rb @@ -1,8 +1,9 @@ +# frozen_string_literal: true + class UserSerializer < ActiveModel::Serializer attributes :email, - :first_name, - :last_name, - :position_title, - :profile_photo - + :first_name, + :last_name, + :position_title, + :profile_photo end diff --git a/app/serializers/website_serializer.rb b/app/serializers/website_serializer.rb index 398b18959..4b20d68f4 100644 --- a/app/serializers/website_serializer.rb +++ b/app/serializers/website_serializer.rb @@ -1,43 +1,45 @@ +# frozen_string_literal: true + class WebsiteSerializer < ActiveModel::Serializer attributes :id, - :domain, - :parent_domain, - :office, - # :office_id, - :sub_office, - # :suboffice_id, - :contact_email, - :site_owner_email, - :production_status, - :type_of_site, - :digital_brand_category, - :redirects_to, - :status_code, - :cms_platform, - :required_by_law_or_policy, - :has_dap, - :dap_gtm_code, - # :cost_estimator_url, - # :modernization_plan_url, - # :annual_baseline_cost, - # :modernization_cost, - :analytics_url, - :uses_feedback, - :feedback_tool, - :sitemap_url, - :mobile_friendly, - :has_search, - :uses_tracking_cookies, - :has_authenticated_experience, - :authentication_tool, - :notes, - :repository_url, - :hosting_platform, - # :modernization_cost_2021, - # :modernization_cost_2022, - # :modernization_cost_2023, - :uswds_version, - :https, - :created_at, - :updated_at + :domain, + :parent_domain, + :office, + # :office_id, + :sub_office, + # :suboffice_id, + :contact_email, + :site_owner_email, + :production_status, + :type_of_site, + :digital_brand_category, + :redirects_to, + :status_code, + :cms_platform, + :required_by_law_or_policy, + :has_dap, + :dap_gtm_code, + # :cost_estimator_url, + # :modernization_plan_url, + # :annual_baseline_cost, + # :modernization_cost, + :analytics_url, + :uses_feedback, + :feedback_tool, + :sitemap_url, + :mobile_friendly, + :has_search, + :uses_tracking_cookies, + :has_authenticated_experience, + :authentication_tool, + :notes, + :repository_url, + :hosting_platform, + # :modernization_cost_2021, + # :modernization_cost_2022, + # :modernization_cost_2023, + :uswds_version, + :https, + :created_at, + :updated_at end diff --git a/app/uploaders/logo_uploader.rb b/app/uploaders/logo_uploader.rb index a0b842ddf..f42a3b8ac 100644 --- a/app/uploaders/logo_uploader.rb +++ b/app/uploaders/logo_uploader.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class LogoUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick @@ -47,7 +49,7 @@ def store_dir # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: def extension_allowlist - %w(jpg jpeg gif png) + %w[jpg jpeg gif png] end # Override the filename of the uploaded files: diff --git a/app/views/admin/collections/_form.html.erb b/app/views/admin/collections/_form.html.erb index 92453759d..e3c1c9333 100644 --- a/app/views/admin/collections/_form.html.erb +++ b/app/views/admin/collections/_form.html.erb @@ -53,8 +53,7 @@ ["🟢 Reporting within A-11 guidelines", "TRUE"], ["🔴 Not submitting data", "FALSE"], ["🟡 Reporting partially within A-11 guidelines", "PARTIAL"] - ] - %> + ] %>
This data collection has been published. @@ -128,7 +128,7 @@
<% if !@collection.submitted? && !@collection.published? %> -
Submitting this Data Collection will send an email
diff --git a/app/views/admin/digital_product_versions/edit.html.erb b/app/views/admin/digital_product_versions/edit.html.erb
index 425cbb427..64705eb7e 100644
--- a/app/views/admin/digital_product_versions/edit.html.erb
+++ b/app/views/admin/digital_product_versions/edit.html.erb
@@ -1,4 +1,4 @@
Update digital product version
<%= render "form", digital_product_version: @digital_product_version %>
-New digital product version
<%= render "form", digital_product_version: @digital_product_version %>
-
Only "Archive" a Product after your Organization
diff --git a/app/views/admin/digital_service_accounts/_form.html.erb b/app/views/admin/digital_service_accounts/_form.html.erb
index 6985bcd16..f072b0eb9 100644
--- a/app/views/admin/digital_service_accounts/_form.html.erb
+++ b/app/views/admin/digital_service_accounts/_form.html.erb
@@ -116,7 +116,7 @@
<% if !digital_service_account.persisted? %>
-
Tags, Agencies, and Contacts can be associated with this diff --git a/app/views/admin/digital_service_accounts/_tags.html.erb b/app/views/admin/digital_service_accounts/_tags.html.erb index e611a9171..486a940ce 100644 --- a/app/views/admin/digital_service_accounts/_tags.html.erb +++ b/app/views/admin/digital_service_accounts/_tags.html.erb @@ -1,56 +1,56 @@ <%= form_with(model: digital_service_account, url: admin_digital_service_account_path(digital_service_account), local: true) do |f| %> -
This social media account has been archived.
@@ -139,7 +139,7 @@
<% end %>
-
Only "Archive" an Account after your Organization diff --git a/app/views/admin/digital_service_accounts/upload.html.erb b/app/views/admin/digital_service_accounts/upload.html.erb index 1f6731269..37b733369 100644 --- a/app/views/admin/digital_service_accounts/upload.html.erb +++ b/app/views/admin/digital_service_accounts/upload.html.erb @@ -10,7 +10,6 @@ Bulk Social Media Account Upload Create CSV File Your csv file must contain the following headers exactly as they are shown with their corresponding data: account_platform, account_url, account_name, short_description, language, agencies, contacts - Agency and Contact Format If you have more than one agency or contact that needs to be associated with a single account, delineate each item with a "|" between them diff --git a/app/views/admin/form_sections/_view.html.erb b/app/views/admin/form_sections/_view.html.erb index 6a9ba3520..fe641e78a 100644 --- a/app/views/admin/form_sections/_view.html.erb +++ b/app/views/admin/form_sections/_view.html.erb @@ -5,7 +5,7 @@ - + section title saved @@ -27,7 +27,7 @@
diff --git a/app/views/admin/forms/_form.html.erb b/app/views/admin/forms/_form.html.erb index 16b1fcd69..2f4bca9f8 100644 --- a/app/views/admin/forms/_form.html.erb +++ b/app/views/admin/forms/_form.html.erb @@ -4,7 +4,7 @@
diff --git a/app/views/admin/forms/_form_notifications.html.erb b/app/views/admin/forms/_form_notifications.html.erb index 9f3e48543..cddfe788b 100644 --- a/app/views/admin/forms/_form_notifications.html.erb +++ b/app/views/admin/forms/_form_notifications.html.erb @@ -4,7 +4,7 @@
@@ -26,15 +26,15 @@
diff --git a/app/views/admin/forms/_logo_display.html.erb b/app/views/admin/forms/_logo_display.html.erb index 58b1ff588..f74f3d984 100644 --- a/app/views/admin/forms/_logo_display.html.erb +++ b/app/views/admin/forms/_logo_display.html.erb @@ -1,7 +1,7 @@@@ -41,7 +41,7 @@
@@ -56,4 +56,3 @@ <% end %> <% end %>
diff --git a/app/views/admin/forms/compliance.html.erb b/app/views/admin/forms/compliance.html.erb index 56ae0beb9..c60af58c9 100644 --- a/app/views/admin/forms/compliance.html.erb +++ b/app/views/admin/forms/compliance.html.erb @@ -15,7 +15,7 @@
diff --git a/app/views/admin/forms/delivery_method.html.erb b/app/views/admin/forms/delivery_method.html.erb index 2a0ee364c..3eebaf92b 100644 --- a/app/views/admin/forms/delivery_method.html.erb +++ b/app/views/admin/forms/delivery_method.html.erb @@ -15,7 +15,7 @@
@@ -70,7 +70,7 @@ <% Form::DELIVERY_METHODS.each_with_index do |delivery_method, index| %>
Touchpoints supports a maximum of 20 questions. diff --git a/app/views/admin/forms/responses.html.erb b/app/views/admin/forms/responses.html.erb index b72512eea..e8fd86a68 100644 --- a/app/views/admin/forms/responses.html.erb +++ b/app/views/admin/forms/responses.html.erb @@ -14,7 +14,7 @@ Customer Feedback Analysis <% if admin_permissions? %> -
+ <% end %> <% if @form.kind == "a11" %> diff --git a/app/views/admin/forms/show.html.erb b/app/views/admin/forms/show.html.erb index 24f38a31d..9f6943f97 100644 --- a/app/views/admin/forms/show.html.erb +++ b/app/views/admin/forms/show.html.erb @@ -100,7 +100,7 @@This alternative version of embed script includes an integrity attribute. @@ -155,7 +155,7 @@
<% end %> <% else %> -diff --git a/app/views/admin/goal_targets/new.html.erb b/app/views/admin/goal_targets/new.html.erb index 7b5d06bc2..ea1f34ea0 100644 --- a/app/views/admin/goal_targets/new.html.erb +++ b/app/views/admin/goal_targets/new.html.erb @@ -10,4 +10,4 @@ url: $(this).attr("href") + "/targets" }); }); - \ No newline at end of file + diff --git a/app/views/admin/goals/_tags.html.erb b/app/views/admin/goals/_tags.html.erb index c3ba77f9c..b31b63ad5 100644 --- a/app/views/admin/goals/_tags.html.erb +++ b/app/views/admin/goals/_tags.html.erb @@ -3,7 +3,7 @@
<%= form.submit class: "usa-button" %>
diff --git a/app/views/admin/omb_cx_reporting_collections/_csv_data.html.erb b/app/views/admin/omb_cx_reporting_collections/_csv_data.html.erb index 2d01b84f3..9c15e08ab 100644 --- a/app/views/admin/omb_cx_reporting_collections/_csv_data.html.erb +++ b/app/views/admin/omb_cx_reporting_collections/_csv_data.html.erb @@ -3,8 +3,7 @@ @@ -38,8 +37,7 @@ :question_total, :start_date, :end_date - ] - %> + ] %> <%= header_fields.join(",") %>+
<%= j + 1 %>. <%= obj.name %>
diff --git a/app/views/admin/organizations/_tags.html.erb b/app/views/admin/organizations/_tags.html.erb index c2c972a15..8b375bc47 100644 --- a/app/views/admin/organizations/_tags.html.erb +++ b/app/views/admin/organizations/_tags.html.erb @@ -1,57 +1,57 @@ <%= form_with(model: @organization, url: admin_organization_path(@organization), local: true) do |f| %> -No Collections at this time diff --git a/app/views/admin/performance/_form.html.erb b/app/views/admin/performance/_form.html.erb index 670a21ee7..8073474b4 100644 --- a/app/views/admin/performance/_form.html.erb +++ b/app/views/admin/performance/_form.html.erb @@ -12,7 +12,6 @@
Name | -Submissions | -Lifespan (Days) | -
---|---|---|
- <%= link_to form[:name], admin_form_path(form[:short_uuid]) %> - | -- <%= form[:counts].num_submissions %> - | -- <%= number_with_precision(form[:counts].lifespan / (3600 * 24), precision: 2) %> - | -
Name | +Submissions | +Lifespan (Days) | +
---|---|---|
+ <%= link_to form[:name], admin_form_path(form[:short_uuid]) %> + | ++ <%= form[:counts].num_submissions %> + | ++ <%= number_with_precision(form[:counts].lifespan / (3600 * 24), precision: 2) %> + | +
@@ -54,9 +54,9 @@ |
Name | -
---|
- <%= link_to form[:name], admin_form_path(form[:short_uuid]) %> - | -
Name | +
---|
+ <%= link_to form[:name], admin_form_path(form[:short_uuid]) %> + | +
-
+
-
+
diff --git a/app/views/admin/service_stages/_form.html.erb b/app/views/admin/service_stages/_form.html.erb index cd4a37dfa..4e1bc932d 100644 --- a/app/views/admin/service_stages/_form.html.erb +++ b/app/views/admin/service_stages/_form.html.erb @@ -52,7 +52,7 @@ <%= form.label :persona_id, "Persona", class: "usa-label" %> Optionally, a - <%=link_to "Persona", admin_personas_path %> + <%= link_to "Persona", admin_personas_path %> can be associated with this Step. <%= form.select :persona_id, options_for_select(Persona.all.map { |p| [p.name, p.id] }, selected: service_stage.persona_id), { prompt: "Select a Persona..." }, { class: "usa-select" } %> diff --git a/app/views/admin/services/_form.html.erb b/app/views/admin/services/_form.html.erb index 758d1108d..f87eb59cf 100644 --- a/app/views/admin/services/_form.html.erb +++ b/app/views/admin/services/_form.html.erb @@ -6,8 +6,7 @@ "Informational", "Data and Research", "Regulatory", -] -%> +] %> <%= form_with(model: service, url: service.persisted? ? admin_service_path(service) : admin_services_path, local: true) do |form| %> <% if service.errors.any? %> diff --git a/app/views/admin/services/_service_managers.html.erb b/app/views/admin/services/_service_managers.html.erb index b41d1efb4..8993ef818 100644 --- a/app/views/admin/services/_service_managers.html.erb +++ b/app/views/admin/services/_service_managers.html.erb @@ -1,55 +1,55 @@
-
+
@@ -143,8 +143,6 @@
No Service Stages defined yet. diff --git a/app/views/admin/site/management.html.erb b/app/views/admin/site/management.html.erb index 260c924ec..91c2f7f24 100644 --- a/app/views/admin/site/management.html.erb +++ b/app/views/admin/site/management.html.erb @@ -7,8 +7,7 @@
All forms have at least one manager. diff --git a/app/views/admin/submissions/_a11_analysis.html.erb b/app/views/admin/submissions/_a11_analysis.html.erb index 3b0123a55..cb31ac6a8 100644 --- a/app/views/admin/submissions/_a11_analysis.html.erb +++ b/app/views/admin/submissions/_a11_analysis.html.erb @@ -1 +1 @@ -<%= render 'components/a11_analysis', { form: form } %> \ No newline at end of file +<%= render 'components/a11_analysis', { form: form } %> diff --git a/app/views/admin/submissions/_a11_chart.html.erb b/app/views/admin/submissions/_a11_chart.html.erb index 8c68d986f..f2c0b96dd 100644 --- a/app/views/admin/submissions/_a11_chart.html.erb +++ b/app/views/admin/submissions/_a11_chart.html.erb @@ -1 +1 @@ -<%= render 'components/admin/a11_chart', form: form %> \ No newline at end of file +<%= render 'components/admin/a11_chart', form: form %> diff --git a/app/views/admin/submissions/_flag.html.erb b/app/views/admin/submissions/_flag.html.erb index 8dedc23c8..94e8df1ba 100644 --- a/app/views/admin/submissions/_flag.html.erb +++ b/app/views/admin/submissions/_flag.html.erb @@ -1,4 +1,4 @@ <%= link_to unflag_admin_form_submission_path(submission.form, submission), id: "flag-submission-#{submission.id}", remote: true, class: "usa-button usa-button--outline", method: :post, data: { confirm: 'Are you sure?' } do %> Flagged -<% end %> \ No newline at end of file +<% end %> diff --git a/app/views/admin/submissions/_responses_by_status.html.erb b/app/views/admin/submissions/_responses_by_status.html.erb index 8226f04b0..0f517eca1 100644 --- a/app/views/admin/submissions/_responses_by_status.html.erb +++ b/app/views/admin/submissions/_responses_by_status.html.erb @@ -1,4 +1,4 @@ -<%= render 'components/responses_by_status', submissions: form.submissions %> \ No newline at end of file +<%= render 'components/responses_by_status', submissions: form.submissions %> diff --git a/app/views/admin/submissions/_responses_per_day.html.erb b/app/views/admin/submissions/_responses_per_day.html.erb index 48fadb63e..86d349919 100644 --- a/app/views/admin/submissions/_responses_per_day.html.erb +++ b/app/views/admin/submissions/_responses_per_day.html.erb @@ -1 +1 @@ -<%= render 'components/admin/responses_per_day', response_groups: @response_groups %> \ No newline at end of file +<%= render 'components/admin/responses_per_day', response_groups: @response_groups %> diff --git a/app/views/admin/submissions/_status_form.html.erb b/app/views/admin/submissions/_status_form.html.erb index e90582b9b..aebaf591a 100644 --- a/app/views/admin/submissions/_status_form.html.erb +++ b/app/views/admin/submissions/_status_form.html.erb @@ -4,7 +4,7 @@
diff --git a/app/views/admin/submissions/_submissions_table.html.erb b/app/views/admin/submissions/_submissions_table.html.erb index ec970eb91..f89f80123 100644 --- a/app/views/admin/submissions/_submissions_table.html.erb +++ b/app/views/admin/submissions/_submissions_table.html.erb @@ -1 +1 @@ -<%= render template: "admin/submissions/index", locals: { form: @form, submissions: @submissions, all_submissions: @all_submissions } %> \ No newline at end of file +<%= render template: "admin/submissions/index", locals: { form: @form, submissions: @submissions, all_submissions: @all_submissions } %> diff --git a/app/views/admin/submissions/_tags.html.erb b/app/views/admin/submissions/_tags.html.erb index 58f35c4ad..3f356ad0a 100644 --- a/app/views/admin/submissions/_tags.html.erb +++ b/app/views/admin/submissions/_tags.html.erb @@ -1,63 +1,63 @@ <%= form_with(model: submission, url: admin_form_submission_path(submission.form, submission), local: true) do |f| %> -
About the diff --git a/app/views/admin/users/_form.html.erb b/app/views/admin/users/_form.html.erb index 5be75b4ca..7a9c039d1 100644 --- a/app/views/admin/users/_form.html.erb +++ b/app/views/admin/users/_form.html.erb @@ -83,7 +83,7 @@
These "Inactive" users have not logged in within 90 days. diff --git a/app/views/admin/users/show.html.erb b/app/views/admin/users/show.html.erb index a0c1ad922..cddc8883a 100644 --- a/app/views/admin/users/show.html.erb +++ b/app/views/admin/users/show.html.erb @@ -14,7 +14,7 @@ <% end %>
<% if @user.inactive? %> -This user is inactive @@ -84,7 +84,7 @@ <% end %> <% else %> -
No Forms at this time @@ -107,7 +107,7 @@ <% end %> <% else %> -
No Digital Products at this time @@ -130,7 +130,7 @@ <% end %> <% else %> -
No Digital Service Accounts at this time @@ -153,7 +153,7 @@ <% end %> <% else %> -
No Websites at this time @@ -198,7 +198,7 @@ <%= render 'components/users/events', events: @user_events %>
No Collections at this time diff --git a/app/views/admin/websites/_results.html.erb b/app/views/admin/websites/_results.html.erb index 16ba6477a..fa37783d7 100644 --- a/app/views/admin/websites/_results.html.erb +++ b/app/views/admin/websites/_results.html.erb @@ -21,8 +21,7 @@
Owner | Domain | Missing fields | - - - <% @websites.each do | website | %> - |
---|---|---|---|
<%= website.site_owner_email %> | -<%= website.domain %> | -<%= website.blankFields %> | -<%= link_to 'Send Website Data Collection Request', "/admin/websites/#{website.id}/collection_request/", data: { confirm: 'Are you sure?' }, class: "usa-button usa-button--outline" %> - |
No logged events exist yet for this website. diff --git a/app/views/admin/websites/gsa.html.erb b/app/views/admin/websites/gsa.html.erb index da41695e8..d3c7e4671 100644 --- a/app/views/admin/websites/gsa.html.erb +++ b/app/views/admin/websites/gsa.html.erb @@ -11,8 +11,7 @@
- <%= link_to "Use a custom date", gsa_admin_websites_url(last_updated: Date.today - 2.weeks)%> + <%= link_to "Use a custom date", gsa_admin_websites_url(last_updated: Date.today - 2.weeks) %> using a `last_updated` date the following format YYYY-MM-DD.
diff --git a/app/views/admin/websites/review.html.erb b/app/views/admin/websites/review.html.erb index 744398eb5..2d8323cd8 100644 --- a/app/views/admin/websites/review.html.erb +++ b/app/views/admin/websites/review.html.erb @@ -21,7 +21,6 @@The website @@ -72,7 +72,7 @@