From c3f0a89184c6e54650a65b37599e6bff2e50c6e8 Mon Sep 17 00:00:00 2001 From: Julian Gallimore Date: Wed, 18 Oct 2023 13:30:08 +0200 Subject: [PATCH] Task to fill lat/lng for those labs missing values Over the past two years a bug in lab form resulted in no lat/lng being saved to the database. With this task, call the Places API to try fill in missing values. To test/run on production server. --- lib/tasks/fixes.rake | 60 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 lib/tasks/fixes.rake diff --git a/lib/tasks/fixes.rake b/lib/tasks/fixes.rake new file mode 100644 index 00000000..3e267387 --- /dev/null +++ b/lib/tasks/fixes.rake @@ -0,0 +1,60 @@ +require 'httparty' + +namespace :fixes do + + desc "Any labs without GEO coordinates, fill from address" + task labsgeo: :environment do + + labs = Lab.where(latitude: nil) + + labs.each do |lab| + + query_lines = [] + query_lines << lab.address_1 if lab.address_1.present? + query_lines << lab.address_2 if lab.address_2.present? + query_lines << lab.city if lab.city.present? + query_lines << lab.county if lab.county.present? + query_lines << lab.subregion if lab.subregion.present? + query_lines << lab.region if lab.region.present? + query_lines << lab.postal_code if lab.postal_code.present? + query_lines << lab.country_code if lab.country_code.present? + + querytext = query_lines.join(', ') + + puts querytext + + response = HTTParty.get('https://maps.googleapis.com/maps/api/place/findplacefromtext/json', + query: { + key: ENV['GOOGLE_PLACES_API_KEY'], + input: querytext, + fields: 'formatted_address,name,geometry', + inputtype: 'textquery', + }, + ) + + data = JSON.parse(response.body) + + if !data.key?('candidates') || !data['candidates'].is_a?(Array) + warn "#{lab.slug}: No results returned." + next + end + + if data['candidates'].empty? + warn "#{lab.slug}: No results returned." + next + end + + if data['candidates'].length > 1 + warn "#{lab.slug}: More than one result, skipping..." + next + end + + result = data['candidates'].first + + puts "FOUND: #{result['geometry']['location']['lat']}" + + lab.update(latitude: result['geometry']['location']['lat'], longitude: result['geometry']['location']['lng']) + + end + end +end