diff --git a/app/models/champs/commune_champ.rb b/app/models/champs/commune_champ.rb index 67f448e4b..a1e69ba48 100644 --- a/app/models/champs/commune_champ.rb +++ b/app/models/champs/commune_champ.rb @@ -4,6 +4,9 @@ class Champs::CommuneChamp < Champs::TextChamp store_accessor :value_json, :code_departement, :code_postal, :code_region before_save :on_codes_change, if: :should_refresh_after_code_change? + validates :external_id, presence: true, if: -> { validate_champ_value_or_prefill? && value.present? } + after_validation :instrument_external_id_error, if: -> { errors.include?(:external_id) } + def departement_name APIGeoService.departement_name(code_departement) end @@ -101,4 +104,11 @@ class Champs::CommuneChamp < Champs::TextChamp def should_refresh_after_code_change? !departement? || code_postal_changed? || external_id_changed? end + + def instrument_external_id_error + Sentry.capture_message( + "Commune with value and no external id Edge case reached", + extra: { request_id: Current.request_id } + ) + end end diff --git a/spec/models/champs/commune_champ_spec.rb b/spec/models/champs/commune_champ_spec.rb index 5448aa048..97e5e8569 100644 --- a/spec/models/champs/commune_champ_spec.rb +++ b/spec/models/champs/commune_champ_spec.rb @@ -28,6 +28,22 @@ describe Champs::CommuneChamp do expect(champ.for_export(:departement)).to eq '63 – Puy-de-Dôme' end + context 'with tricky bug (should not happen, but it happens)' do + let(:champ) do + described_class.new(stable_id: 99, dossier:).tap do |champ| + champ.external_id = '' + champ.value = 'Gagny' + champ.run_callbacks(:save) + end + end + + it 'fails' do + expect(champ).to receive(:instrument_external_id_error) + expect(champ.validate(:champs_public_value)).to be_falsey + expect(champ.errors).to include('external_id') + end + end + context 'with code' do let(:champ) do described_class.new(stable_id: 99, dossier:).tap do |champ|