FIX: user directory didn't update stats of users with no recent activity

This commit is contained in:
Neil Lalonde 2017-08-09 15:57:35 -04:00
parent 53e6ccf17b
commit ca1609c821
2 changed files with 31 additions and 4 deletions

View File

@ -41,6 +41,7 @@ class DirectoryItem < ActiveRecord::Base
end
ActiveRecord::Base.transaction do
# Delete records that belonged to users who have been deleted
exec_sql "DELETE FROM directory_items
USING directory_items di
LEFT JOIN users u ON u.id = user_id
@ -48,6 +49,7 @@ class DirectoryItem < ActiveRecord::Base
u.id IS NULL AND
di.period_type = :period_type", period_type: period_types[period_type]
# Create new records for users who don't have one yet
exec_sql "INSERT INTO directory_items(period_type, user_id, likes_received, likes_given, topics_entered, days_visited, posts_read, topic_count, post_count)
SELECT
:period_type,
@ -64,6 +66,7 @@ class DirectoryItem < ActiveRecord::Base
WHERE di.id IS NULL AND u.id > 0
", period_type: period_types[period_type]
# Calculate new values and update records
exec_sql "WITH x AS (SELECT
u.id user_id,
SUM(CASE WHEN ua.action_type = :was_liked_type THEN 1 ELSE 0 END) likes_received,
@ -74,13 +77,12 @@ class DirectoryItem < ActiveRecord::Base
SUM(CASE WHEN ua.action_type = :new_topic_type THEN 1 ELSE 0 END) topic_count,
SUM(CASE WHEN ua.action_type = :reply_type THEN 1 ELSE 0 END) post_count
FROM users AS u
LEFT OUTER JOIN user_actions AS ua ON ua.user_id = u.id
LEFT OUTER JOIN user_actions AS ua ON ua.user_id = u.id AND COALESCE(ua.created_at, :since) >= :since
LEFT OUTER JOIN topics AS t ON ua.target_topic_id = t.id AND t.archetype = 'regular'
LEFT OUTER JOIN posts AS p ON ua.target_post_id = p.id
LEFT OUTER JOIN categories AS c ON t.category_id = c.id
WHERE u.active
AND NOT u.blocked
AND COALESCE(ua.created_at, :since) >= :since
AND t.deleted_at IS NULL
AND COALESCE(t.visible, true)
AND p.deleted_at IS NULL

View File

@ -23,14 +23,39 @@ describe DirectoryItem do
UserActionCreator.enable
end
let!(:post) { create_post }
it "creates the record for the user" do
post = create_post
DirectoryItem.refresh!
expect(DirectoryItem.where(period_type: DirectoryItem.period_types[:all])
.where(user_id: post.user.id)
.where(topic_count: 1).count).to eq(1)
end
it "handles users with no activity" do
post = nil
freeze_time(2.years.ago) do
post = create_post
# Create records for that activity
DirectoryItem.refresh!
end
DirectoryItem.refresh!
[:yearly, :monthly, :weekly, :daily, :quarterly].each do |period|
directory_item = DirectoryItem
.where(period_type: DirectoryItem.period_types[period])
.where(user_id: post.user.id)
.first
expect(directory_item.topic_count).to eq(0)
expect(directory_item.post_count).to eq(0)
end
directory_item = DirectoryItem
.where(period_type: DirectoryItem.period_types[:all])
.where(user_id: post.user.id)
.first
expect(directory_item.topic_count).to eq(1)
end
end
end