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,21 +1,3 @@
class EditableChamp::CommunesComponent < EditableChamp::EditableChampBaseComponent
include ApplicationHelper
def dsfr_champ_container
:fieldset
end
private
def commune_options
@champ.communes.map { ["#{_1[:name]} (#{_1[:postal_code]})", _1[:code]] }
end
def code_postal_input_id
"#{@champ.input_id}-code_postal"
end
def commune_select_options
{ selected: @champ.selected }.merge(@champ.mandatory? ? { prompt: '' } : { include_blank: '' })
end
end

View file

@ -1,5 +0,0 @@
---
en:
postal_code: "Enter <strong>the postal code</strong>"
commune: "Select <strong>the municipality</strong> from the list"
not_found: No municipality found for postal code %{postal_code}. Please check that you haven't made any mistakes.

View file

@ -1,5 +0,0 @@
---
fr:
postal_code: "Renseignez le <strong>code postal</strong>"
commune: "Sélectionnez la commune dans la liste"
not_found: Aucune commune trouvée pour le code postal %{postal_code}. Verifiez que vous n'avez pas fait derreur.

View file

@ -1,23 +1,2 @@
.fr-fieldset__element.fr-mb-0
.fr-input-group
= @form.label :code_postal, t('.postal_code').html_safe, class: 'fr-label', for: code_postal_input_id
= @form.text_field :code_postal, required: @champ.required?, id: code_postal_input_id, class: "width-33-desktop width-100-mobile small-margin fr-input"
- if @champ.code_postal?
- if commune_options.empty?
.fr-error-text.mb-4= t('.not_found', postal_code: @champ.code_postal)
.fr-fieldset__element.fr-mb-0
- if commune_options.empty?
-# noop
- elsif commune_options.size <= 3
%fieldset.fr-fieldset
.fr-fieldset__legend--regular.fr-fieldset__legend= t('.commune').html_safe
- commune_options.each.with_index do |(option, value), index|
.fr-fieldset__element
.fr-radio-group
= @form.radio_button :value, value, checked: @champ.selected == value, id: "#{code_postal_input_id}-#{value.parameterize}"
= @form.label :value, option, for: "#{code_postal_input_id}-#{value.parameterize}", class: 'fr-label'
- else
= @form.label :value, t('.commune').html_safe, for: @champ.input_id, class: 'fr-label'
= @form.select :value, commune_options, commune_select_options, required: @champ.required?, id: @champ.input_id, aria: { describedby: @champ.describedby_id }, class: "width-33-desktop width-100-mobile fr-select"
= render Dsfr::ComboboxComponent.new form: @form, name: :external_id, url: data_sources_data_source_commune_path, selected: [@champ.to_s, @champ.selected], id: @champ.input_id, class: 'fr-select', describedby: @champ.describedby_id do
= @form.hidden_field :code_postal, data: { value_slot: 'data:string' }

View file

@ -0,0 +1,76 @@
class DataSources::CommuneController < ApplicationController
def search
if params[:q].present? && params[:q].length > 1
response = fetch_results
if response.success?
results = JSON.parse(response.body, symbolize_names: true)
render json: format_results(results)
else
render json: []
end
else
render json: []
end
end
private
def fetch_results
if postal_code?(params[:q])
fetch_by_postal_code(params[:q])
else
fetch_by_name(params[:q])
end
end
def fetch_by_name(name)
Typhoeus.get("#{API_GEO_URL}/communes", params: {
type: 'commune-actuelle,arrondissement-municipal',
nom: name,
boost: 'population',
limit: 20
})
end
def fetch_by_postal_code(postal_code)
Typhoeus.get("#{API_GEO_URL}/communes", params: {
type: 'commune-actuelle,arrondissement-municipal',
codePostal: postal_code,
boost: 'population',
limit: 10
})
end
def postal_code?(string)
string.match?(/\A[-+]?\d+\z/) ? true : false
end
def format_results(results)
results.reject(&method(:code_metropole?)).flat_map do |result|
item = {
name: result[:nom].tr("'", ''),
code: result[:code],
epci_code: result[:codeEpci],
departement_code: result[:codeDepartement]
}.compact
if result[:codesPostaux].present?
result[:codesPostaux].map { item.merge(postal_code: _1) }
else
[item]
end.map do |item|
{
label: "#{item[:name]} (#{item[:postal_code]})",
value: item[:code],
data: item[:postal_code]
}
end
end
end
def code_metropole?(result)
result[:code].in?(['75056', '13055', '69123'])
end
end

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

View file

@ -3,4 +3,4 @@ en:
attributes:
champs/commune_champ:
hints:
value: "Enter the municipality's zip code, then select the municipality from the list"
value: "Enter the city name or zip code, then select the municipality from the list"

View file

