Merge branch 'dev'

This commit is contained in:
gregoirenovel 2018-04-09 11:14:43 +02:00
commit f0c0d654ca
25 changed files with 339 additions and 133 deletions

View file

@ -250,7 +250,7 @@ class Admin::ProceduresController < AdminController
private private
def procedure_params def procedure_params
editable_params = [:libelle, :description, :organisation, :direction, :lien_site_web, :lien_notice, :euro_flag, :logo, :auto_archive_on] editable_params = [:libelle, :description, :organisation, :direction, :lien_site_web, :lien_notice, :web_hook_url, :euro_flag, :logo, :auto_archive_on]
if @procedure.try(:locked?) if @procedure.try(:locked?)
params.require(:procedure).permit(*editable_params) params.require(:procedure).permit(*editable_params)
else else

View file

@ -10,7 +10,7 @@ module Manager
if administrateur.errors.empty? if administrateur.errors.empty?
PipedriveAcceptsDealsJob.perform_later( PipedriveAcceptsDealsJob.perform_later(
create_administrateur_params[:person_id], create_administrateur_params[:person_id],
PipedriveService::PIPEDRIVE_CAMILLE_ID, Pipedrive::DealAdapter::PIPEDRIVE_CAMILLE_ID,
create_administrateur_params[:stage_id] create_administrateur_params[:stage_id]
) )
@ -26,7 +26,7 @@ module Manager
def refuse_administrateur def refuse_administrateur
PipedriveRefusesDealsJob.perform_later( PipedriveRefusesDealsJob.perform_later(
refuse_administrateur_params[:person_id], refuse_administrateur_params[:person_id],
PipedriveService::PIPEDRIVE_CAMILLE_ID Pipedrive::DealAdapter::PIPEDRIVE_CAMILLE_ID
) )
AdministrationMailer AdministrationMailer
@ -56,7 +56,7 @@ module Manager
end end
def demandes def demandes
@demandes ||= PipedriveService.fetch_people_demandes @demandes ||= PipedriveService.get_demandes
end end
end end
end end

View file

@ -0,0 +1,9 @@
class Administrateurs::ActivateBeforeExpirationJob < ApplicationJob
queue_as :cron
def perform(*args)
Administrateur.inactive.where(created_at: 2.days.ago.all_day).each do |a|
AdministrateurMailer.activate_before_expiration(a).deliver_later
end
end
end

View file

@ -1,5 +1,5 @@
class PipedriveAcceptsDealsJob < ApplicationJob class PipedriveAcceptsDealsJob < ApplicationJob
def perform(person_id, owner_id, stage_id) def perform(person_id, owner_id, stage_id)
PipedriveService.accept_deals_from_person(person_id, owner_id, stage_id) PipedriveService.accept_demande_from_person(person_id, owner_id, stage_id)
end end
end end

View file

@ -1,5 +1,5 @@
class PipedriveRefusesDealsJob < ApplicationJob class PipedriveRefusesDealsJob < ApplicationJob
def perform(person_id, owner_id) def perform(person_id, owner_id)
PipedriveService.refuse_deals_from_person(person_id, owner_id) PipedriveService.refuse_demande_from_person(person_id, owner_id)
end end
end end

16
app/jobs/web_hook_job.rb Normal file
View file

@ -0,0 +1,16 @@
class WebHookJob < ApplicationJob
queue_as :default
TIMEOUT = 10
def perform(procedure, dossier)
body = {
procedure_id: procedure.id,
dossier_id: dossier.id,
state: dossier.state,
updated_at: dossier.updated_at
}
Typhoeus.post(procedure.web_hook_url, body: body, timeout: TIMEOUT)
end
end

50
app/lib/pipedrive/api.rb Normal file
View file

