From 75441e063a3a4c3e40b52f2936e5dbe113e5fee0 Mon Sep 17 00:00:00 2001 From: David Battersby Date: Fri, 20 Oct 2023 17:56:50 +0800 Subject: [PATCH] DEV: create new_post_moved event trigger when moving posts (#24005) This change adds a new event trigger (new_post_moved) when the first post in a topic is moved to a new topic. Plugins that listen for the new_post_moved event now have an easy way to update old data based on the post id. --- app/models/post_mover.rb | 1 + spec/models/post_mover_spec.rb | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/app/models/post_mover.rb b/app/models/post_mover.rb index cfa1720318c..45e78acf350 100644 --- a/app/models/post_mover.rb +++ b/app/models/post_mover.rb @@ -277,6 +277,7 @@ class PostMover new_post.custom_fields = post.custom_fields new_post.save_custom_fields + DiscourseEvent.trigger(:first_post_moved, new_post, post) DiscourseEvent.trigger(:post_moved, new_post, original_topic.id) # we don't want to keep the old topic's OP bookmarked when we are diff --git a/spec/models/post_mover_spec.rb b/spec/models/post_mover_spec.rb index 28186efd54d..1656d2db870 100644 --- a/spec/models/post_mover_spec.rb +++ b/spec/models/post_mover_spec.rb @@ -2463,5 +2463,45 @@ RSpec.describe PostMover do end end end + + context "with event trigger" do + fab!(:topic_1) { Fabricate(:topic) } + fab!(:topic_2) { Fabricate(:topic) } + fab!(:post_1) { Fabricate(:post, topic: topic_1) } + fab!(:post_2) { Fabricate(:post, topic: topic_1) } + + it "receives 2 post moved event triggers for the first post" do + post_mover = PostMover.new(topic_1, Discourse.system_user, [post_1.id]) + events = DiscourseEvent.track_events { post_mover.to_topic(topic_2.id) } + filtered_events = + events.filter { |e| %i[first_post_moved post_moved].include? e[:event_name] } + + expect(filtered_events.size).to eq(2) + end + + it "uses first_post_moved trigger for first post" do + post_mover = PostMover.new(topic_1, Discourse.system_user, [post_1.id]) + events = DiscourseEvent.track_events(:first_post_moved) { post_mover.to_topic(topic_2.id) } + expect(events.size).to eq(1) + + new_post = Post.find_by(topic_id: topic_2.id, post_number: 1) + + event = events.first + expect(event[:event_name]).to eq(:first_post_moved) + expect(event[:params][0]).to eq(new_post) + expect(event[:params][1]).to eq(post_1) + end + + it "uses post_moved trigger for other posts" do + post_mover = PostMover.new(topic_1, Discourse.system_user, [post_2.id]) + events = DiscourseEvent.track_events(:post_moved) { post_mover.to_topic(topic_2.id) } + expect(events.size).to eq(1) + + event = events.first + expect(event[:event_name]).to eq(:post_moved) + expect(event[:params][0]).to eq(post_2) + expect(event[:params][1]).to eq(topic_1.id) + end + end end end