@ -3,4 +3,4 @@ fr:
attributes:
champs/commune_champ:
hints:
value: "Renseignez le code postal de la ville puis, ensuite, sélectionnez la commune dans la liste"
value: "Renseignez le nom ou le code postal de la ville puis, sélectionnez la commune dans la liste"

View file

@ -224,6 +224,8 @@ Rails.application.routes.draw do
namespace :data_sources do
get :adresse, to: 'adresse#search', as: :data_source_adresse
get :commune, to: 'commune#search', as: :data_source_commune
get :search_domaine_fonct, to: 'chorus#search_domaine_fonct', as: :search_domaine_fonct
get :search_centre_couts, to: 'chorus#search_centre_couts', as: :search_centre_couts
get :search_ref_programmation, to: 'chorus#search_ref_programmation', as: :search_ref_programmation

View file

@ -122,9 +122,8 @@ FactoryBot.define do
factory :champ_communes, class: 'Champs::CommuneChamp' do
type_de_champ { association :type_de_champ_communes, procedure: dossier.procedure }
value { 'Coye-la-Forêt (60580)' }
value_json { { "departement" => "Oise", "code_departement" => "60" } }
external_id { "60172" }
external_id { '60172' }
code_postal { '60580' }
end
factory :champ_epci, class: 'Champs::EpciChamp' do

113
spec/fixtures/cassettes/communes.yml vendored Normal file
View file

@ -0,0 +1,113 @@
---
http_interactions:
- request:
method: get
uri: https://geo.api.gouv.fr/communes?boost=population&codePostal=60&limit=10&type=commune-actuelle,arrondissement-municipal
body:
encoding: US-ASCII
string: ''
headers:
User-Agent:
- demarches-simplifiees.fr
Expect:
- ''
response:
status:
code: 200
message: ''
headers:
Server:
- nginx/1.10.3 (Ubuntu)
Date:
- Fri, 03 Nov 2023 16:28:05 GMT
Content-Type:
- application/json; charset=utf-8
Content-Length:
- '2'
X-Powered-By:
- Express
Vary:
- Origin
Etag:
- W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"
Strict-Transport-Security:
- max-age=15552000
body:
encoding: ASCII-8BIT
string: "[]"
recorded_at: Fri, 03 Nov 2023 16:28:05 GMT
- request:
method: get
uri: https://geo.api.gouv.fr/communes?boost=population&codePostal=6040&limit=10&type=commune-actuelle,arrondissement-municipal
body:
encoding: US-ASCII
string: ''
headers:
User-Agent:
- demarches-simplifiees.fr
Expect:
- ''
response:
status:
code: 200
message: ''
headers:
Server:
- nginx/1.10.3 (Ubuntu)
Date:
- Fri, 03 Nov 2023 16:28:05 GMT
Content-Type:
- application/json; charset=utf-8
Content-Length:
- '2'
X-Powered-By:
- Express
Vary:
- Origin
Etag:
- W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"
Strict-Transport-Security:
- max-age=15552000
body:
encoding: ASCII-8BIT
string: "[]"
recorded_at: Fri, 03 Nov 2023 16:28:05 GMT
- request:
method: get
uri: https://geo.api.gouv.fr/communes?boost=population&codePostal=60400&limit=10&type=commune-actuelle,arrondissement-municipal
body:
encoding: US-ASCII
string: ''
headers:
User-Agent:
- demarches-simplifiees.fr
Expect:
- ''
response:
status:
code: 200
message: ''
headers:
Server:
- nginx/1.10.3 (Ubuntu)
Date:
- Fri, 03 Nov 2023 16:28:05 GMT
Content-Type:
- application/json; charset=utf-8
Content-Length:
- '1608'
Vary:
- Accept-Encoding
- Origin
X-Powered-By:
- Express
Etag:
- W/"648-ePvxexacWlkxvdJ8v6an7VGvHMo"
Strict-Transport-Security:
- max-age=15552000
body:
encoding: ASCII-8BIT
string: !binary |-
W3sibm9tIjoiQXBwaWxseSIsImNvZGUiOiI2MDAyMSIsImNvZGVEZXBhcnRlbWVudCI6IjYwIiwic2lyZW4iOiIyMTYwMDAyMTYiLCJjb2RlRXBjaSI6IjI0NjAwMDc1NiIsImNvZGVSZWdpb24iOiIzMiIsImNvZGVzUG9zdGF1eCI6WyI2MDQwMCJdLCJwb3B1bGF0aW9uIjo1Mjl9LHsibm9tIjoiQmFixZN1ZiIsImNvZGUiOiI2MDAzNyIsImNvZGVEZXBhcnRlbWVudCI6IjYwIiwic2lyZW4iOiIyMTYwMDAzNjQiLCJjb2RlRXBjaSI6IjI0NjAwMDc1NiIsImNvZGVSZWdpb24iOiIzMiIsImNvZGVzUG9zdGF1eCI6WyI2MDQwMCJdLCJwb3B1bGF0aW9uIjo1MTB9LHsibm9tIjoiQmVhdXJhaW5zLWzDqHMtTm95b24iLCJjb2RlIjoiNjAwNTUiLCJjb2RlRGVwYXJ0ZW1lbnQiOiI2MCIsInNpcmVuIjoiMjE2MDAwNTQ3IiwiY29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YwIiwic2lyZW4iOiIyMTYwMDE4MDAiLCJjb2RlRXBjaSI6IjI0NjAwMDc1NiIsImNvZGVSZWdpb24iOiIzMiIsImNvZGVzUG9zdGF1eCI6WyI2MDQwMCJdLCJwb3B1bGF0aW9uIjo5MDh9LHsibm9tIjoiQ3V0cyIsImNvZGUiOiI2MDE4OSIsImNvZGVEZXBhcnRlbWVudCI6IjYwIiwic2lyZW4iOiIyMTYwMDE4ODMiLCJjb2RlRXBjaSI6IjI0NjAwMDc1NiIsImNvZGVSZWdpb24iOiIzMiIsImNvZGVzUG9zdGF1eCI6WyI2MDQwMCJdLCJwb3B1bGF0aW9uIjo5Njd9LHsibm9tIjoiR2VudnJ5IiwiY29kZSI6IjYwMjcwIiwiY29kZURlcGFydGVtZW50IjoiNjAiLCJzaXJlbiI6IjIxNjAwMjY3NSIsImNvZGVFcGNpIjoiMjQ2MDAwNzU2IiwiY29kZVJlZ2lvbiI6IjMyIiwiY29kZXNQb3N0YXV4IjpbIjYwNDAwIl0sInBvcHVsYXRpb24iOjMzNX1d
recorded_at: Fri, 03 Nov 2023 16:28:05 GMT
recorded_with: VCR 6.1.0