@ -0,0 +1,50 @@
class Pipedrive::API
PIPEDRIVE_ALL_NOT_DELETED_DEALS = 'all_not_deleted'
PIPEDRIVE_DEALS_URL = [PIPEDRIVE_API_URL, 'deals'].join("/")
PIPEDRIVE_PEOPLE_URL = [PIPEDRIVE_API_URL, 'persons'].join("/")
def self.get_persons_owned_by_user(user_id)
url = PIPEDRIVE_PEOPLE_URL
params = { user_id: user_id }
self.get(url, params)
end
def self.get_deals_for_person(person_id)
url = [PIPEDRIVE_PEOPLE_URL, person_id, "deals"].join('/')
params = { status: PIPEDRIVE_ALL_NOT_DELETED_DEALS }
self.get(url, params)
end
def self.put_deal(deal_id, params)
url = [PIPEDRIVE_DEALS_URL, deal_id].join("/")
self.put(url, params)
end
def self.put_person(person_id, params)
url = [PIPEDRIVE_PEOPLE_URL, person_id].join("/")
self.put(url, params)
end
private
def self.get(url, params)
params.merge!({
start: 0,
limit: 500,
api_token: PIPEDRIVE_TOKEN
})
response = RestClient.get(url, params: params)
JSON.parse(response.body)['data']
end
def self.put(url, params)
url = "#{url}?api_token=#{PIPEDRIVE_TOKEN}"
RestClient.put(url, params.to_json, { content_type: :json })
end
end

View file

@ -0,0 +1,36 @@
class Pipedrive::DealAdapter
PIPEDRIVE_ADMIN_CENTRAL_STOCK_STAGE_ID = 35
PIPEDRIVE_REGIONS_STOCK_STAGE_ID = 24
PIPEDRIVE_PREFECTURES_STOCK_STAGE_ID = 20
PIPEDRIVE_DEPARTEMENTS_STOCK_STAGE_ID = 30
PIPEDRIVE_COMMUNES_STOCK_STAGE_ID = 40
PIPEDRIVE_ORGANISMES_STOCK_STAGE_ID = 1
PIPEDRIVE_ORGANISMES_REFUSES_STOCK_STAGE_ID = 45
PIPEDRIVE_LOST_STATUS = "lost"
PIPEDRIVE_LOST_REASON = "refusé depuis DS"
PIPEDRIVE_CAMILLE_ID = '3189424'
def self.refuse_deal(deal_id, owner_id)
params = {
user_id: owner_id,
stage_id: PIPEDRIVE_ORGANISMES_REFUSES_STOCK_STAGE_ID,
status: PIPEDRIVE_LOST_STATUS,
lost_reason: PIPEDRIVE_LOST_REASON
}
Pipedrive::API.put_deal(deal_id, params)
end
def self.get_deals_ids_for_person(person_id)
Pipedrive::API.get_deals_for_person(person_id)
.map { |datum| datum['id'] }
end
def self.update_deal_owner_and_stage(deal_id, owner_id, stage_id)
params = { user_id: owner_id, stage_id: stage_id }
Pipedrive::API.put_deal(deal_id, params)
end
end

View file

@ -0,0 +1,22 @@
class Pipedrive::PersonAdapter
PIPEDRIVE_POSTE_ATTRIBUTE_ID = '33a790746f1713d712fe97bcce9ac1ca6374a4d6'
PIPEDRIVE_ROBOT_ID = '2748449'
def self.get_demandes_from_persons_owned_by_robot
Pipedrive::API.get_persons_owned_by_user(PIPEDRIVE_ROBOT_ID).map do |datum|
{
person_id: datum['id'],
nom: datum['name'],
poste: datum[PIPEDRIVE_POSTE_ATTRIBUTE_ID],
email: datum.dig('email', 0, 'value'),
organisation: datum['org_name']
}
end
end
def self.update_person_owner(person_id, owner_id)
params = { owner_id: owner_id }
Pipedrive::API.put_person(person_id, params)
end
end

View file

@ -0,0 +1,11 @@
class AdministrateurMailer < ApplicationMailer
layout 'mailers/layout'
def activate_before_expiration(administrateur)
@administrateur = administrateur
@expiration_date = administrateur.reset_password_sent_at + Devise.reset_password_within
mail(to: administrateur.email,
subject: "demarches-simplifiees.fr - N'oubliez pas d'activer votre compte administrateur",
reply_to: "contact@demarches-simplifiees.fr")
end
end

