Skip to content

Instantly share code, notes, and snippets.

@GesJeremie
Created April 23, 2017 16:24
Show Gist options
  • Save GesJeremie/ad604afac38b6f762275b38e009ff27e to your computer and use it in GitHub Desktop.
Save GesJeremie/ad604afac38b6f762275b38e009ff27e to your computer and use it in GitHub Desktop.
defmodule Babysitting.Operations.Classified.CreateContactOperation do
import Plug.Conn;
alias Babysitting.Repo;
alias Babysitting.{ClassifiedContact}
alias Babysitting.Changesets.{ClassifiedContactChangeset}
def run(conn, params, options) do
conn = assign(conn, :params, params)
conn = assign(conn, :options, options)
with {:ok, conn} <- get_changeset(conn),
{:ok, conn} <- save_contact(conn),
{:ok, conn} <- preload_associations_contact(conn),
{:ok, conn} <- send_email_admin(conn),
{:ok, conn} <- send_email_babysitter(conn)
do
{:ok, conn}
else
{:error, conn, :save_contact} ->
# TODO: Add flash error
IO.puts "errors lol"
{:error, conn}
end
end
def get_changeset(conn) do
params = conn.assigns.params |> Map.put("classified_id", conn.assigns.options.classified_id)
changeset = ClassifiedContactChangeset.create(%ClassifiedContact{}, params)
conn = assign(conn, :changeset, changeset)
{:ok, conn}
end
def save_contact(conn) do
case Repo.insert(conn.assigns.changeset) do
{:ok, contact} ->
conn = assign(conn, :contact, contact)
{:ok, conn}
{:error, changeset} ->
conn = assign(conn, :changeset, changeset)
{:error, conn, :save_contact}
end
end
def preload_associations_contact(conn) do
contact =
conn.assigns.contact
|> Repo.preload(:classified)
|> Repo.preload(classified: :tenant)
conn = assign(conn, :contact, contact)
{:ok, conn}
end
def send_email_admin(conn) do
Email.new_contact_admin(%{conn: conn, contact: conn.assigns.contact}) |> Mailer.deliver_later
{:ok, conn}
end
def send_email_babysitter(conn) do
Email.new_contact(%{conn: conn, contact: conn.assigns.contact}) |> Mailer.deliver_later
{:ok, conn}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment