diff --git a/app/models/topic.rb b/app/models/topic.rb index b8be34167ee..6b01d9e4535 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -662,12 +662,26 @@ SQL if self.category_id != new_category.id self.update!(category_id: new_category.id) - Category.where(id: old_category.id).update_all("topic_count = topic_count - 1") if old_category + + if old_category + Category + .where(id: old_category.id) + .update_all("topic_count = topic_count - 1") + end # when a topic changes category we may have to start watching it # if we happen to have read state for it CategoryUser.auto_watch(category_id: new_category.id, topic_id: self.id) CategoryUser.auto_track(category_id: new_category.id, topic_id: self.id) + + post = self.ordered_posts.first + + if post + PostAlerter.new.notify_post_users( + post, + [post.user, post.last_editor].uniq + ) + end end Category.where(id: new_category.id).update_all("topic_count = topic_count + 1") diff --git a/spec/fabricators/topic_fabricator.rb b/spec/fabricators/topic_fabricator.rb index 1fd06233cdd..b3efbb98e3d 100644 --- a/spec/fabricators/topic_fabricator.rb +++ b/spec/fabricators/topic_fabricator.rb @@ -17,7 +17,6 @@ Fabricator(:banner_topic, from: :topic) do end Fabricator(:private_message_topic, from: :topic) do - user category_id { nil } title { sequence(:title) { |i| "This is a private message #{i}" } } archetype "private_message" diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb index 6a17b19bec7..aed6e653ddc 100644 --- a/spec/models/topic_spec.rb +++ b/spec/models/topic_spec.rb @@ -1191,11 +1191,8 @@ describe Topic do category.reload end - it 'increases the topic_count' do - expect(category.topic_count).to eq(1) - end - it "doesn't change the topic_count when the value doesn't change" do + expect(category.topic_count).to eq(1) expect { topic.change_category_to_id(category.id); category.reload }.not_to change(category, :topic_count) end @@ -1215,6 +1212,29 @@ describe Topic do expect(category.reload.topic_count).to eq(0) end + describe 'user that watching the new category' do + it 'should generate the notification for the topic' do + topic.posts << Fabricate(:post) + + CategoryUser.set_notification_level_for_category( + user, + CategoryUser::notification_levels[:watching], + new_category.id + ) + + expect do + topic.change_category_to_id(new_category.id) + end.to change { Notification.count }.by(1) + + notification = Notification.last + + expect(notification.notification_type).to eq(Notification.types[:posted]) + expect(notification.topic_id).to eq(topic.id) + expect(notification.user_id).to eq(user.id) + expect(notification.post_number).to eq(1) + end + end + describe 'when new category is set to auto close by default' do before do new_category.update!(auto_close_hours: 5)