diff --git a/app/models/topic_user.rb b/app/models/topic_user.rb index bbf6283d07f..bcc24d979f6 100644 --- a/app/models/topic_user.rb +++ b/app/models/topic_user.rb @@ -234,6 +234,8 @@ class TopicUser < ActiveRecord::Base first_visited_at: now , last_visited_at: now )) + + DiscourseEvent.trigger(:topic_first_visited_by_user, topic_id, user_id) end def track_visit!(topic_id, user_id) diff --git a/spec/models/topic_user_spec.rb b/spec/models/topic_user_spec.rb index 6884a95ec13..f68f41b7728 100644 --- a/spec/models/topic_user_spec.rb +++ b/spec/models/topic_user_spec.rb @@ -477,4 +477,32 @@ describe TopicUser do end end + it "correctly triggers an event on first visit" do + begin + tracked_user = Fabricate(:user) + post = create_post + + called = 0 + visits = [] + user_first_visit = -> (topic_id, user_id) do + visits << "#{topic_id}-#{user_id}" + called += 1 + end + + DiscourseEvent.on(:topic_first_visited_by_user, &user_first_visit) + + expect(called).to eq(0) + + TopicUser.change(tracked_user, post.topic.id, total_msecs_viewed: 1) + + expect(visits).to eq(["#{post.topic.id}-#{tracked_user.id}"]) + expect(called).to eq(1) + + TopicUser.change(tracked_user, post.topic.id, total_msecs_viewed: 2) + + expect(called).to eq(1) + ensure + DiscourseEvent.off(:topic_first_visited_by_user, &user_first_visit) + end + end end