demarches-normaliennes/app/models/champs/address_champ.rb

137 lines
2.6 KiB
Ruby
Raw Normal View History

2018-02-13 18:18:20 +01:00
class Champs::AddressChamp < Champs::TextChamp
2021-02-17 13:54:24 +01:00
def full_address?
data.present?
end
def feature
data.to_json if full_address?
end
def feature=(value)
if value.blank?
self.data = nil
else
feature = JSON.parse(value)
if feature.key?('properties')
self.data = APIGeoService.parse_ban_address(feature)
else
self.data = feature
end
end
rescue JSON::ParserError
self.data = nil
end
2021-02-17 13:54:24 +01:00
def address
full_address? ? data : nil
end
def address_label
full_address? ? data['label'] : value
end
def search_terms
if full_address?
[data['label'], data['department_name'], data['region_name'], data['city_name']]
2021-02-17 13:54:24 +01:00
else
[address_label]
end
end
def to_s
2021-04-08 17:43:45 +02:00
address_label.presence || ''
2021-02-17 13:54:24 +01:00
end
2024-04-02 17:05:44 +02:00
def for_tag(path = :value)
case path
when :value
address_label
when :departement
departement_code_and_name || ''
when :commune
commune_name || ''
end
2021-02-17 13:54:24 +01:00
end
2024-04-02 17:05:44 +02:00
def for_export(path = :value)
case path
when :value
value.present? ? address_label : nil
when :departement
departement_code_and_name
when :commune
commune_name
end
2021-02-17 13:54:24 +01:00
end
def for_api
address_label
end
def code_departement
if full_address?
address.fetch('department_code')
end
2021-02-17 13:54:24 +01:00
end
def code_region
if full_address?
address.fetch('region_code')
end
2021-02-17 13:54:24 +01:00
end
def departement_name
APIGeoService.departement_name(code_departement)
end
def departement_code_and_name
if full_address?
"#{code_departement} #{departement_name}"
end
end
def departement
if full_address?
{ code: code_departement, name: departement_name }
end
end
def commune_name
return if !full_address?
commune = APIGeoService.commune_name(code_departement, address['city_code'])
return commune if address['postal_code'].blank?
"#{commune} (#{address['postal_code']})"
end
def commune
if full_address?
city_code = address.fetch('city_code')
city_name = address.fetch('city_name')
postal_code = address.fetch('postal_code')
commune_name = APIGeoService.commune_name(code_departement, city_code)
commune_code = APIGeoService.commune_code(code_departement, city_name)
if commune_name.present?
{
code: city_code,
name: commune_name
}
elsif commune_code.present?
{
code: commune_code,
name: city_name
}
else
{
code: city_code,
name: city_name
}
end.merge(postal_code:)
end
end
2018-02-13 18:18:20 +01:00
end