From e44ab779313f6c89be681d28c9b3f64fcd7700b4 Mon Sep 17 00:00:00 2001 From: Martin Fenner Date: Wed, 10 Apr 2019 08:06:35 +0200 Subject: [PATCH] check for active clients before deleting provider. #229 --- app/controllers/concerns/countable.rb | 8 ++++++++ app/controllers/providers_controller.rb | 4 ++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/app/controllers/concerns/countable.rb b/app/controllers/concerns/countable.rb index 52c9570cd..18da6cf6b 100644 --- a/app/controllers/concerns/countable.rb +++ b/app/controllers/concerns/countable.rb @@ -27,6 +27,14 @@ def client_count(provider_id: nil) response.results.total > 0 ? facet_by_cumulative_year(response.response.aggregations.cumulative_years.buckets) : [] end + # count active clients by provider. Provider can only be deleted when there are no active clients. + def active_client_count(provider_id: nil) + return 0 unless provider_id.present? + + response = Client.query(nil, provider_id: provider_id, page: { number: 1, size: 0 }) + response.results.total + end + # show provider count for admin # count until the previous year if provider has been deleted def provider_count(provider_id: nil) diff --git a/app/controllers/providers_controller.rb b/app/controllers/providers_controller.rb index d5c17f2e8..531755ba2 100644 --- a/app/controllers/providers_controller.rb +++ b/app/controllers/providers_controller.rb @@ -146,8 +146,8 @@ def totals # a provider with clients or prefixes can't be deleted def destroy logger = Logger.new(STDOUT) - if @provider.client_count.present? - message = "Can't delete provider that has clients." + if @provider.active_client_count > 0 + message = "Can't delete provider that has active clients." status = 400 logger.warn message render json: { errors: [{ status: status.to_s, title: message }] }.to_json, status: status