Browse Source

Lookup location by postcode

pull/2098/head
Kat 2 years ago
parent
commit
99e844b2bd
  1. 11
      app/models/location.rb
  2. 5
      db/migrate/20231218105226_add_la_inferred_to_locations.rb
  3. 3
      db/schema.rb
  4. 15
      spec/models/location_spec.rb

11
app/models/location.rb

@ -169,10 +169,6 @@ class Location < ApplicationRecord
errors.add :postcode, error_message
else
self.postcode = PostcodeService.clean(postcode)
if postcode_changed?
self.location_admin_district = nil
self.location_code = nil
end
end
end
@ -200,9 +196,16 @@ private
def lookup_postcode!
result = PIO.lookup(postcode)
unless location_admin_district_changed?
self.location_admin_district = nil
self.location_code = nil
end
if result
self.location_code = result[:location_code]
self.location_admin_district = result[:location_admin_district]
self.is_la_inferred = true
else
self.is_la_inferred = false
end
end
end

5
db/migrate/20231218105226_add_la_inferred_to_locations.rb

@ -0,0 +1,5 @@
class AddLaInferredToLocations < ActiveRecord::Migration[7.0]
def change
add_column :locations, :is_la_inferred, :boolean
end
end

3
db/schema.rb

@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.0].define(version: 2023_12_04_101105) do
ActiveRecord::Schema[7.0].define(version: 2023_12_18_105226) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
@ -355,6 +355,7 @@ ActiveRecord::Schema[7.0].define(version: 2023_12_04_101105) do
t.datetime "startdate"
t.string "location_admin_district"
t.boolean "confirmed"
t.boolean "is_la_inferred"
t.index ["old_id"], name: "index_locations_on_old_id", unique: true
t.index ["scheme_id"], name: "index_locations_on_scheme_id"
end

15
spec/models/location_spec.rb

@ -24,6 +24,7 @@ RSpec.describe Location, type: :model do
location.postcode = "M1 1AE"
location.save!
expect(location.location_code).to eq("E08000003")
expect(location.is_la_inferred).to eq(true)
end
it "infers and returns the list of local authorities" do
@ -33,6 +34,20 @@ RSpec.describe Location, type: :model do
expect(location.linked_local_authorities.active(Time.zone.local(2023, 4, 1)).first.code).to eq("E06000063")
end
context "when local authority cannot be inferred" do
before do
stub_request(:get, /api.postcodes.io\/postcodes\/CA101AA/)
.to_return(status: 200, body: '{"status":200}', headers: {})
end
it "does not set the local authority" do
location.update!(postcode: "CA10 1AA", location_code: nil, location_admin_district: nil)
expect(location.location_code).to eq(nil)
expect(location.linked_local_authorities.count).to eq(0)
expect(location.is_la_inferred).to eq(false)
end
end
context "when location_code is no in LocalAuthorities table" do
before do
stub_request(:get, /api.postcodes.io\/postcodes\/CA101AA/)

Loading…
Cancel
Save