View file

@ -1,47 +0,0 @@
describe Migrations::NormalizeCommunesJob, type: :job do
let(:champ) { create(:champ_communes, external_id: code_insee, code_departement:) }
let(:code_insee) { '97209' }
let(:value) { 'Fort-de-France (97200)' }
let(:code_departement) { nil }
before { champ.update_column(:value, value) }
subject { described_class.perform_now([champ.id]) }
context 'Fort-de-France' do
it 'assign code_departement and code_postal' do
expect(champ.reload.code_postal).to be_nil
expect(champ.reload.code_departement).to be_nil
subject
expect(champ.reload.code_postal).to eq('97200')
expect(champ.reload.code_departement).to eq('972')
end
end
context 'Ajaccio' do
let(:code_insee) { '2A004' }
let(:value) { 'Ajaccio (20000)' }
it 'assign code_departement and code_postal' do
expect(champ.reload.code_postal).to be_nil
expect(champ.reload.code_departement).to be_nil
subject
expect(champ.reload.code_postal).to eq('20000')
expect(champ.reload.code_departement).to eq('2A')
end
end
context 'undefined' do
let(:code_insee) { '2A004' }
let(:value) { 'Ajaccio (20000)' }
let(:code_departement) { 'undefined' }
it 'assign code_departement and code_postal' do
expect(champ.reload.code_postal).to be_nil
expect(champ.reload.code_departement).to eq('undefined')
subject
expect(champ.reload.code_postal).to eq('20000')
expect(champ.reload.code_departement).to eq('2A')
end
end
end

View file

@ -2,11 +2,10 @@ describe Champs::CommuneChamp do
let(:code_insee) { '63102' }
let(:code_postal) { '63290' }
let(:code_departement) { '63' }
let(:champ) { create(:champ_communes, code_postal: code_postal) }
let(:champ) { create(:champ_communes, code_postal:, external_id: code_insee) }
describe 'value' do
it 'with code_postal' do
champ.update(value: code_insee)
expect(champ.to_s).to eq('Châteldon (63290)')
expect(champ.name).to eq('Châteldon')
expect(champ.external_id).to eq(code_insee)

View file

@ -89,7 +89,7 @@ describe Logic::ChampValue do
end
context 'commune tdc' do
let(:champ) { create(:champ_communes, value: 'Rueil-Malmaison', value_json: { code_postal: '92500', code_departement: '92' }) }
let(:champ) { create(:champ_communes, code_postal: '92500', external_id: '92063') }
it { is_expected.to eq('92') }
end

View file

@ -123,7 +123,7 @@ describe RoutingEngine, type: :model do
context 'with a matching rule' do
before do
gi_2.update(routing_rule: ds_eq(champ_value(communes_tdc.stable_id), constant('92')))
dossier.champs.first.update(value: 'Rueil-Malmaison', value_json: { code_postal: '92500', code_departement: '92' })
dossier.champs.first.update(code_postal: '92500', external_id: '92063')
end
it { is_expected.to eq(gi_2) }

