Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Use group by for grouping tweets

Uku Taht9df398b663f3
diff --git a/lib/plausible/stats/stats.ex b/lib/plausible/stats/stats.ex
index b17c6696ce..36d61349c9 100644
--- a/lib/plausible/stats/stats.ex
+++ b/lib/plausible/stats/stats.ex
@@ -253,10 +253,7 @@ defmodule Plausible.Stats do
tweets = Repo.all(
from t in Plausible.Twitter.Tweet,
where: t.link in ^urls
- ) |> Enum.reduce(%{}, fn tweet, acc ->
- Map.update(acc, tweet.link, [tweet], &([tweet | &1]))
- end)
- |> IO.inspect
+ ) |> Enum.group_by(&(&1.link))
Enum.map(referring_urls, fn url ->
Map.put(url, :tweets, tweets[url[:name]])
diff --git a/test/plausible_web/controllers/api/stats_controller/referrers_test.exs b/test/plausible_web/controllers/api/stats_controller/referrers_test.exs
index 7959978ef8..c49855c2e0 100644
--- a/test/plausible_web/controllers/api/stats_controller/referrers_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/referrers_test.exs
@@ -133,5 +133,21 @@ defmodule PlausibleWeb.Api.StatsController.ReferrersTest do
"search_terms" => terms
}
end
+
+ test "enriches twitter referrers with tweets if available", %{conn: conn, site: site} do
+ insert(:pageview, hostname: site.domain, referrer: "t.co/some-link", referrer_source: "Twitter", timestamp: ~N[2019-01-01 01:00:00])
+ insert(:pageview, hostname: site.domain, referrer: "t.co/some-link", referrer_source: "Twitter", timestamp: ~N[2019-01-01 01:00:00])
+ insert(:pageview, hostname: site.domain, referrer: "t.co/nonexistent-link", referrer_source: "Twitter", timestamp: ~N[2019-01-01 02:00:00])
+
+ insert(:tweet, link: "t.co/some-link", text: "important tweet")
+
+ conn = get(conn, "/api/stats/#{site.domain}/referrers/Twitter?period=day&date=2019-01-01")
+
+ res = json_response(conn, 200)
+ assert res["total_visitors"] == 3
+ assert [tweet1, tweet2] = res["referrers"]
+ assert %{"name" => "t.co/some-link", "count" => 2, "tweets" => [%{"text" => "important tweet"}]} = tweet1
+ assert %{"name" => "t.co/nonexistent-link", "count" => 1, "tweets" => nil} = tweet2
+ end
end
end
diff --git a/test/support/factory.ex b/test/support/factory.ex
index b266c74784..ac9529155e 100644
--- a/test/support/factory.ex
+++ b/test/support/factory.ex
@@ -79,4 +79,15 @@ defmodule Plausible.Factory do
expires: Timex.now() |> Timex.shift(days: 1)
}
end
+
+ def tweet_factory do
+ %Plausible.Twitter.Tweet{
+ tweet_id: UUID.uuid4(),
+ author_handle: "author-handle",
+ author_name: "author-name",
+ author_image: "pic.twitter.com/author.png",
+ text: "tweet-text",
+ created: Timex.now()
+ }
+ end
end