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

107 lines
2.1 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class Champs::AddressChamp < Champs::TextChamp
def full_address?
data.present?
end
def feature=(value)
return if value.blank?
feature = JSON.parse(value)
self.data = APIGeoService.parse_ban_address(feature)
rescue JSON::ParserError
self.data = nil
end
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']]
else
[address_label]
end
end
def to_s
address_label.presence || ''
end
def for_tag
address_label
end
def for_export
value.present? ? address_label : nil
end
def for_api
address_label
end
def code_departement
if full_address?
address.fetch('department_code')
end
end
def code_region
if full_address?
address.fetch('region_code')
end
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
if full_address?
"#{APIGeoService.commune_name(code_departement, address['city_code'])} (#{address['postal_code']})"
end
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
end