Skip to content

Commit

Permalink
Active l'abonnement HubEE et ajoute la collectivité sur FQF
Browse files Browse the repository at this point in the history
Les abonnements HubEE doivent être créées avant d'être activés, ce
commit met en place cette séparation.
Pour associer un éditeur le webhook envoie maintenant le
service_provider associé à la demande (stocké dans extra_infos).

Une méthode pour récupérer un abonnement existant a aussi été ajoutée
pour rendre le webhook plus robuste.

La collectivité est aussi créée du côté du FormulaireQF.
  • Loading branch information
jbfeldis committed Oct 18, 2024
1 parent a081984 commit 4f1339e
Show file tree
Hide file tree
Showing 17 changed files with 195 additions and 20 deletions.
6 changes: 4 additions & 2 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,10 @@ gem 'wicked'

gem 'rest-client'
gem 'faraday'
gem 'faraday-gzip'
gem 'faraday-net_http'
gem 'faraday-retry'
gem 'faraday-encoding'

group :development, :test do
gem 'awesome_print'
Expand All @@ -104,10 +106,10 @@ group :development do
# Can be configured to work on production as well see: https://github.com/MiniProfiler/rack-mini-profiler/blob/master/README.md
gem 'rack-mini-profiler', '~> 3.3'
gem 'rubocop', require: false
gem 'rubocop-rails'
gem 'rubocop-rspec'
gem 'rubocop-capybara'
gem 'rubocop-factory_bot'
gem 'rubocop-rails'
gem 'rubocop-rspec'
gem 'rubocop-rspec_rails'

gem 'better_errors'
Expand Down
8 changes: 8 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,11 @@ GEM
railties (>= 5.0.0)
faraday (2.9.0)
faraday-net_http (>= 2.0, < 3.2)
faraday-encoding (0.0.6)
faraday
faraday-gzip (2.0.1)
faraday (>= 1.0)
zlib (~> 3.0)
faraday-net_http (3.1.0)
net-http
faraday-net_http_persistent (2.1.0)
Expand Down Expand Up @@ -562,6 +567,7 @@ GEM
nokogiri (~> 1.8)
yajl-ruby (1.4.3)
zeitwerk (2.7.0)
zlib (3.1.1)

PLATFORMS
aarch64-linux
Expand All @@ -586,6 +592,8 @@ DEPENDENCIES
draper
factory_bot_rails
faraday
faraday-encoding
faraday-gzip
faraday-net_http
faraday-retry
gaffe
Expand Down
2 changes: 1 addition & 1 deletion app/clients/abstract_hubee_api_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ class AbstractHubEEAPIClient
protected

def http_connection(&block)
@http_connection ||= Faraday.new do |conn|
Faraday.new do |conn|
conn.request :retry, max: 5
conn.response :raise_error
conn.response :json
Expand Down
35 changes: 35 additions & 0 deletions app/clients/formulaire_qf_api_client.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class FormulaireQFAPIClient
def create_collectivity(authorization_request)
organization = authorization_request.organization
editor_name = authorization_request.extra_infos.dig('service_provider', 'id')

params = {
siret: organization.siret,
code_cog: organization.code_commune_etablissement,
departement: organization.code_postal_etablissement[0..1],
name: organization.denomination,
status: 'active',
editor: editor_name
}

http_connection.post("#{host}/api/collectivites", params.to_json)
end

private

def host
Rails.application.credentials.formulaire_qf.host
end

def http_connection(&block)
Faraday.new do |conn|
conn.headers['Content-Type'] = 'application/json'
conn.request :authorization, 'Bearer', -> { secret }
yield(conn) if block
end
end

def secret
Rails.application.credentials.formulaire_qf.secret
end
end
7 changes: 7 additions & 0 deletions app/clients/hubee_api_authentication.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,11 @@ def auth_url
def encoded_client_id_and_secret
Base64.strict_encode64("#{consumer_key}:#{consumer_secret}")
end

