Skip to content

Commit

Permalink
Add count messages per user function (papercups-io#264)
Browse files Browse the repository at this point in the history
* add count_messages_per_user function

* add test to count_messages_per_user function

* fix count_messages_per_user broken tests
  • Loading branch information
estevanjantsk authored Oct 1, 2020
1 parent a533ed3 commit 912ec88
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/chat_api/reporting.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule ChatApi.Reporting do
"""

import Ecto.Query, warn: false
alias ChatApi.{Repo, Conversations.Conversation, Messages.Message}
alias ChatApi.{Repo, Conversations.Conversation, Messages.Message, Users.User}

# TODO: filter by records created between a given `from_date` and `to_date`
def messages_by_date(account_id) do
Expand All @@ -14,6 +14,15 @@ defmodule ChatApi.Reporting do
|> Repo.all()
end

def count_messages_per_user(account_id) do
Message
|> where(account_id: ^account_id)
|> join(:inner, [m], u in User, on: m.user_id == u.id)
|> select([m, u], %{user: %{id: u.id, email: u.email}, count: count(m.user_id)})
|> group_by([m, u], [m.user_id, u.id])
|> Repo.all()
end

# TODO: filter by records created between a given `from_date` and `to_date`
def conversations_by_date(account_id) do
Conversation
Expand Down
30 changes: 30 additions & 0 deletions test/chat_api/reporting_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,36 @@ defmodule ChatApi.ReportingTest do
] = Reporting.messages_by_date(account.id)
end

test "count_messages_per_user/1 should return correct number of messages sent per user on team",
%{
account: account,
customer: customer
} do
user_2 = user_fixture(account)
user_3 = user_fixture(account)
conversation = conversation_fixture(account, customer)

message_fixture(account, conversation, %{
inserted_at: ~N[2020-09-01 12:00:00],
user_id: user_2.id
})

message_fixture(account, conversation, %{
inserted_at: ~N[2020-09-02 12:00:00],
user_id: user_2.id
})

message_fixture(account, conversation, %{
inserted_at: ~N[2020-09-03 12:00:00],
user_id: user_3.id
})

assert [
%{count: 2},
%{count: 1}
] = Reporting.count_messages_per_user(account.id)
end

test "messages_by_date/1 only fetches messages by the given account id", %{
account: account,
customer: customer
Expand Down

0 comments on commit 912ec88

Please sign in to comment.