diff --git a/app/controllers/items_controller.rb b/app/controllers/items_controller.rb index c87e608e92..c63efbf76e 100644 --- a/app/controllers/items_controller.rb +++ b/app/controllers/items_controller.rb @@ -91,6 +91,14 @@ def update def deactivate item = current_organization.items.find(params[:id]) + + partners = Partner + .joins(families: {children: :requested_items}) + .where(organization_id: current_organization.id) + .where(children: {active: true}) + .where(items: {id: item.id}) + .distinct + begin item.deactivate! rescue => e @@ -99,6 +107,11 @@ def deactivate return end + if partners.any? + flash[:alert] = "The following partners have active children with this item: " + + partners.map(&:name).map(&:downcase).sort.join(", ") + end + flash[:notice] = "#{item.name} has been deactivated." redirect_to items_path end diff --git a/app/models/item.rb b/app/models/item.rb index 15e7b1382c..405ee4d7b6 100644 --- a/app/models/item.rb +++ b/app/models/item.rb @@ -52,6 +52,7 @@ class Item < ApplicationRecord has_many :donations, through: :line_items, source: :itemizable, source_type: "::Donation" has_many :distributions, through: :line_items, source: :itemizable, source_type: "::Distribution" has_many :request_units, class_name: "ItemUnit", dependent: :destroy + has_and_belongs_to_many :children, class_name: "Partners::Child" scope :active, -> { where(active: true) } diff --git a/spec/controllers/items_controller_spec.rb b/spec/controllers/items_controller_spec.rb index 96fad6b4bc..a445af9900 100644 --- a/spec/controllers/items_controller_spec.rb +++ b/spec/controllers/items_controller_spec.rb @@ -219,6 +219,24 @@ expect(response).to have_notice end end + + describe "PATCH #deactivate" do + let(:item) { create(:item, organization: organization) } + let!(:partner) { create(:partner, organization: organization, name: "Helping Hands") } + let!(:family) { create(:partners_family, partner: partner) } + let!(:child) { create(:partners_child, family: family, active: true) } + + before do + child.requested_items << item + end + + it "sets a flash alert listing partners with active children for this item" do + patch :deactivate, params: { id: item.id } + + expect(response).to redirect_to(items_path) + expect(flash[:alert]).to include("helping hands") # downcased in controller + end + end end context "While not signed in" do