-
Notifications
You must be signed in to change notification settings - Fork 0
/
project_recipients.ex
70 lines (58 loc) · 1.72 KB
/
project_recipients.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
defmodule ProjectStatus.ProjectRecipients do
use GenServer
# alias ProjectStatus.Project
alias ProjectStatus.EmailRecipient
# alias ProjectStatus.StatusEmail
alias ProjectStatus.Repo
import Ecto.Query
##
# API
def start(project_id) do
{:ok, pid} = Supervisor.start_child(ProjectStatus.ProjectRecipientsSupervisor, [self, project_id])
Process.link(pid)
{:ok, pid}
end
def add_recipient_to_project(pid, recipient) do
GenServer.call(pid, {:add_recipient_to_project, recipient})
end
def delete_recipient(pid, recipient_id) do
GenServer.call(pid, {:delete_recipient, recipient_id})
end
def project_recipients(pid) do
GenServer.call(pid, :project_recipients)
end
##
# Lifecycle
def start_link(client_pid, project_id) do
GenServer.start_link(__MODULE__, {client_pid, project_id})
end
def init({_,_} = state) do
{:ok, state}
end
##
# Callbacks
def handle_call({:add_recipient_to_project, recipient_params}, _from, {_, project_id} = state) do
recipient = recipient_params
|> Map.put("project_id", project_id)
|> add_recipient
{:reply, recipient, state}
end
def handle_call({:delete_recipient, recipient_id}, _from, state) do
Repo.get(EmailRecipient, recipient_id) |> Repo.delete!
{:reply, :ok, state}
end
def handle_call(:project_recipients, _from, {_, project_id} = state) do
recipients = (from r in EmailRecipient, where: r.project_id == ^project_id)
|> Repo.all
{:reply, {:ok, recipients}, state}
end
# private
defp add_recipient(params) do
changeset = EmailRecipient.changeset(%EmailRecipient{}, params)
if changeset.valid? do
changeset |> Repo.insert
else
{:error, changeset}
end
end
end