FIX: Consistently notify lowest post number if post_moved notification generation (#30448)

We currently query the posts table without an order when notifying users of moved posts. Generally the query will return the lowest post number post (b/c ID correlates with post_number in most cases) but not always. This adds an order to the post query in notify_moved_posts job.

Also I removed some if statement nesting with early returns / guard clauses.
This commit is contained in:
Mark VanLandingham
2024-12-23 09:53:43 -06:00
committed by GitHub
parent d69b7da3ca
commit df1fc5bca8
2 changed files with 23 additions and 16 deletions

View File

@ -6,27 +6,28 @@ module Jobs
raise Discourse::InvalidParameters.new(:post_ids) if args[:post_ids].blank? raise Discourse::InvalidParameters.new(:post_ids) if args[:post_ids].blank?
raise Discourse::InvalidParameters.new(:moved_by_id) if args[:moved_by_id].blank? raise Discourse::InvalidParameters.new(:moved_by_id) if args[:moved_by_id].blank?
# Make sure we don't notify the same user twice (in case multiple posts were moved at once.)
users_notified = Set.new
posts = posts =
Post Post
.includes(:user, :topic)
.where(id: args[:post_ids]) .where(id: args[:post_ids])
.where("user_id <> ?", args[:moved_by_id]) .where("user_id <> ?", args[:moved_by_id])
.includes(:user, :topic) .order(post_number: :asc)
if posts.present? return if posts.blank?
moved_by = User.find_by(id: args[:moved_by_id])
posts.each do |p| moved_by = User.find_by(id: args[:moved_by_id])
if users_notified.exclude?(p.user_id)
p.user.notifications.create( # Make sure we don't notify the same user twice (in case multiple posts were moved at once.)
notification_type: Notification.types[:moved_post], users_notified = Set.new
topic_id: p.topic_id, posts.each do |p|
post_number: p.post_number, next if users_notified.include?(p.user_id)
data: { topic_title: p.topic.title, display_username: moved_by.username }.to_json,
) p.user.notifications.create(
users_notified << p.user_id notification_type: Notification.types[:moved_post],
end topic_id: p.topic_id,
end post_number: p.post_number,
data: { topic_title: p.topic.title, display_username: moved_by.username }.to_json,
)
users_notified << p.user_id
end end
end end
end end

View File

@ -29,6 +29,12 @@ RSpec.describe Jobs::NotifyMovedPosts do
}.to change(moved_post_notifications, :count).by(2) }.to change(moved_post_notifications, :count).by(2)
end end
it "notifies on the post with lowest post number" do
Jobs::NotifyMovedPosts.new.execute(post_ids: [p1.id, p3.id], moved_by_id: admin.id)
expect(moved_post_notifications.last.post_number).to eq(p1.post_number)
end
context "when moved by one of the posters" do context "when moved by one of the posters" do
it "create one notifications, because the poster is the mover" do it "create one notifications, because the poster is the mover" do
expect { expect {