FIX: remove invite based associated object (#12927)

FIX: remove invite based associated object (#12927)

diff --git a/app/services/user_destroyer.rb b/app/services/user_destroyer.rb
index 13ebf83..5af6a4d 100644
--- a/app/services/user_destroyer.rb
+++ b/app/services/user_destroyer.rb
@@ -85,6 +85,13 @@ class UserDestroyer
           end
         end
 
+        Invite.where(email: user_emails).each do |invite|
+          # invited_users will be removed by dependent destroy association when user is destroyed
+          invite.invited_groups.destroy_all
+          invite.topic_invites.destroy_all
+          invite.destroy
+        end
+
         unless opts[:quiet]
           if @actor == user
             deleted_by = Discourse.system_user
diff --git a/spec/services/user_destroyer_spec.rb b/spec/services/user_destroyer_spec.rb
index 8ac418d..3bcafc5 100644
--- a/spec/services/user_destroyer_spec.rb
+++ b/spec/services/user_destroyer_spec.rb
@@ -221,6 +221,22 @@ describe UserDestroyer do
       end
     end
 
+    context 'user was invited' do
+      it "should delete the invite of user" do
+        invite = Fabricate(:invite)
+        topic_invite = invite.topic_invites.create!(topic: Fabricate(:topic))
+        invited_group = invite.invited_groups.create!(group: Fabricate(:group))
+        user = Fabricate(:user)
+        user.user_emails.create!(email: invite.email)
+
+        UserDestroyer.new(admin).destroy(user)
+
+        expect(Invite.exists?(invite.id)).to eq(false)
+        expect(InvitedGroup.exists?(invited_group.id)).to eq(false)
+        expect(TopicInvite.exists?(topic_invite.id)).to eq(false)
+      end
+    end
+
     context 'user created category' do
       let!(:topic) { Fabricate(:topic, user: user) }
       let!(:first_post) { Fabricate(:post, user: user, topic: topic) }

GitHub sha: b81c740f

This commit appears in #12927 which was approved by eviltrout. It was merged by eviltrout.