From 6bd26e81c1a1f8150aee8afa5e8a7502c58ec4ed Mon Sep 17 00:00:00 2001 From: Penar Musaraj Date: Thu, 8 Feb 2024 11:17:59 -0500 Subject: [PATCH] FIX: Respect date range in top traffic sources report (#25599) See https://meta.discourse.org/t/reports-top-traffic-sources-topics-stat-issue/179850 --- app/models/incoming_links_report.rb | 9 +++++- spec/models/incoming_links_report_spec.rb | 38 +++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/app/models/incoming_links_report.rb b/app/models/incoming_links_report.rb index 3c17ff38100..9c965ad8d6a 100644 --- a/app/models/incoming_links_report.rb +++ b/app/models/incoming_links_report.rb @@ -138,6 +138,8 @@ class IncomingLinksReport num_clicks.keys, category_id: report.category_id, include_subcategories: report.include_subcategories, + start_date: report.start_date, + end_date: report.end_date, ) report.data = [] num_clicks.each_key do |domain| @@ -176,7 +178,12 @@ class IncomingLinksReport include_subcategories: options[:include_subcategories], ) .joins(incoming_referer: :incoming_domain) - .where("incoming_links.created_at > ? AND incoming_domains.name IN (?)", 30.days.ago, domains) + .where( + "incoming_links.created_at > ? AND incoming_links.created_at < ?", + options[:start_date], + options[:end_date], + ) + .where("incoming_domains.name IN (?)", domains) .group("incoming_domains.name") end diff --git a/spec/models/incoming_links_report_spec.rb b/spec/models/incoming_links_report_spec.rb index c168ff79122..1bc5c498870 100644 --- a/spec/models/incoming_links_report_spec.rb +++ b/spec/models/incoming_links_report_spec.rb @@ -127,6 +127,44 @@ RSpec.describe IncomingLinksReport do }, ] end + + it "respects date ranges" do + p1 = create_post + p1.topic.save + + p2 = create_post + p2.topic.save + + 2.times do |n| + IncomingLink.create( + referer: "http://test.com", + post_id: p1.id, + ip_address: "10.0.0.#{n}", + user_id: p1.user.id, + created_at: 2.days.ago, + ) + end + + 3.times do |n| + IncomingLink.create( + referer: "http://yowza.com", + post_id: p2.id, + ip_address: "10.0.0.#{n}", + user_id: p2.user.id, + created_at: 2.months.ago, + ) + end + + r = IncomingLinksReport.find("top_traffic_sources").as_json + expect(r[:data]).to eq [{ domain: "test.com", num_clicks: 2, num_topics: 1 }] + + r2 = + IncomingLinksReport.find( + "top_traffic_sources", + { start_date: 3.months.ago, end_date: 1.month.ago }, + ).as_json + expect(r2[:data]).to eq [{ domain: "yowza.com", num_clicks: 3, num_topics: 1 }] + end end describe "top_referrers" do