demarches-normaliennes/app/controllers/champs/siret_controller.rb

66 lines
1.7 KiB
Ruby
Raw Normal View History

2018-04-03 17:53:14 +02:00
class Champs::SiretController < ApplicationController
2018-09-06 19:23:27 +02:00
before_action :authenticate_logged_user!
def show
@position = params[:position]
extract_siret
find_etablisement
if @siret.empty?
return clear_siret_and_etablissement
end
if @siret.present? && @siret.length != 14
return siret_error(:invalid)
end
begin
etablissement = find_etablissement_with_siret
2020-03-05 13:50:38 +01:00
rescue ApiEntreprise::API::RequestFailed
return siret_error(:network_error)
end
if etablissement.nil?
return siret_error(:not_found)
end
@etablissement = etablissement
if !@champ.nil?
@champ.update!(value: etablissement.siret, etablissement: etablissement)
2018-09-06 19:23:27 +02:00
end
end
private
def extract_siret
if params[:dossier].key?(:champs_attributes)
@siret = params[:dossier][:champs_attributes][@position][:value]
@attribute = "dossier[champs_attributes][#{@position}][etablissement_attributes]"
else
@siret = params[:dossier][:champs_private_attributes][@position][:value]
@attribute = "dossier[champs_private_attributes][#{@position}][etablissement_attributes]"
2018-04-03 17:53:14 +02:00
end
2018-09-06 19:23:27 +02:00
end
def find_etablisement
if params[:champ_id].present?
@champ = policy_scope(Champ).find(params[:champ_id])
2019-03-12 14:57:03 +01:00
@etablissement = @champ&.etablissement
2018-09-06 19:23:27 +02:00
end
2019-03-12 14:57:03 +01:00
@procedure_id = @champ&.dossier&.procedure_id || 'aperçu'
2018-09-06 19:23:27 +02:00
end
def find_etablissement_with_siret
ApiEntrepriseService.create_etablissement(@champ, @siret, current_user.id)
2018-04-03 17:53:14 +02:00
end
def clear_siret_and_etablissement
@champ&.update!(value: '')
@etablissement&.destroy
end
def siret_error(error)
clear_siret_and_etablissement
@siret = error
end
2018-04-03 17:53:14 +02:00
end