def http_connection(&block)
@http_connection ||= super do |conn|
conn.response :json
yield(conn) if block
end
end
end
46 changes: 38 additions & 8 deletions app/clients/hubee_api_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ def create_organization(organization, email)
branchCode: organization.code_commune_etablissement,
email:,
name: organization.denomination,
country: 'France',
postalCode: organization.code_postal_etablissement,
territory: organization.code_commune_etablissement,
status: 'Actif'
Expand All @@ -34,23 +35,20 @@ def create_subscription(authorization_request, organization_payload, process_cod
"#{host}/referential/v1/subscriptions",
{
datapassId: authorization_request.external_id.to_i,
notificationFrequency: 'unitaire',
notificationFrequency: 'Aucune',
processCode: process_code,
subscriber: {
type: 'SI',
companyRegister: organization_payload['companyRegister'],
branchCode: organization_payload['branchCode']
},
email: authorization_request.demandeur.email,
status: 'Actif',
status: 'Inactif',
localAdministrator: {
email: authorization_request.demandeur.email
},
delegationActor: {
branchCode: organization_payload['branchCode'],
companyRegister: organization_payload['companyRegister'],
type: 'EDT'
},
validateDateTime: DateTime.now.iso8601,
updateDateTime: DateTime.now.iso8601
}.to_json,
'Content-Type' => 'application/json'
)
Expand All @@ -60,6 +58,37 @@ def create_subscription(authorization_request, organization_payload, process_cod
raise
end

def find_subscription(_authorization_request, organization_payload, process_code)
request = http_connection { |conn| conn.request :gzip }.get(
"#{host}/referential/v1/subscriptions",
companyRegister: organization_payload['companyRegister'],
processCode: process_code
)
request.body.first
end

def update_subscription(authorization_request, subscription_payload, editor_payload = {})
subscription_id = authorization_request.extra_infos['hubee_subscription_id']
return if subscription_id.blank?

payload = subscription_payload.with_indifferent_access.merge({
status: 'Actif',
activateDateTime: DateTime.now.iso8601,
accessMode: 'API',
notificationFrequency: 'Aucune'
}.with_indifferent_access)

payload.delete('id')
payload.delete('creationDateTime')
payload.merge!(editor_payload.with_indifferent_access) if editor_payload.present?

http_connection.put(
"#{host}/referential/v1/subscriptions/#{subscription_id}",
payload.to_json,
'Content-Type' => 'application/json'
)
end

protected

def host
Expand All @@ -72,9 +101,10 @@ def already_exists_error?(faraday_error)
end
end

def http_connection
def http_connection(&block)
super do |conn|
conn.request :authorization, 'Bearer', -> { HubEEAPIAuthentication.new.access_token }
yield(conn) if block
end
end
end
3 changes: 2 additions & 1 deletion app/interactors/datapass_webhook/adapt_v2_to_v1.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ def build_data
'previous_enrollment_id' => nil,
'scopes' => generic_data['scopes'].index_with { |_scope| true },
'team_members' => build_team_members,
'events' => []
'events' => [],
'service_provider' => context.data['service_provider'],
}
}
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,17 @@ def authorization_request_attributes
).merge(authorization_request_attributes_for_current_event).merge(
'last_update' => fired_at_as_datetime,
'previous_external_id' => context.data['pass']['copied_from_enrollment_id'],
'api' => context.api
'api' => context.api,
'extra_infos' => extra_infos_with_service_provider
)
end

def extra_infos_with_service_provider
context.authorization_request.extra_infos.merge({
'service_provider' => Hash(context.data.dig('pass', 'service_provider'))
})
end

