diff --git a/app/models/mixins/archived_mixin.rb b/app/models/mixins/archived_mixin.rb index 55555896202..1f4643a271a 100644 --- a/app/models/mixins/archived_mixin.rb +++ b/app/models/mixins/archived_mixin.rb @@ -16,6 +16,14 @@ def active? deleted_on.nil? end + def archive! + update_attributes!(:deleted_on => Time.now.utc) + end + + def unarchive! + update_attributes!(:deleted_on => nil) + end + # Needed for metrics def my_zone if ext_management_system.present? diff --git a/app/models/service_template.rb b/app/models/service_template.rb index 6572aea0725..efb8b25b638 100644 --- a/app/models/service_template.rb +++ b/app/models/service_template.rb @@ -37,6 +37,7 @@ class ServiceTemplate < ApplicationRecord include OwnershipMixin include NewWithTypeStiMixin include TenancyMixin + include ArchivedMixin include_concern 'Filter' belongs_to :tenant @@ -56,6 +57,7 @@ class ServiceTemplate < ApplicationRecord has_many :dialogs, -> { distinct }, :through => :resource_actions has_many :miq_requests, :as => :source, :dependent => :nullify + has_many :active_requests, -> { where(:request_state => MiqRequest::ACTIVE_STATES) }, :as => :source, :class_name => "MiqRequest" virtual_column :type_display, :type => :string virtual_column :template_valid, :type => :boolean @@ -151,6 +153,11 @@ def destroy super end + def archive + raise _("Cannot archive while in use") unless active_requests.empty? + archive! + end + def request_class ServiceTemplateProvisionRequest end diff --git a/spec/models/service_template_spec.rb b/spec/models/service_template_spec.rb index 701772cd161..eab9edb719a 100644 --- a/spec/models/service_template_spec.rb +++ b/spec/models/service_template_spec.rb @@ -862,6 +862,40 @@ ) end end + + context "#archive" do + let(:service_template) { FactoryGirl.create(:service_template, :miq_requests => miq_requests) } + context "with no MiqRequests" do + let(:miq_requests) { [] } + + it "archives the service_template" do + service_template.archive + expect(service_template.reload.archived?).to be_truthy + end + end + + context "with no active MiqRequests" do + let(:miq_requests) { [FactoryGirl.create(:service_template_provision_request, :request_state => "finished")] } + it "archives the service_template" do + service_template.archive + expect(service_template.reload.archived?).to be_truthy + end + end + + context "with an active MiqRequest" do + let(:miq_requests) do + [ + FactoryGirl.create(:service_template_provision_request, :request_state => "finished"), + FactoryGirl.create(:service_template_provision_request, :request_state => "queued"), + ] + end + + it "archives the service_template" do + expect { service_template.archive }.to raise_error("Cannot archive while in use") + expect(service_template.reload.archived?).to be_falsy + end + end + end end def add_and_save_service(p, c)