Skip to content

Commit 6655585

Browse files
authored
feat: add analytics. start with factcheck article contribution
- setting up analytics route and controller - fetch factcheck urls and authors, displaying it on UI - counting urls and displaying data on a table
1 parent 14e1627 commit 6655585

File tree

4 files changed

+68
-0
lines changed

4 files changed

+68
-0
lines changed

lib/dau/analytics.ex

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
defmodule DAU.Analytics do
2+
import Ecto.Query
3+
alias DAU.Feed.Common
4+
alias DAU.Repo
5+
6+
def fetch_author_and_url(opts \\ []) do
7+
query =
8+
Common
9+
|> query_author_and_url()
10+
11+
query =
12+
case Keyword.get(opts, :test_run) do
13+
true -> query |> limit(20) |> offset(0)
14+
_ -> query
15+
end
16+
17+
query
18+
|> Repo.all()
19+
|> count_urls_per_username()
20+
end
21+
22+
defp query_author_and_url(query) do
23+
from c in query,
24+
select: %{
25+
username: fragment("jsonb_array_elements(?)->>'username'", c.factcheck_articles),
26+
url: fragment("jsonb_array_elements(?)->>'url'", c.factcheck_articles)
27+
}
28+
end
29+
30+
defp count_urls_per_username(data) do
31+
data
32+
|> Enum.group_by(& &1.username)
33+
|> Enum.map(fn {username, urls} -> %{username: username, url_count: Enum.count(urls)} end)
34+
|> Enum.sort(&(&1.url_count >= &2.url_count))
35+
end
36+
end
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
defmodule DAUWeb.AnalyticsController do
2+
use DAUWeb, :controller
3+
alias DAU.Analytics
4+
5+
def hello_world(conn, _params) do
6+
data = Analytics.fetch_author_and_url()
7+
render(conn, :index, data: data)
8+
end
9+
end
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
defmodule DAUWeb.AnalyticsHTML do
2+
use DAUWeb, :html
3+
import DAUWeb.CoreComponents
4+
5+
def index(assigns) do
6+
~H"""
7+
<div class="flex justify-center">
8+
<div class="w-full max-w-4xl mx-auto">
9+
<.table id="analytics-table" rows={@data}>
10+
<:col :let={item} label="Username"><%= item.username %></:col>
11+
<:col :let={item} label="Factcheck Articles Added"><%= item.url_count %></:col>
12+
</.table>
13+
</div>
14+
</div>
15+
"""
16+
end
17+
end

lib/dau_web/router.ex

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,4 +158,10 @@ defmodule DAUWeb.Router do
158158
live "/users/confirm", UserConfirmationInstructionsLive, :new
159159
end
160160
end
161+
162+
scope "/analytics", DAUWeb do
163+
pipe_through [:browser]
164+
165+
get "/", AnalyticsController, :hello_world
166+
end
161167
end

0 commit comments

Comments
 (0)