FIX: user vote count is updated when topics are trashed/restored (#46)

FIX: user vote count is updated when topics are trashed/restored (#46)

  • FIX: user vote count updates properly for trashed/recovered topics

  • fixed weird tab sizing

  • removed unused spec variable

  • VoteRelease job queries deleted topics as well

  • use Jobs.run_immediately!

diff --git a/plugin.rb b/plugin.rb
index 29fe24d..c2730a7 100755
--- a/plugin.rb
+++ b/plugin.rb
@@ -292,7 +292,7 @@ after_initialize do
 
     class VoteRelease < ::Jobs::Base
       def execute(args)
-        if topic = Topic.find_by(id: args[:topic_id])
+        if topic = Topic.with_deleted.find_by(id: args[:topic_id])
           UserCustomField.where(name: DiscourseVoting::VOTES, value: args[:topic_id]).find_each do |user_field|
             user = User.find(user_field.user_id)
             user.custom_fields[DiscourseVoting::VOTES] = user.votes.dup - [args[:topic_id]]
@@ -306,7 +306,7 @@ after_initialize do
 
     class VoteReclaim < ::Jobs::Base
       def execute(args)
-        if topic = Topic.find_by(id: args[:topic_id])
+        if topic = Topic.with_deleted.find_by(id: args[:topic_id])
           UserCustomField.where(name: DiscourseVoting::VOTES_ARCHIVE, value: topic.id).find_each do |user_field|
             user = User.find(user_field.user_id)
             user.custom_fields[DiscourseVoting::VOTES] = user.votes.dup.push(topic.id).uniq
@@ -330,6 +330,14 @@ after_initialize do
     end
   end
 
+  DiscourseEvent.on(:topic_trashed) do |topic|
+    Jobs.enqueue(:vote_release, topic_id: topic.id) if !topic.closed && !topic.archived
+  end
+
+  DiscourseEvent.on(:topic_recovered) do |topic|
+    Jobs.enqueue(:vote_reclaim, topic_id: topic.id) if !topic.closed && !topic.archived
+  end
+
   DiscourseEvent.on(:post_edited) do |post, topic_changed|
     if topic_changed &&
         SiteSetting.voting_enabled &&
diff --git a/spec/voting_spec.rb b/spec/voting_spec.rb
index 325e0c7..545a12e 100644
--- a/spec/voting_spec.rb
+++ b/spec/voting_spec.rb
@@ -108,6 +108,20 @@ describe DiscourseVoting do
     end
   end
 
+  context "when a job is trashed and then recovered" do
+    it "released the vote back to the user, then reclaims it on topic recovery" do
+      Jobs.run_immediately!
+      user0.custom_fields[DiscourseVoting::VOTES] = [topic1.id]
+      user0.save
+
+      topic1.reload.trash!
+      expect(user0.reload.votes).to eq([])
+
+      topic1.recover!
+      expect(user0.reload.votes).to eq([topic1.id])
+    end
+  end
+
   context "when a topic is moved to a category" do
     let(:admin) { Fabricate(:admin) }
     let(:post0) { Fabricate(:post, topic: topic0, post_number: 1) }

GitHub sha: 429dc1e5