diff --git a/app/models/procedure.rb b/app/models/procedure.rb index 66363c943..e1a67e0fb 100644 --- a/app/models/procedure.rb +++ b/app/models/procedure.rb @@ -47,6 +47,20 @@ class Procedure < ApplicationRecord validates :description, presence: true, allow_blank: false, allow_nil: false validates :organisation, presence: true, allow_blank: false, allow_nil: false + # Warning: dossier after_save build_default_champs must be removed + # to save a dossier created from this method + def new_dossier + champs = types_de_champ + .ordered + .map { |tdc| tdc.champ.build } + + champs_private = types_de_champ_private + .ordered + .map { |tdc| tdc.champ.build } + + Dossier.new(procedure: self, champs: champs, champs_private: champs_private) + end + def hide! now = DateTime.now self.update(hidden_at: now) diff --git a/app/models/type_de_champ.rb b/app/models/type_de_champ.rb index 9fe76cfe6..55358132e 100644 --- a/app/models/type_de_champ.rb +++ b/app/models/type_de_champ.rb @@ -28,6 +28,7 @@ class TypeDeChamp < ApplicationRecord scope :public_only, -> { where(private: false) } scope :private_only, -> { where(private: true) } + scope :ordered, -> { order(order_place: :asc) } has_many :champ, inverse_of: :type_de_champ, dependent: :destroy do def build(params = {}) diff --git a/spec/models/procedure_spec.rb b/spec/models/procedure_spec.rb index 9a939c3fe..444759a5f 100644 --- a/spec/models/procedure_spec.rb +++ b/spec/models/procedure_spec.rb @@ -636,4 +636,28 @@ describe Procedure do it { is_expected.to eq("dossiers_procedure-#{procedure.id}_2018-01-02_23-11") } end end + + describe '#new_dossier' do + let(:procedure) do + procedure = create(:procedure) + + create(:type_de_champ_text, procedure: procedure, order_place: 1) + create(:type_de_champ_number, procedure: procedure, order_place: 2) + create(:type_de_champ_textarea, :private, procedure: procedure) + + procedure + end + + let(:dossier) { procedure.new_dossier } + + it { expect(dossier.procedure).to eq(procedure) } + + it { expect(dossier.champs.size).to eq(2) } + it { expect(dossier.champs[0].type).to eq("Champs::TextChamp") } + + it { expect(dossier.champs_private.size).to eq(1) } + it { expect(dossier.champs_private[0].type).to eq("Champs::TextareaChamp") } + + it { expect(Champ.count).to eq(0) } + end end