diff --git a/app/models/case_log.rb b/app/models/case_log.rb index 08ae06a8f..49c3a8a73 100644 --- a/app/models/case_log.rb +++ b/app/models/case_log.rb @@ -24,6 +24,7 @@ class CaseLog < ApplicationRecord validates_with CaseLogValidator before_validation :recalculate_start_year!, if: :startdate_changed? + before_validation :reset_scheme_location!, if: :scheme_changed? before_validation :process_postcode_changes!, if: :postcode_full_changed? before_validation :process_previous_postcode_changes!, if: :ppostcode_full_changed? before_validation :reset_invalidated_dependent_fields! @@ -689,4 +690,8 @@ private def upcase_and_remove_whitespace(string) string.present? ? string.upcase.gsub(/\s+/, "") : string end + + def reset_scheme_location! + self.location = nil + end end diff --git a/app/models/derived_variables/case_log_variables.rb b/app/models/derived_variables/case_log_variables.rb index 831d3c7ce..8a80a4adf 100644 --- a/app/models/derived_variables/case_log_variables.rb +++ b/app/models/derived_variables/case_log_variables.rb @@ -68,6 +68,12 @@ module DerivedVariables::CaseLogVariables self.hhtype = household_type self.new_old = new_or_existing_tenant self.vacdays = property_vacant_days + + if is_supported_housing? + if scheme && scheme.locations.size == 1 + self.location = scheme.locations.first + end + end end private diff --git a/spec/models/case_log_spec.rb b/spec/models/case_log_spec.rb index b07b913fe..bca9cbb32 100644 --- a/spec/models/case_log_spec.rb +++ b/spec/models/case_log_spec.rb @@ -1678,6 +1678,21 @@ RSpec.describe CaseLog do expect(case_log["tshortfall_known"]).to eq(0) end end + + context "when a case log is a supported housing log" do + before { case_log.needstype = 2 } + context "and a scheme with a single log is selected" do + let(:scheme) { FactoryBot.create(:scheme) } + let!(:location) { FactoryBot.create(:location, scheme:)} + before { case_log.update!(scheme:) } + + it "derives the scheme location" do + record_from_db = ActiveRecord::Base.connection.execute("select location_id from case_logs where id=#{case_log.id}").to_a[0] + expect(record_from_db["location_id"]).to eq(location.id) + expect(case_log["location_id"]).to eq(location.id) + end + end + end end describe "optional fields" do @@ -2147,4 +2162,6 @@ RSpec.describe CaseLog do end end end + + end