performs_geo_lookup.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. # Perform geo data lookup on user changes.
  3. module User::PerformsGeoLookup
  4. extend ActiveSupport::Concern
  5. included do
  6. before_create :user_check_geo_location
  7. before_update :user_check_geo_location
  8. end
  9. private
  10. def user_check_geo_location
  11. location = %w[address street zip city country]
  12. # check if geo update is needed based on old/new location
  13. if id
  14. current = User.find_by(id: id)
  15. return if !current
  16. current_location = {}
  17. location.each do |item|
  18. current_location[item] = current[item]
  19. end
  20. end
  21. # get full address
  22. next_location = {}
  23. location.each do |item|
  24. next_location[item] = attributes[item]
  25. end
  26. # return if address hasn't changed and geo data is already available
  27. return if (current_location == next_location) && preferences['lat'] && preferences['lng']
  28. # geo update
  29. user_update_geo_location
  30. end
  31. def user_update_geo_location
  32. address = ''
  33. location = %w[address street zip city country]
  34. location.each do |item|
  35. next if attributes[item].blank?
  36. if address.present?
  37. address += ', '
  38. end
  39. address += attributes[item]
  40. end
  41. # return if no address is given
  42. return if address.blank?
  43. # lookup
  44. latlng = Service::GeoLocation.geocode(address)
  45. return if !latlng
  46. # store data
  47. preferences['lat'] = latlng[0]
  48. preferences['lng'] = latlng[1]
  49. end
  50. end