2024-04-29 00:17:15 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2023-01-09 15:29:18 +01:00
|
|
|
module SiretChampEtablissementFetchableConcern
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
2023-01-14 10:13:26 +01:00
|
|
|
attr_reader :etablissement_fetch_error_key
|
|
|
|
|
2023-01-09 15:29:18 +01:00
|
|
|
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')
|
2023-01-09 15:29:18 +01:00
|
|
|
|
2024-07-24 10:23:00 +02:00
|
|
|
update!(etablissement: etablissement, value_json: APIGeoService.parse_etablissement_address(etablissement))
|
2023-01-09 15:29:18 +01:00
|
|
|
rescue => error
|
2024-04-05 12:07:40 +02:00
|
|
|
if error.try(:network_error?) && !APIEntrepriseService.api_insee_up?
|
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
|
2023-01-09 15:29:18 +01:00
|
|
|
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')
|
2023-01-09 15:29:18 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2023-01-14 10:13:26 +01:00
|
|
|
def clear_etablissement!(error_key)
|
|
|
|
@etablissement_fetch_error_key = error_key
|
2023-01-09 15:29:18 +01:00
|
|
|
|
|
|
|
etablissement_to_destroy = etablissement
|
2023-01-11 15:04:45 +01:00
|
|
|
update!(etablissement: nil)
|
2023-01-09 15:29:18 +01:00
|
|
|
etablissement_to_destroy&.destroy
|
2023-01-14 10:13:26 +01:00
|
|
|
|
|
|
|
false
|
2023-01-09 15:29:18 +01:00
|
|
|
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
|
2023-01-09 15:29:18 +01:00
|
|
|
end
|