Submit social housing lettings and sales data (CORE)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.2 KiB

class AddressSearchController < ApplicationController
before_action :authenticate_user!
before_action :set_log, only: %i[manual_input search_input]
2 months ago
def index
query = params[:query]
2 months ago
if query.match?(/\A\d+\z/) && query.length > 5
# Query is all numbers and greater than 5 digits, assume it's a UPRN
service = UprnClient.new(query)
2 months ago
service.call
if service.error.present?
render json: { error: service.error }, status: :unprocessable_entity
else
presenter = UprnDataPresenter.new(service.result)
render json: [{ text: presenter.address, value: presenter.uprn }]
2 months ago
end
elsif query.match?(/[a-zA-Z]/)
# Query contains letters, assume it's an address
service = AddressClient.new(query)
2 months ago
service.call
if service.error.present?
render json: { error: service.error }, status: :unprocessable_entity
else
results = service.result.map do |result|
presenter = AddressDataPresenter.new(result)
{ text: presenter.address, value: presenter.uprn }
end
render json: results
2 months ago
end
2 months ago
else
2 months ago
# Query is ambiguous, use both APIs and merge results
address_service = AddressClient.new(query)
uprn_service = UprnClient.new(query)
2 months ago
address_service.call
uprn_service.call
1 month ago
results = (address_service.result || []) + (uprn_service.result || [])
2 months ago
if address_service.error.present? && uprn_service.error.present?
render json: { error: "Address and UPRN are not recognised." }, status: :unprocessable_entity
2 months ago
else
formatted_results = results.map do |result|
presenter = AddressDataPresenter.new(result)
{ text: presenter.address, value: presenter.uprn }
end
render json: formatted_results
2 months ago
end
2 months ago
end
end
def manual_input
@log.update!(manual_address_entry_selected: true)
redirect_to polymorphic_url([@log, :address])
end
def search_input
@log.update!(manual_address_entry_selected: false)
redirect_to polymorphic_url([@log, :address_search])
end
private
def set_log
@log = current_user.send("#{params[:log_type]}s").find(params[:log_id])
end
2 months ago
end