View file

@ -75,6 +75,7 @@ class Dossier < ApplicationRecord
after_save :build_default_champs, if: Proc.new { saved_change_to_procedure_id? } after_save :build_default_champs, if: Proc.new { saved_change_to_procedure_id? }
after_save :build_default_individual, if: Proc.new { procedure.for_individual? } after_save :build_default_individual, if: Proc.new { procedure.for_individual? }
after_save :send_dossier_received after_save :send_dossier_received
after_save :send_web_hook
after_create :send_draft_notification_email after_create :send_draft_notification_email
validates :user, presence: true validates :user, presence: true
@ -326,4 +327,13 @@ class Dossier < ApplicationRecord
NotificationMailer.send_draft_notification(self).deliver_now! NotificationMailer.send_draft_notification(self).deliver_now!
end end
end end
def send_web_hook
if saved_change_to_state? && !brouillon? && procedure.web_hook_url
WebHookJob.perform_later(
procedure,
self
)
end
end
end end

View file

@ -1,102 +1,17 @@
class PipedriveService class PipedriveService
PIPEDRIVE_POSTE_ATTRIBUTE_ID = '33a790746f1713d712fe97bcce9ac1ca6374a4d6' def self.accept_demande_from_person(person_id, owner_id, stage_id)
person_deals_ids = Pipedrive::DealAdapter.get_deals_ids_for_person(person_id)
PIPEDRIVE_ROBOT_ID = '2748449' person_deals_ids.each { |deal_id| Pipedrive::DealAdapter.update_deal_owner_and_stage(deal_id, owner_id, stage_id) }
PIPEDRIVE_CAMILLE_ID = '3189424' Pipedrive::PersonAdapter.update_person_owner(person_id, owner_id)
PIPEDRIVE_ALL_NOT_DELETED_DEALS = 'all_not_deleted'
PIPEDRIVE_LOST_STATUS = "lost"
PIPEDRIVE_LOST_REASON = "refusé depuis DS"
PIPEDRIVE_ADMIN_CENTRAL_STOCK_STAGE_ID = 35
PIPEDRIVE_REGIONS_STOCK_STAGE_ID = 24
PIPEDRIVE_PREFECTURES_STOCK_STAGE_ID = 20
PIPEDRIVE_DEPARTEMENTS_STOCK_STAGE_ID = 30
PIPEDRIVE_COMMUNES_STOCK_STAGE_ID = 40
PIPEDRIVE_ORGANISMES_STOCK_STAGE_ID = 1
PIPEDRIVE_ORGANISMES_REFUSES_STOCK_STAGE_ID = 45
class << self
def accept_deals_from_person(person_id, owner_id, stage_id)
waiting_deal_ids = fetch_waiting_deal_ids(person_id)
waiting_deal_ids.each { |deal_id| update_deal_owner_and_stage(deal_id, owner_id, stage_id) }
update_person_owner(person_id, owner_id)
end end
def refuse_deals_from_person(person_id, owner_id) def self.refuse_demande_from_person(person_id, owner_id)
waiting_deal_ids = fetch_waiting_deal_ids(person_id) person_deals_ids = Pipedrive::DealAdapter.get_deals_ids_for_person(person_id)
waiting_deal_ids.each { |deal_id| refuse_deal(deal_id, owner_id) } person_deals_ids.each { |deal_id| Pipedrive::DealAdapter.refuse_deal(deal_id, owner_id) }
update_person_owner(person_id, owner_id) Pipedrive::PersonAdapter.update_person_owner(person_id, owner_id)
end end
def fetch_people_demandes def self.get_demandes
params = { Pipedrive::PersonAdapter.get_demandes_from_persons_owned_by_robot
start: 0,
limit: 500,
user_id: PIPEDRIVE_ROBOT_ID,
api_token: PIPEDRIVE_TOKEN
}
response = RestClient.get(PIPEDRIVE_PEOPLE_URL, { params: params })
json = JSON.parse(response.body)
json['data'].map do |datum|
{
person_id: datum['id'],
nom: datum['name'],
poste: datum[PIPEDRIVE_POSTE_ATTRIBUTE_ID],
email: datum.dig('email', 0, 'value'),
organisation: datum['org_name']
}
end
end
private
def refuse_deal(deal_id, owner_id)
url = PIPEDRIVE_DEALS_URL + "/#{deal_id}?api_token=#{PIPEDRIVE_TOKEN}"
params = {
user_id: owner_id,
stage_id: PIPEDRIVE_ORGANISMES_REFUSES_STOCK_STAGE_ID,
status: PIPEDRIVE_LOST_STATUS,
lost_reason: PIPEDRIVE_LOST_REASON
}
RestClient.put(url, params.to_json, { content_type: :json })
end
def fetch_waiting_deal_ids(person_id)
url = [PIPEDRIVE_PEOPLE_URL, person_id, "deals"].join('/')
params = {
start: 0,
limit: 500,
status: PIPEDRIVE_ALL_NOT_DELETED_DEALS,
api_token: PIPEDRIVE_TOKEN
}
response = RestClient.get(url, params: params)
json = JSON.parse(response.body)
json['data'].map { |datum| datum['id'] }
end
def update_deal_owner_and_stage(deal_id, owner_id, stage_id)
url = PIPEDRIVE_DEALS_URL + "/#{deal_id}?api_token=#{PIPEDRIVE_TOKEN}"
params = { user_id: owner_id, stage_id: stage_id }
RestClient.put(url, params.to_json, { content_type: :json })
end
def update_person_owner(person_id, owner_id)
url = PIPEDRIVE_PEOPLE_URL + "/#{person_id}?api_token=#{PIPEDRIVE_TOKEN}"
params = { owner_id: owner_id }
RestClient.put(url, params.to_json, { content_type: :json })
end
end end
end end