def authorization_request_attributes_for_current_event
authorization_request_attributes_for_current_event = {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ def call
return unless context.modalities.include?('formulaire_qf')

CreateFormulaireQFHubEESubscriptionJob.perform_later(context.authorization_request.id)
CreateFormulaireQFCollectivityJob.perform_later(context.authorization_request.id)
end
end
6 changes: 6 additions & 0 deletions app/jobs/create_formulaire_qf_collectivity_job.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class CreateFormulaireQFCollectivityJob < ApplicationJob
def perform(authorization_request_id)
authorization_request = AuthorizationRequest.find(authorization_request_id)
FormulaireQFAPIClient.new.create_collectivity(authorization_request)
end
end
33 changes: 27 additions & 6 deletions app/jobs/create_formulaire_qf_hubee_subscription_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,23 @@ def perform(authorization_request_id)
authorization_request.extra_infos['hubee_organization_id'] = build_hubee_organization_id(hubee_organization_payload)
authorization_request.save!

create_subscription_on_hubee(authorization_request, hubee_organization_payload)
subscription_payload = find_or_create_subscription_on_hubee(authorization_request, hubee_organization_payload)

service_provider = authorization_request.extra_infos['service_provider']
subscription_update_payload = {}

if service_provider.present? && service_provider['type'] == 'editor'
subscription_update_payload.merge!({
delegationActor: {
branchCode: service_provider['code_cog'],
companyRegister: service_provider['siret'],
type: 'EDT'
},
accessMode: 'API'
})
end

update_subscription_on_hubee(authorization_request, subscription_payload, subscription_update_payload)
rescue ActiveRecord::RecordNotFound
# do nothing
end
Expand All @@ -20,13 +36,18 @@ def find_or_create_organization_on_hubee(authorization_request)
hubee_api_client.create_organization(authorization_request.organization, authorization_request.demandeur.email)
end

def create_subscription_on_hubee(authorization_request, hubee_organization)
hubee_subscription_payload = hubee_api_client.create_subscription(authorization_request, hubee_organization, process_code)

authorization_request.extra_infos['hubee_subscription_id'] = hubee_subscription_payload['id']
def find_or_create_subscription_on_hubee(authorization_request, hubee_organization)
payload = hubee_api_client.create_subscription(authorization_request, hubee_organization, process_code)
authorization_request.extra_infos['hubee_subscription_id'] = payload['id']
authorization_request.save!
rescue HubEEAPIClient::AlreadyExists
# do nothing
payload = hubee_api_client.find_subscription(authorization_request, hubee_organization, process_code)
authorization_request.extra_infos['hubee_subscription_id'] = payload['id']
authorization_request.save!
end

def update_subscription_on_hubee(authorization_request, subscription_payload, editor_payload)
hubee_api_client.update_subscription(authorization_request, subscription_payload, editor_payload)
end

def build_hubee_organization_id(hubee_organization_payload)
Expand Down
2 changes: 1 addition & 1 deletion config/credentials/test.yml.enc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
zCEivVYu4bj2l1LSnXFlbXhTNV5NFRoA09/3q+9PwPcEtrLMZBIlr31hs0yWzXvWluCqNoH9N5ybeYGX28UgZhJypoURARvO9LK27B59a+e/uv5KMAAPmVkVlCe/TBHnFbBGnFzJWs/T4JziOAkJc1pTLRFMDv5RbFCC3rz9NPo469N2zl9U+44waK6UBdONwJn6Af/SEa0Ay7HAwnWor0pBV2yWuz02WYPTQyNrfNKt2fBt8iFoM2iTyTYxaUcovb+tVNNN/l6QqwflqmIMVMiMB1AYuyxlcS8BP1A+pBpoAWCVQVV+aKk/PFDRCqpiQetZGmD33iVmTZAoT6S3Hy+VTbKThTe8sYDbBt0O90zg5ZyzfMiHGnmYgeezVr9OvfxdVDZN+dHFZggfITugT1n1kpuHxh7WHxw9mTX+xx5IDqR6q7XvdzNzQoj3K+ao9tHYKUZ99UX9Jypn8t+IXtyQi7CcDELkm4T8oxKKZheBc5LkLZW72AM/wIUe7xumd77zphnDb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o1f1CXuoglE4b4yG1UbSQEmFEzzyfHsuK6ULS2i7ZIrpqTx1+uWXKhY6XfvIxY+aHzr27FXxVLrbhLj6y2EgeLao2THw+PRqGdWMizdjY0NGP37V96dd33QjL98UJaQbb9J0bAxzhvOThd4VeTxtFl/dCa0wLHApYHfGYdrVgIjpEC0xMd/mennJz8chTm90xPciKS772UqewGZiUCFvFQ37d/bIOr+fyikFbYfM3+yMbpy183iBg1xuWklocFpZvRe4UMo1M8xCSHvr1T5gtOxC3pu4mb5NuzmH9KT1Z2Y41TRjy9jcS4JaOG4mDvZP75q5EmTkVXDopbdIbyCf77gCCmiVmRjCOI1igzwQyh96iDDDbw4RluUCZPjgEXEVj87d5VtXhjdDkqWLekEh3oCchboNShsKAUdkk0OvkAzXq6LDjj3VljNemVAb9krhIawXm6oJiBM9rQSnN22JQjfvzAIhQYOhp7/8jJKRbnZd5M9rcJNf1MxGxnHvxUHslWRN0SzzCMuihrAc3ZmcfzHBPPwGIgCJ7s8bgF2zBD8rRQvbNBxP35rF/zKvTR4npt7FwX37DjCjXTTtmYSQvdcRzUUBFpsA2WLBCQM/FsdTx2l8K8uRCxgYdaZbCQZhPMH8FIYW3aNdqxUdWETdMagBA2exnNJO2IvTg2fe6Nrur/bzorjhgoi7KqR13RypvOQYSJn+JIHrf3EIRy1pH3l4e888/928Cv9SvF5PsfIzCxW5VW3lISQW/LDp+W4ietq2RWE8EU43byA/vtHiVRjZ1bF23Hiiyq9XWchS--1iVrN2uZYhSZST7Q--wTX5GsuCHbFXF8Ki2bYStA==
9 changes: 9 additions & 0 deletions spec/factories/datapass_webhooks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@
'entreprises' => true
}
end

