feat(dossier): commune champ is an autocomplete now

This commit is contained in:
Paul Chavard 2023-10-13 16:06:26 +02:00
parent b92ccc0a09
commit 34a76d8afd
22 changed files with 231 additions and 160 deletions

View file

@ -1,6 +1,6 @@
class Champs::CommuneChamp < Champs::TextChamp
store_accessor :value_json, :code_departement, :code_postal
before_validation :on_code_postal_change
before_save :on_codes_change, if: :should_refresh_after_code_change?
def for_export
[to_s, code? ? code : '', departement? ? departement_code_and_name : '']
@ -37,7 +37,7 @@ class Champs::CommuneChamp < Champs::TextChamp
alias postal_code code_postal
def name
if code?
if departement? && code?
APIGeoService.commune_name(code_departement, code).presence || safe_to_s
else
safe_to_s
@ -45,7 +45,7 @@ class Champs::CommuneChamp < Champs::TextChamp
end
def to_s
if code?
if departement? && code_postal? && code?
name = APIGeoService.commune_name(code_departement, code)
name.present? ? "#{name} (#{code_postal})" : safe_to_s
else
@ -69,46 +69,29 @@ class Champs::CommuneChamp < Champs::TextChamp
end
end
def value=(code)
if code.blank? || !code_postal?
self.code_departement = nil
self.external_id = nil
super(nil)
else
commune = communes.find { _1[:code] == code }
if commune.present?
self.code_departement = commune[:departement_code]
self.external_id = commune[:code]
super(commune[:name])
else
self.code_departement = nil
self.external_id = nil
super(nil)
end
end
end
def html_label?
false
end
def legend_label?
true
end
private
def safe_to_s
value.present? ? value.to_s : ''
end
def on_code_postal_change
if code_postal_changed?
if communes.one?
self.value = communes.first[:code]
else
self.value = nil
end
def on_codes_change
return if !code?
commune = communes.find { _1[:code] == code }
if commune.present?
self.code_departement = commune[:departement_code]
self.value = commune[:name]
else
self.code_departement = nil
self.code_postal = nil
self.external_id = nil
self.value = nil
end
end
def should_refresh_after_code_change?
!departement? || code_postal_changed? || external_id_changed?
end
end

View file

@ -32,7 +32,7 @@ class TypesDeChamp::PrefillCommuneTypeDeChamp < TypesDeChamp::PrefillTypeDeChamp
end
def code_postal_and_commune_attributes(champ, postal_code, commune_code)
code_postal_attributes(champ, postal_code).merge(value: commune_code)
code_postal_attributes(champ, postal_code).merge(external_id: commune_code)
end
def departements