View file

@ -2,10 +2,14 @@
.alert.alert-info .alert.alert-info
Cette procédure est publiée, certains éléments de la description ne sont plus modifiables Cette procédure est publiée, certains éléments de la description ne sont plus modifiables
- { libelle: 'Libellé*', description: 'Description*', organisation: 'Organisme*', direction: 'Direction', lien_site_web: 'Lien site internet', lien_notice: 'Lien notice' }.each do |key, value| - { libelle: 'Libellé*', description: 'Description*', organisation: 'Organisme*', direction: 'Direction', lien_site_web: 'Lien site internet', lien_notice: 'Lien notice', web_hook_url: 'Lien de rappel HTTP' }.each do |key, value|
- if key != :web_hook_url || current_administrateur&.feature_enabled?(:web_hook_allowed)
.form-group .form-group
%h4 %h4
= value = value
- if key == :web_hook_url
%p
Un lien de rappel HTTP (aussi appelé webhook) est utilisé pour notifier un service tiers du changement de l'état dun dossier sur demarches-simplifiees.fr. À chaque changement détat d'un dossier, notre site va effectuer une requête sur le lien renseigné avec en paramètres : le nouvel état du dossier, lidentifiant de la procédure, l'identifiant dossier et la date du changement. Vous pourrez alors utiliser notre API pour récupérer les nouvelles informations du dossier concerné.
- if key == :description - if key == :description
= f.text_area key, rows: '6', placeholder: 'Description du projet', class: 'form-control' = f.text_area key, rows: '6', placeholder: 'Description du projet', class: 'form-control'

View file

@ -0,0 +1,17 @@
- content_for(:title, "N'oubliez pas d'activer votre compte")
Bonjour,
%br
%br
Vous avez fait la demande dun compte administrateur sur demarches-simplifiees.fr.
Votre compte a été créé mais reste inactif, il arrivera à expiration le #{@expiration_date.strftime("%d/%m/%Y")}
%br
%br
Afin dactiver votre compte, veuillez cliquer sur le lien ci-dessous :
= link_to(admin_activate_url(token: @administrateur.reset_password_token), admin_activate_url(token: @administrateur.reset_password_token))
%br
%br
Nous restons à votre disposition si vous avez besoin daccompagnement.
%br
%br
= render partial: "layouts/mailers/bizdev_signature"

