FIX: Correctly update replies when first post gets moved

FIX: Correctly update replies when first post gets moved

diff --git a/app/models/post_mover.rb b/app/models/post_mover.rb
index 12ca7e0..bf7ca56 100644
--- a/app/models/post_mover.rb
+++ b/app/models/post_mover.rb
@@ -129,6 +129,7 @@ class PostMover
     move_incoming_emails
     move_notifications
     update_reply_counts
+    move_first_post_replies
     delete_post_replies
   end
 
@@ -254,6 +255,16 @@ class PostMover
     SQL
   end
 
+  def move_first_post_replies
+    DB.exec <<~SQL
+      UPDATE post_replies pr
+      SET post_id = mp.new_post_id
+      FROM moved_posts mp, moved_posts mr
+      WHERE mp.old_post_id <> mp.new_post_id AND pr.post_id = mp.old_post_id AND
+        EXISTS (SELECT 1 FROM moved_posts mr WHERE mr.new_post_id = pr.reply_id)
+    SQL
+  end
+
   def delete_post_replies
     DB.exec <<~SQL
       DELETE
diff --git a/spec/models/post_mover_spec.rb b/spec/models/post_mover_spec.rb
index 3cebd1e..da1aedd 100644
--- a/spec/models/post_mover_spec.rb
+++ b/spec/models/post_mover_spec.rb
@@ -584,6 +584,12 @@ describe PostMover do
             topic.reload
             expect(topic.posts.by_post_number).to match_array([p1, p3, p4])
             expect(topic.highest_post_number).to eq(p4.post_number)
+
+            # updates replies for posts moved to same topic
+            expect(PostReply.where(reply_id: p2.id).pluck(:post_id)).to contain_exactly(new_first.id)
+
+            # leaves replies to the first post of the original topic unchanged
+            expect(PostReply.where(reply_id: p3.id).pluck(:post_id)).to contain_exactly(p1.id)
           end
 
           it "preserves post actions in the new post" do

GitHub sha: 50db6a1d