service_provider do
{
'id' => '3d_ouest',
'type' => 'editor',
'siret' => '44973625500018',
'code' => '22113',
}
end
end

factory :datapass_webhook_team_member_model, class: Hash do
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@
expect(subject.reopening).to be_falsey
end

it 'stores the service provider in extra_infos' do
expect { subject }.to change { authorization_request.reload.extra_infos['service_provider'] }
end

context 'when it is the same demandeur' do
let(:demandeur) { build(:datapass_webhook_team_member_model, type: 'demandeur', email: authorization_request.demandeur.email) }

Expand Down
20 changes: 20 additions & 0 deletions spec/jobs/create_formulaire_qf_collectivity_job_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
require 'rails_helper'

RSpec.describe CreateFormulaireQFCollectivityJob, type: :job do
describe '#perform' do
subject(:job) { described_class.perform_now(authorization_request.id) }

let(:api_client) { instance_double(FormulaireQFAPIClient) }
let(:authorization_request) { create(:authorization_request, :with_demandeur, api: 'particulier') }

before do
allow(FormulaireQFAPIClient).to receive(:new).and_return(api_client)
end

it 'creates collectivity on Formulaire QF' do
expect(api_client).to receive(:create_collectivity).with(authorization_request)

job
end
end
end
6 changes: 6 additions & 0 deletions spec/jobs/create_formulaire_qf_hubee_subscription_job_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
before do
allow(hubee_api_client).to receive(:find_organization).and_raise(HubEEAPIClient::NotFound)
allow(hubee_api_client).to receive_messages(create_organization: organization_payload, create_subscription: subscription_payload)
allow(hubee_api_client).to receive(:update_subscription)
end

it 'creates an organization on HubEE' do
Expand Down Expand Up @@ -50,6 +51,7 @@
context 'when organization exists on HubEE' do
before do
allow(hubee_api_client).to receive_messages(find_organization: hubee_organization_payload, create_subscription: subscription_payload)
allow(hubee_api_client).to receive(:update_subscription)
end

it 'does not create an organization on HubEE' do
Expand Down Expand Up @@ -77,8 +79,12 @@
end

context 'when subscription already exists' do
let(:hubee_subscription_payload) { { 'id' => 123 } }

before do
allow(hubee_api_client).to receive(:create_subscription).and_raise(HubEEAPIClient::AlreadyExists)
allow(hubee_api_client).to receive(:find_subscription).and_return(hubee_subscription_payload)
allow(hubee_api_client).to receive(:update_subscription)
end

it 'does not raise an error' do
Expand Down
Loading

0 comments on commit 4f1339e

Please sign in to comment.