diff --git a/app/models/contact.rb b/app/models/contact.rb index 233954c67..7b83bec44 100644 --- a/app/models/contact.rb +++ b/app/models/contact.rb @@ -161,4 +161,20 @@ class Contact < ActiveRecord::Base errors.add(:ident_country_code, 'is not following ISO_3166-1 alpha 2 format') end end + + class << self + def find_orphans + Contact.where(' + NOT EXISTS( + select 1 from domains d where d.owner_contact_id = contacts.id + ) AND NOT EXISTS( + select 1 from domain_contacts dc where dc.contact_id = contacts.id + ) + ') + end + + def destroy_orphans + find_orphans.destroy_all + end + end end diff --git a/config/schedule.rb b/config/schedule.rb index 3af205c71..9d9d442b0 100644 --- a/config/schedule.rb +++ b/config/schedule.rb @@ -15,3 +15,7 @@ set :output, 'log/cron.log' every 10.minutes do runner 'ZonefileSetting.generate_zonefiles' end + +every 6.months, at: '1am' do + runner 'Contact.destroy_orphans' +end diff --git a/spec/models/contact_spec.rb b/spec/models/contact_spec.rb index fac45183e..1c8bdf8ca 100644 --- a/spec/models/contact_spec.rb +++ b/spec/models/contact_spec.rb @@ -193,7 +193,7 @@ describe Contact do invalid.each do |date| @contact.ident = date @contact.valid? - @contact.errors.full_messages.should == + @contact.errors.full_messages.should == ["Ident Ident not in valid birthady format, should be YYYY-MM-DD"] end end @@ -322,3 +322,30 @@ describe Contact, '.check_availability' do response[2][:code].should == 'asd14' end end + +describe Contact, '.destroy_orphans' do + before do + @contact_1 = Fabricate(:contact, code: 'asd12') + @contact_2 = Fabricate(:contact, code: 'asd13') + end + + it 'destroys orphans' do + Contact.find_orphans.count.should == 2 + Contact.destroy_orphans + Contact.find_orphans.count.should == 0 + end + + it 'should find one orphan' do + Fabricate(:domain, owner_contact: @contact_1) + Contact.find_orphans.count.should == 1 + Contact.find_orphans.last.should == @contact_2 + end + + it 'should find no orphans' do + Fabricate(:domain, owner_contact: @contact_1, admin_contacts: [@contact_2]) + cc = Contact.count + Contact.find_orphans.count.should == 0 + Contact.destroy_orphans + Contact.count.should == cc + end +end