2016-10-19 03:11:36 +00:00
|
|
|
# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
|
2013-08-06 10:29:35 +00:00
|
|
|
|
|
|
|
class Observer::User::Geo < ActiveRecord::Observer
|
|
|
|
observe 'user'
|
|
|
|
|
|
|
|
def before_create(record)
|
|
|
|
check_geo(record)
|
2017-06-16 22:53:20 +00:00
|
|
|
true
|
2013-08-06 10:29:35 +00:00
|
|
|
end
|
2015-05-07 10:27:12 +00:00
|
|
|
|
2013-08-06 10:29:35 +00:00
|
|
|
def before_update(record)
|
|
|
|
check_geo(record)
|
2017-06-16 22:53:20 +00:00
|
|
|
true
|
2013-08-06 10:29:35 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# check if geo need to be updated
|
|
|
|
def check_geo(record)
|
|
|
|
|
2015-05-07 11:12:40 +00:00
|
|
|
location = %w(address street zip city country)
|
2013-08-06 10:29:35 +00:00
|
|
|
|
|
|
|
# check if geo update is needed based on old/new location
|
|
|
|
if record.id
|
2016-03-08 06:32:58 +00:00
|
|
|
current = User.find_by(id: record.id)
|
2014-02-03 19:23:00 +00:00
|
|
|
return if !current
|
2013-08-06 10:29:35 +00:00
|
|
|
|
|
|
|
current_location = {}
|
|
|
|
location.each { |item|
|
|
|
|
current_location[item] = current[item]
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
# get full address
|
|
|
|
next_location = {}
|
|
|
|
location.each { |item|
|
|
|
|
next_location[item] = record[item]
|
|
|
|
}
|
|
|
|
|
|
|
|
# return if address hasn't changed and geo data is already available
|
2016-03-08 06:32:58 +00:00
|
|
|
return if (current_location == next_location) && record.preferences['lat'] && record.preferences['lng']
|
2013-08-06 10:29:35 +00:00
|
|
|
|
|
|
|
# geo update
|
2015-05-07 12:10:38 +00:00
|
|
|
geo_update(record)
|
2013-08-06 10:29:35 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# update geo data of user
|
|
|
|
def geo_update(record)
|
|
|
|
address = ''
|
2015-05-07 11:12:40 +00:00
|
|
|
location = %w(address street zip city country)
|
2013-08-06 10:29:35 +00:00
|
|
|
location.each { |item|
|
|
|
|
if record[item] && record[item] != ''
|
|
|
|
address = address + ',' + record[item]
|
|
|
|
end
|
|
|
|
}
|
|
|
|
|
|
|
|
# return if no address is given
|
|
|
|
return if address == ''
|
|
|
|
|
2013-08-15 20:40:22 +00:00
|
|
|
# lookup
|
2016-03-08 06:32:58 +00:00
|
|
|
latlng = Service::GeoLocation.geocode(address)
|
2013-08-06 10:29:35 +00:00
|
|
|
return if !latlng
|
|
|
|
|
|
|
|
# store data
|
|
|
|
record.preferences['lat'] = latlng[0]
|
|
|
|
record.preferences['lng'] = latlng[1]
|
|
|
|
end
|
2014-02-03 19:23:00 +00:00
|
|
|
end
|