diff --git a/app/models/enterprise.rb b/app/models/enterprise.rb index 5340aecddd..3c080e7fca 100644 --- a/app/models/enterprise.rb +++ b/app/models/enterprise.rb @@ -48,7 +48,7 @@ class Enterprise < ApplicationRecord dependent: :destroy belongs_to :address, class_name: 'Spree::Address' belongs_to :business_address, optional: true, class_name: 'Spree::Address', dependent: :destroy - has_many :enterprise_fees + has_many :enterprise_fees, dependent: nil # paranoid association is deleted in a before_destroy has_many :enterprise_roles, dependent: :destroy has_many :users, through: :enterprise_roles belongs_to :owner, class_name: 'Spree::User', @@ -63,7 +63,7 @@ class Enterprise < ApplicationRecord has_many :inventory_items, dependent: :destroy has_many :tag_rules, dependent: :destroy has_one :stripe_account, dependent: :destroy - has_many :vouchers + has_many :vouchers, dependent: nil # paranoid association is deleted in a before_destroy has_many :connected_apps, dependent: :destroy has_one :custom_tab, dependent: :destroy @@ -130,6 +130,9 @@ class Enterprise < ApplicationRecord after_create :set_default_contact after_create :relate_to_owners_enterprises + before_destroy :delete_all_enterprise_fees + before_destroy :delete_all_vouchers + after_rollback :restore_permalink after_touch :touch_distributors after_create_commit :send_welcome_email @@ -587,4 +590,12 @@ class Enterprise < ApplicationRecord where.not(enterprises: { id: }). update_all(updated_at: Time.zone.now) end + + def delete_all_enterprise_fees + enterprise_fees.each(&:really_destroy!) + end + + def delete_all_vouchers + vouchers.each(&:really_destroy!) + end end diff --git a/spec/models/enterprise_spec.rb b/spec/models/enterprise_spec.rb index 06eb7cfbb0..d21514ff8e 100644 --- a/spec/models/enterprise_spec.rb +++ b/spec/models/enterprise_spec.rb @@ -86,6 +86,26 @@ describe Enterprise do expect(DistributorShippingMethod.where(id: shipping_method_ids)).not_to exist end + it "destroys all enterprise_fees upon destroy" do + enterprise = create(:enterprise) + fee_ids = create_list(:enterprise_fee, 2, enterprise:).map(&:id) + + expect(EnterpriseFee.where(id: fee_ids)).to exist + enterprise.destroy + expect(EnterpriseFee.where(id: fee_ids)).not_to exist + end + + it "destroys all vouchers upon destroy" do + enterprise = create(:enterprise) + voucher_ids = (1..2).map do |code| + create(:voucher, enterprise:, code: "new code #{code}") + end.map(&:id) + + expect(Voucher.where(id: voucher_ids)).to exist + enterprise.destroy + expect(Voucher.where(id: voucher_ids)).not_to exist + end + describe "relationships to other enterprises" do let(:e) { create(:distributor_enterprise) } let(:p) { create(:supplier_enterprise) }