FIX: Update draft count when sequence is increased (#13940)

FIX: Update draft count when sequence is increased (#13940)

  • FIX: Update draft count when sequence is increased

Sometimes users ended up having a draft count higher than the actual number of drafts.

  • FIX: Do not update draft count twice

The call to DraftSequence.next! above already does it.

diff --git a/app/models/draft_sequence.rb b/app/models/draft_sequence.rb
index 4afca80..cfe1a27 100644
--- a/app/models/draft_sequence.rb
+++ b/app/models/draft_sequence.rb
@@ -23,6 +23,8 @@ class DraftSequence < ActiveRecord::Base
 
     DB.exec("DELETE FROM drafts WHERE user_id = :user_id AND draft_key = :draft_key AND sequence < :sequence", draft_key: key, user_id: user_id, sequence: sequence)
 
+    UserStat.update_draft_count(user_id)
+
     sequence
   end
 
diff --git a/lib/post_creator.rb b/lib/post_creator.rb
index 922c7e3..69a94bd 100644
--- a/lib/post_creator.rb
+++ b/lib/post_creator.rb
@@ -229,7 +229,6 @@ class PostCreator
       @post.topic.reload
 
       publish
-      UserStat.update_draft_count(@user.id)
 
       track_latest_on_category
       enqueue_jobs unless @opts[:skip_jobs]
diff --git a/spec/components/post_creator_spec.rb b/spec/components/post_creator_spec.rb
index 368ba3b..f993f5a 100644
--- a/spec/components/post_creator_spec.rb
+++ b/spec/components/post_creator_spec.rb
@@ -167,6 +167,7 @@ describe PostCreator do
             "/topic/#{created_post.topic_id}",
             "/topic/#{created_post.topic_id}",
             "/user",
+            "/user",
             "/user"
           ].sort
         )
@@ -196,7 +197,10 @@ describe PostCreator do
         user_action = messages.find { |m| m.channel == "/u/#{p.user.username}" }
         expect(user_action).not_to eq(nil)
 
-        expect(messages.filter { |m| m.channel != "/distributed_hash" }.length).to eq(6)
+        draft_count = messages.find { |m| m.channel == "/user" }
+        expect(draft_count).not_to eq(nil)
+
+        expect(messages.filter { |m| m.channel != "/distributed_hash" }.length).to eq(7)
       end
 
       it 'extracts links from the post' do
diff --git a/spec/models/draft_sequence_spec.rb b/spec/models/draft_sequence_spec.rb
index 47747c1..250c52f 100644
--- a/spec/models/draft_sequence_spec.rb
+++ b/spec/models/draft_sequence_spec.rb
@@ -15,6 +15,13 @@ describe DraftSequence do
       user.id = -99999
       2.times { expect(DraftSequence.next!(user, 'test')).to eq(0) }
     end
+
+    it 'updates draft count' do
+      Draft.create!(user: user, draft_key: 'test', data: {})
+      expect(user.reload.user_stat.draft_count).to eq(1)
+      expect(DraftSequence.next!(user, 'test')).to eq 1
+      expect(user.reload.user_stat.draft_count).to eq(0)
+    end
   end
 
   describe '.current' do

GitHub sha: d9843d757a3030e276305940893f38c8e52280ae

This commit appears in #13940 which was approved by ZogStriP. It was merged by nbianca.