defmodule Resend.Conversations.TagInteractor do
import Ecto.Changeset
import Resend.Utils.Random
alias Resend.{
Conversation,
Tag,
Repo,
Message,
Endpoint
}
@doc """
Public API
"""
def run(params ) do
Repo.transaction fn ->
params
|> find_conversation
|> create_tag
|> create_status_message
|> notify_team
|> Map.get(:tag)
end
end
@doc """
Private API
"""
defp find_conversation(params = %{id: conversation_id}) do
conversation =
Conversation |> Repo.get(conversation_id)
params |> Map.put(:conversation, conversation)
end
defp create_tag(params = %{user: user, id: id, type: type}) do
tag = Tag.create!(%{conversation_id: id, user_id: user.id, type: type})
params |> Map.put(:tag, tag)
end
defp create_status_message(params = %{conversation: conversation, user: user}) do
message = %{
conversation_id: conversation.id,
type: "event",
subtype: "archived",
system: true,
data: %{
author_id: user.id
}
}
message =
Message.create!(message)
|> Map.put(:author_id, user.id)
|> Map.put(:author_name, user.display_name)
params |> Map.put(:message, message)
end
defp notify_team(params = %{conversation: conversation, tag: tag, message: message}) do
topic = "apps:" <> conversation.app_id
Endpoint.broadcast!(topic, "conversation_tagged", tag)
Endpoint.broadcast!(topic, "new_message", message)
params
end
end