Browse Source

improvement: make series generation more modular

pull/48/head
Inhji Y. 12 months ago
parent
commit
6d5452c536
  1. 18
      apps/listens/lib/listens/report.ex
  2. 16
      apps/listens/lib/listens/series.ex
  3. 2
      apps/tomie_web/lib/tomie_web/live/listen_live/charts.ex

18
apps/listens/lib/listens/report.ex

@ -1,5 +1,6 @@
defmodule Listens.Report do
import Ecto.Query, warn: false
import Listens.Series
alias Listens.Artists.Artist
alias Listens.Albums.Album
@ -46,21 +47,12 @@ defmodule Listens.Report do
Db.Repo.all(q)
end
def listens_per_day_query(artist_id, days) do
days_minus_one = days - 1
def listens_per_day_query(artist_id, [{range, value}]) when range in [:days, :weeks, :months] do
final_range = range |> to_string() |> String.replace_trailing("s", "")
final_value = value - 1
from(l in Listen,
right_join:
day in fragment(
"""
SELECT generate_series(
current_date - interval '1 day' * ?,
current_date,
'1 day'
)::date AS d
""",
^days_minus_one
),
right_join: day in series_day(^final_value),
on: day.d == fragment("date(?)", l.listened_at) and l.artist_id == ^artist_id,
group_by: day.d,
order_by: day.d,

16
apps/listens/lib/listens/series.ex

@ -0,0 +1,16 @@
defmodule Listens.Series do
defmacro series_day(value) do
quote do
fragment(
"""
SELECT generate_series(
current_date - interval '1 day' * ?,
current_date,
'1 day'
)::date AS d
""",
unquote(value)
)
end
end
end

2
apps/tomie_web/lib/tomie_web/live/listen_live/charts.ex

@ -13,7 +13,7 @@ defmodule TomieWeb.ListenLive.Charts do
Listens.Artists.Artist
|> Listens.Report.top(6, weeks: -2)
|> Enum.map(fn %{model: artist, listens: _l} ->
%{name: artist.name, data: Listens.Report.by_day(artist.id, 14)}
%{name: artist.name, data: Listens.Report.by_day(artist.id, days: 14)}
end)
|> Jason.encode!()
]

Loading…
Cancel
Save