Skip to content

A platform for community discussion. Free, open, simple.

FIX: Unread group PMs should use `GroupUser#first_unread_pm_at`. (#14075)

Alan Guo Xiang Tand13716286c36
diff --git a/lib/topic_query/private_message_lists.rb b/lib/topic_query/private_message_lists.rb
index da8d204aca1..9aaadbabbe6 100644
--- a/lib/topic_query/private_message_lists.rb
+++ b/lib/topic_query/private_message_lists.rb
@@ -182,9 +182,23 @@ class TopicQuery
staff: user.staff?
)
- first_unread_pm_at = UserStat
- .where(user_id: user.id)
- .pluck_first(:first_unread_pm_at)
+ first_unread_pm_at =
+ case type
+ when :user
+ user_first_unread_pm_at(user)
+ when :group
+ GroupUser
+ .where(user: user, group: group)
+ .pluck_first(:first_unread_pm_at)
+ else
+ user_first_unread_pm_at = user_first_unread_pm_at(user)
+
+ group_first_unread_pm_at = GroupUser
+ .where(user: user)
+ .minimum(:first_unread_pm_at)
+
+ [user_first_unread_pm_at, group_first_unread_pm_at].compact.min
+ end
if first_unread_pm_at
list = list.where("topics.updated_at >= ?", first_unread_pm_at)
@@ -246,5 +260,9 @@ class TopicQuery
.first
end
end
+
+ def user_first_unread_pm_at(user)
+ UserStat.where(user: user).pluck_first(:first_unread_pm_at)
+ end
end
end
diff --git a/spec/lib/topic_query/private_message_lists_spec.rb b/spec/lib/topic_query/private_message_lists_spec.rb
index 29701387440..6c02589c158 100644
--- a/spec/lib/topic_query/private_message_lists_spec.rb
+++ b/spec/lib/topic_query/private_message_lists_spec.rb
@@ -111,16 +111,26 @@ describe TopicQuery::PrivateMessageLists do
end
describe '#list_private_messages_all_unread' do
- it 'returns a list of unread private messages' do
- topics = TopicQuery.new(nil).list_private_messages_all_unread(user_2).topics
-
- expect(topics).to eq([])
-
+ before do
TopicUser.find_by(user: user_2, topic: group_message).update!(
last_read_post_number: 1
)
create_post(user: user, topic: group_message)
+ end
+
+ it 'returns a list of unread private messages' do
+ topics = TopicQuery.new(nil).list_private_messages_all_unread(user_2).topics
+
+ expect(topics).to contain_exactly(group_message)
+ end
+
+ it 'takes into account first_unread_pm_at optimization' do
+ user_2.user_stat.update!(first_unread_pm_at: group_message.created_at + 1.day)
+
+ GroupUser.find_by(user: user_2, group: group).update!(
+ first_unread_pm_at: group_message.created_at - 1.day
+ )
topics = TopicQuery.new(nil).list_private_messages_all_unread(user_2).topics