diff --git a/app/services/bulk_update_from_csv/update_locations_from_csv_service.rb b/app/services/bulk_update_from_csv/update_locations_from_csv_service.rb index cb28f6c81..5a3ce18ab 100644 --- a/app/services/bulk_update_from_csv/update_locations_from_csv_service.rb +++ b/app/services/bulk_update_from_csv/update_locations_from_csv_service.rb @@ -104,8 +104,13 @@ private def update_scheme(location, original_attributes, value) scheme = Scheme.find_by(id: value.delete("S")) if scheme.present? - location["scheme_id"] = scheme.id - Rails.logger.info("Updating location #{original_attributes['location_code']} with scheme: S#{scheme.id}") + original_scheme = Scheme.find_by(id: original_attributes["scheme_code"].delete("S")) + if original_scheme.nil? || !([original_scheme.owning_organisation] + original_scheme.owning_organisation.parent_organisations + original_scheme.owning_organisation.child_organisations).include?(scheme.owning_organisation) + Rails.logger.info("Cannot update location #{original_attributes['location_code']} with scheme_code: #{value}. Scheme with id #{value} is not in organisation that does not have relationship with the original organisation") + else + location["scheme_id"] = scheme.id + Rails.logger.info("Updating location #{original_attributes['location_code']} with scheme: S#{scheme.id}") + end else Rails.logger.info("Cannot update location #{original_attributes['location_code']} with scheme_code: #{value}. Scheme with id #{value} is not in the database") end diff --git a/spec/lib/tasks/update_schemes_and_locations_from_csv_spec.rb b/spec/lib/tasks/update_schemes_and_locations_from_csv_spec.rb index ae2a8864c..2f981776e 100644 --- a/spec/lib/tasks/update_schemes_and_locations_from_csv_spec.rb +++ b/spec/lib/tasks/update_schemes_and_locations_from_csv_spec.rb @@ -314,7 +314,7 @@ RSpec.describe "bulk_update" do let(:updated_locations_csv_path) { "updated_locations.csv" } let(:wrong_file_path) { "/test/no_csv_here.csv" } let!(:scheme) { FactoryBot.create(:scheme, service_name: "Scheme 1") } - let!(:different_scheme) { FactoryBot.create(:scheme, service_name: "Different scheme") } + let!(:different_scheme) { FactoryBot.create(:scheme, service_name: "Different scheme", owning_organisation: scheme.owning_organisation) } let(:locations) do create_list(:location,