FIX: Don't log a second pending action

FIX: Don’t log a second pending action

If two people flagged the same post you’d get a “Pending” history event logged which looked bad.

diff --git a/app/models/reviewable.rb b/app/models/reviewable.rb
index bb18a42..57d9271 100644
--- a/app/models/reviewable.rb
+++ b/app/models/reviewable.rb
@@ -93,12 +93,20 @@ class Reviewable < ActiveRecord::Base
       potential_spam: potential_spam
     )
   rescue ActiveRecord::RecordNotUnique
-    updates = {
-      status: statuses[:pending]
-    }
-    updates[:potential_spam] = true if potential_spam
-    where(target: target).update_all(updates)
-    find_by(target: target).tap { |r| r.log_history(:transitioned, created_by) }
+
+    row_count = DB.exec(<<~SQL, status: statuses[:pending], id: target.id, type: target.class.name)
+      UPDATE reviewables
+      SET status = :status
+      WHERE status <> :status
+        AND target_id = :id
+        AND target_type = :type
+    SQL
+
+    where(target: target).update_all(potential_spam: true) if potential_spam
+
+    reviewable = find_by(target: target)
+    reviewable.log_history(:transitioned, created_by) if row_count > 0
+    reviewable
   end
 
   def add_score(
@@ -219,6 +227,7 @@ class Reviewable < ActiveRecord::Base
 
     self.status = Reviewable.statuses[status_symbol]
     save!
+
     log_history(:transitioned, performed_by)
     DiscourseEvent.trigger(:reviewable_transitioned_to, status_symbol, self)
 
diff --git a/spec/models/reviewable_history_spec.rb b/spec/models/reviewable_history_spec.rb
index 743d2f8..735695d 100644
--- a/spec/models/reviewable_history_spec.rb
+++ b/spec/models/reviewable_history_spec.rb
@@ -35,6 +35,14 @@ RSpec.describe ReviewableHistory, type: :model do
     expect(history[2].created_by).to eq(admin)
   end
 
+  it "won't log a transition to the same state" do
+    p0 = Fabricate(:post)
+    reviewable = PostActionCreator.spam(Fabricate(:user), p0).reviewable
+    expect(reviewable.reviewable_histories.size).to eq(1)
+    PostActionCreator.inappropriate(Fabricate(:user), p0)
+    expect(reviewable.reload.reviewable_histories.size).to eq(1)
+  end
+
   it "adds an `edited` event when edited" do
     reviewable = Fabricate(:reviewable)
     old_category = reviewable.category

GitHub sha: d5a61ab1