demarches-normaliennes/app/models/concerns/siret_champ_etablissement_fetchable_concern.rb

46 lines
1.7 KiB
Ruby
Raw Normal View History

module SiretChampEtablissementFetchableConcern
extend ActiveSupport::Concern
2023-01-14 10:13:26 +01:00
attr_reader :etablissement_fetch_error_key
def fetch_etablissement!(siret, user)
2023-01-14 10:13:26 +01:00
return clear_etablissement!(:empty) if siret.empty?
2023-01-16 15:14:53 +01:00
return clear_etablissement!(:invalid_length) if invalid_because?(siret, :length) # i18n-tasks-use t('errors.messages.invalid_siret_length')
return clear_etablissement!(:invalid_checksum) if invalid_because?(siret, :checksum) # i18n-tasks-use t('errors.messages.invalid_siret_checksum')
2023-01-14 10:13:26 +01:00
return clear_etablissement!(:not_found) unless (etablissement = APIEntrepriseService.create_etablissement(self, siret, user&.id)) # i18n-tasks-use t('errors.messages.siret_not_found')
update!(etablissement: etablissement)
rescue => error
2024-04-05 12:07:40 +02:00
if error.try(:network_error?) && !APIEntrepriseService.api_insee_up?
# TODO: notify ops
2023-01-14 10:13:26 +01:00
update!(
etablissement: APIEntrepriseService.create_etablissement_as_degraded_mode(self, siret, user.id)
)
@etablissement_fetch_error_key = :api_entreprise_down
false
else
Sentry.capture_exception(error, extra: { dossier_id: dossier_id, siret: siret })
2023-01-14 10:13:26 +01:00
clear_etablissement!(:network_error) # i18n-tasks-use t('errors.messages.siret_network_error')
end
end
private
2023-01-14 10:13:26 +01:00
def clear_etablissement!(error_key)
@etablissement_fetch_error_key = error_key
etablissement_to_destroy = etablissement
update!(etablissement: nil)
etablissement_to_destroy&.destroy
2023-01-14 10:13:26 +01:00
false
end
2023-01-16 15:14:53 +01:00
def invalid_because?(siret, criteria)
validatable_siret = Siret.new(siret: siret)
return false if validatable_siret.valid?
validatable_siret.errors.details[:siret].any? && validatable_siret.errors.details[:siret].first[:error] == criteria
end
end