View file

@ -64,7 +64,7 @@ RSpec.describe TypesDeChamp::PrefillCommuneTypeDeChamp do
context 'when the first element is a valid postal code' do
context 'when the second element is a valid insee code' do
let(:value) { ['01540', '01457'] }
it { is_expected.to match({ id: champ.id, code_postal: '01540', value: '01457' }) }
it { is_expected.to match({ id: champ.id, code_postal: '01540', external_id: '01457' }) }
end
context 'when the second element is not a valid insee code' do
@ -83,7 +83,7 @@ RSpec.describe TypesDeChamp::PrefillCommuneTypeDeChamp do
context 'when the first element is a valid postal code' do
context 'when the second element is a valid insee code' do
let(:value) { ['01540', '01457', 'hello'] }
it { is_expected.to match({ id: champ.id, code_postal: '01540', value: '01457' }) }
it { is_expected.to match({ id: champ.id, code_postal: '01540', external_id: '01457' }) }
end
context 'when the second element is not a valid insee code' do

View file

@ -62,8 +62,7 @@ describe DossierProjectionService do
end
before do
dossier.champs_public.first.update(code_postal: '63290')
dossier.champs_public.first.update(value: '63102')
dossier.champs_public.first.update(code_postal: '63290', external_id: '63102')
end
let(:result) { subject }

View file

@ -23,10 +23,7 @@ shared_examples "the user has got a prefilled dossier, owned by themselves" do
expect(page).to have_field("Le département de lEPCI", with: epci_value.first)
expect(page).to have_selector("option[value='#{epci_value.last}'][selected]")
expect(page).to have_field(type_de_champ_dossier_link.libelle, with: dossier_link_value)
label_commune = page.find(:label, text: commune_libelle)
radio_commune = page.find("##{label_commune['for']}")
expect(radio_commune).to be_checked
expect(page).to have_field(commune_libelle, with: '01457')
expect(page).to have_field(type_de_champ_commune.libelle, with: commune_libelle)
expect(page).to have_content(annuaire_education_value.last)
expect(page).to have_content(address_value.last)
end

View file

@ -6,7 +6,7 @@ describe 'The user' do
let(:user_dossier) { user.dossiers.first }
let!(:dossier_to_link) { create(:dossier) }
scenario 'fill a dossier', js: true do
scenario 'fill a dossier', js: true, vcr: { cassette_name: 'communes' } do
log_in(user, procedure)
fill_individual
@ -36,9 +36,8 @@ describe 'The user' do
select('Australie', from: form_id_for('pays'))
select('Martinique', from: form_id_for('regions'))
select('02 Aisne', from: form_id_for('departements'))
fill_in('Renseignez le code postal', with: '60400')
# wait_until { all('label', text: 'Sélectionnez la commune dans la liste').size == 1 }
select('Brétigny (60400)', from: form_id_for('commune'))
fill_in('communes', with: '60400')
find('li', text: 'Brétigny (60400)').click
# communes needs more time to be updated
wait_until { champ_value_for('communes') == "Brétigny" }
@ -97,7 +96,7 @@ describe 'The user' do
expect(page).to have_button('alpha')
expect(page).to have_button('charly')
end
expect(page).to have_selected_value('commune', selected: 'Brétigny (60400)')
expect(page).to have_field('communes', with: 'Brétigny (60400)')
expect(page).to have_selected_value('pays', selected: 'Australie')
expect(page).to have_field('dossier_link', with: '123')
expect(page).to have_text('file.pdf')

View file

@ -30,7 +30,7 @@ describe 'Prefilling a dossier (with a GET request):', js: true do
}
let(:epci_value) { ['01', '200029999'] }
let(:dossier_link_value) { '42' }
let(:commune_value) { ['01540', '01457'] } # Vonnas (01540)
let(:commune_value) { ['01540', '01457'] }
let(:commune_libelle) { 'Vonnas (01540)' }
let(:address_value) { "20 Avenue de Ségur 75007 Paris" }
let(:sub_type_de_champs_repetition) { procedure.active_revision.children_of(type_de_champ_repetition) }

View file

@ -29,7 +29,7 @@ describe 'Prefilling a dossier (with a POST request):', js: true do
]
}
let(:epci_value) { ['01', '200029999'] }
let(:commune_value) { ['01540', '01457'] } # Vonnas (01540)
let(:commune_value) { ['01540', '01457'] }
let(:commune_libelle) { 'Vonnas (01540)' }
let(:address_value) { "20 Avenue de Ségur 75007 Paris" }
let(:sub_type_de_champs_repetition) { procedure.active_revision.children_of(type_de_champ_repetition) }