View file

@ -19,16 +19,4 @@ Je vous invite également à consulter notre site de documentation qui regroupe
= link_to('https://demarches-simplifiees.gitbook.io/demarches-simplifiees/', 'https://demarches-simplifiees.gitbook.io/demarches-simplifiees/') = link_to('https://demarches-simplifiees.gitbook.io/demarches-simplifiees/', 'https://demarches-simplifiees.gitbook.io/demarches-simplifiees/')
%br %br
%br %br
Cordialement, = render partial: "layouts/mailers/bizdev_signature"
%br
%br
Camille Garrigue
%br
%br
Équipe demarches-simplifiees.fr
%br
Téléphone (standard) : 01 76 42 02 87
%br
Incubateur de Services Numériques / beta.gouv.fr
%br
Services du Premier Ministre, 20 avenue de Ségur, 75007 Paris

View file

@ -0,0 +1,13 @@
Cordialement,
%br
%br
Camille Garrigue
%br
%br
Équipe demarches-simplifiees.fr
%br
Téléphone (standard) : 01 76 42 02 87
%br
Incubateur de Services Numériques / beta.gouv.fr
%br
Services du Premier Ministre, 20 avenue de Ségur, 75007 Paris

View file

@ -33,12 +33,12 @@
<%= form_tag(manager_demandes_create_administrateur_path) do -%> <%= form_tag(manager_demandes_create_administrateur_path) do -%>
<%= select_tag "stage_id", <%= select_tag "stage_id",
options_for_select({ options_for_select({
"administration centrale" => PipedriveService::PIPEDRIVE_ADMIN_CENTRAL_STOCK_STAGE_ID, "administration centrale" => Pipedrive::DealAdapter::PIPEDRIVE_ADMIN_CENTRAL_STOCK_STAGE_ID,
"région" => PipedriveService::PIPEDRIVE_REGIONS_STOCK_STAGE_ID, "région" => Pipedrive::DealAdapter::PIPEDRIVE_REGIONS_STOCK_STAGE_ID,
"préfecture" => PipedriveService::PIPEDRIVE_PREFECTURES_STOCK_STAGE_ID, "préfecture" => Pipedrive::DealAdapter::PIPEDRIVE_PREFECTURES_STOCK_STAGE_ID,
"département" =>PipedriveService::PIPEDRIVE_DEPARTEMENTS_STOCK_STAGE_ID, "département" =>Pipedrive::DealAdapter::PIPEDRIVE_DEPARTEMENTS_STOCK_STAGE_ID,
"commune" => PipedriveService::PIPEDRIVE_COMMUNES_STOCK_STAGE_ID, "commune" => Pipedrive::DealAdapter::PIPEDRIVE_COMMUNES_STOCK_STAGE_ID,
"organisme" => PipedriveService::PIPEDRIVE_ORGANISMES_STOCK_STAGE_ID "organisme" => Pipedrive::DealAdapter::PIPEDRIVE_ORGANISMES_STOCK_STAGE_ID
}), }),
style: 'margin-bottom: 20px; width: inherit;' %> style: 'margin-bottom: 20px; width: inherit;' %>

View file

@ -44,6 +44,8 @@ Rails.application.configure do
protocol: :http protocol: :http
} }
config.active_job.queue_adapter = :test
# Raises error for missing translations # Raises error for missing translations
# config.action_view.raise_on_missing_translations = true # config.action_view.raise_on_missing_translations = true
end end

View file

@ -4,3 +4,5 @@ champ_pj_allowed_for_admin_ids:
- 0 - 0
champ_siret_allowed_for_admin_ids: champ_siret_allowed_for_admin_ids:
- 0 - 0
web_hook_allowed_for_admin_ids:
- 0

View file

@ -4,6 +4,4 @@ else
API_ENTREPRISE_URL = 'https://staging.entreprise.api.gouv.fr/v2' API_ENTREPRISE_URL = 'https://staging.entreprise.api.gouv.fr/v2'
end end
PIPEDRIVE_API_URL = 'https://api.pipedrive.com/v1/' PIPEDRIVE_API_URL = 'https://api.pipedrive.com/v1'
PIPEDRIVE_PEOPLE_URL = URI.join(PIPEDRIVE_API_URL, 'persons').to_s
PIPEDRIVE_DEALS_URL = URI.join(PIPEDRIVE_API_URL, 'deals').to_s

