FEATURE: Next topic URL prefers unread topics. (#3)

FEATURE: Next topic URL prefers unread topics. (#3)
diff --git a/app/controllers/discourse_code_review/code_review_controller.rb b/app/controllers/discourse_code_review/code_review_controller.rb
index 2db768e..0400aaa 100644
--- a/app/controllers/discourse_code_review/code_review_controller.rb
+++ b/app/controllers/discourse_code_review/code_review_controller.rb
@@ -111,10 +111,10 @@ module DiscourseCodeReview
     def render_next_topic(category_id)
       next_topic = Topic
         .joins(:tags)
+        .joins("LEFT OUTER JOIN topic_users ON (topics.id = topic_users.topic_id AND topic_users.user_id = #{current_user.id})")
         .where('tags.name = ?', SiteSetting.code_review_pending_tag)
-        .where(category_id: category_id)
-        .where('user_id <> ?', current_user.id)
-        .order('bumped_at asc')
+        .where('topics.user_id <> ?', current_user.id)
+        .order('case when last_read_post_number IS NULL then 0 else 1 end asc', "case when category_id = #{category_id.to_i} then 0 else 1 end asc", 'bumped_at asc')
         .first
 
       url = next_topic&.relative_url
diff --git a/spec/plugin_spec.rb b/spec/plugin_spec.rb
new file mode 100644
index 0000000..e69de29
diff --git a/spec/requests/discourse_code_review/code_review_controller_spec.rb b/spec/requests/discourse_code_review/code_review_controller_spec.rb
index 102ffdb..aee3368 100644
--- a/spec/requests/discourse_code_review/code_review_controller_spec.rb
+++ b/spec/requests/discourse_code_review/code_review_controller_spec.rb
@@ -61,4 +61,23 @@ describe DiscourseCodeReview::CodeReviewController do
       expect(commit.topic.tags.pluck(:name)).to eq(["hi", SiteSetting.code_review_followup_tag])
     end
   end
+
+  context '.render_next_topic' do
+
+    let(:user) { Fabricate(:admin) }
+    let(:other_user) { Fabricate(:admin) }
+
+    it 'prefers unread topics over read ones' do
+      commit = create_post(raw: "this is a fake commit", user: other_user, tags: ["hi", SiteSetting.code_review_pending_tag])
+      read_commit = create_post(raw: "this is a read commit", user: other_user, tags: ["hi", SiteSetting.code_review_pending_tag], created_at: Time.zone.now + 1.hour)
+      unread_commit = create_post(raw: "this is an unread commit", user: other_user, tags: ["hi", SiteSetting.code_review_pending_tag], created_at: Time.zone.now + 2.hours)
+      TopicUser.create!(topic: read_commit.topic, user: user, last_read_post_number: read_commit.topic.highest_post_number)
+
+      sign_in user
+
+      post '/code-review/approve.json', params: { topic_id: commit.topic_id }
+      json = JSON.parse(response.body)
+      expect(json["next_topic_url"]).to eq(unread_commit.topic.relative_url)
+    end
+  end
 end

GitHub
sha: 09c41fb4

1 Like