View file

@ -0,0 +1,5 @@
class AddWebhookToProcedures < ActiveRecord::Migration[5.2]
def change
add_column :procedures, :web_hook_url, :string
end
end

View file

@ -453,6 +453,7 @@ ActiveRecord::Schema.define(version: 2018_04_04_113409) do
t.datetime "archived_at" t.datetime "archived_at"
t.datetime "whitelisted_at" t.datetime "whitelisted_at"
t.boolean "ask_birthday", default: false, null: false t.boolean "ask_birthday", default: false, null: false
t.string "web_hook_url"
t.index ["hidden_at"], name: "index_procedures_on_hidden_at" t.index ["hidden_at"], name: "index_procedures_on_hidden_at"
end end

View file

@ -0,0 +1,72 @@
require 'rails_helper'
RSpec.describe Administrateurs::ActivateBeforeExpirationJob, type: :job do
describe 'perform' do
let(:administrateur) { create(:administrateur, active: active) }
let(:mailer_double) { double('mailer', deliver_later: true) }
subject { Administrateurs::ActivateBeforeExpirationJob.perform_now }
before do
Timecop.freeze(DateTime.new(2018, 03, 20))
administrateur.reload
allow(AdministrateurMailer).to receive(:activate_before_expiration).and_return(mailer_double)
end
after { Timecop.return }
context "with an inactive administrateur" do
let(:active) { false }
context "created now" do
before { subject }
it { expect(AdministrateurMailer).not_to have_received(:activate_before_expiration) }
end
context "created a long time ago" do
before do
administrateur.update_columns(created_at: DateTime.new(2018, 03, 10))
subject
end
it { expect(AdministrateurMailer).not_to have_received(:activate_before_expiration) }
end
context "created 2 days ago" do
before do
administrateur.update_columns(created_at: DateTime.new(2018, 03, 18, 20, 00))
subject
end
it { expect(AdministrateurMailer).to have_received(:activate_before_expiration).with(administrateur) }
end
end
context "with an active administrateur" do
let(:active) { true }
context "created now" do
before { subject }
it { expect(AdministrateurMailer).not_to have_received(:activate_before_expiration) }
end
context "created a long time ago" do
before do
administrateur.update_columns(created_at: DateTime.new(2018, 03, 10))
subject
end
it { expect(AdministrateurMailer).not_to have_received(:activate_before_expiration) }
end
context "created 2 days ago" do
before do
administrateur.update_columns(created_at: DateTime.new(2018, 03, 18, 20, 00))
subject
end
it { expect(AdministrateurMailer).not_to have_received(:activate_before_expiration) }
end
end
end
end

View file

@ -0,0 +1,5 @@
class AdministrateurMailerPreview < ActionMailer::Preview
def activate_before_expiration
AdministrateurMailer.activate_before_expiration(Administrateur.inactive.where.not(reset_password_token: nil).last)
end
end

View file

@ -896,4 +896,34 @@ describe Dossier do
it { is_expected.to eq(expected) } it { is_expected.to eq(expected) }
end end
end end
describe 'webhook' do
let(:dossier) { create(:dossier) }
it 'should not call webhook' do
expect {
dossier.accepte!
}.to_not have_enqueued_job(WebHookJob)
end
it 'should call webhook' do
dossier.procedure.update_column(:web_hook_url, '/webhook.json')
expect {
dossier.update_column(:motivation, 'bonjour')
}.to_not have_enqueued_job(WebHookJob)
expect {
dossier.en_construction!
}.to have_enqueued_job(WebHookJob)
expect {
dossier.update_column(:motivation, 'bonjour2')
}.to_not have_enqueued_job(WebHookJob)
expect {
dossier.en_instruction!
}.to have_enqueued_job(WebHookJob)
end
end
end end