57 lines
1.3 KiB
Elixir
57 lines
1.3 KiB
Elixir
defmodule SendItWeb.SubscriptionLive do
|
|
use SendItWeb, :live_view
|
|
|
|
alias SendIt.Marketing
|
|
|
|
@impl true
|
|
def mount(params, _session, socket) do
|
|
{:ok, assign_form(socket, params)}
|
|
end
|
|
|
|
@impl true
|
|
def render(assigns) do
|
|
~H"""
|
|
<div>
|
|
<.header>
|
|
Unsubscribe
|
|
<:subtitle>Enter your email address below to unsubscribe from all emails.</:subtitle>
|
|
</.header>
|
|
|
|
<.simple_form for={@form} id="subscription-form" phx-submit="save">
|
|
<.input type="email" field={@form[:email]} />
|
|
<:actions>
|
|
<.button phx-disable-with="Saving changes...">Unsubscribe</.button>
|
|
</:actions>
|
|
</.simple_form>
|
|
</div>
|
|
"""
|
|
end
|
|
|
|
@impl true
|
|
def handle_event("save", %{"email" => email}, socket) do
|
|
unsubscribe(socket, email)
|
|
end
|
|
|
|
defp unsubscribe(socket, email) do
|
|
case Marketing.unsubscribe(email) do
|
|
{:ok, _contact} ->
|
|
{:noreply,
|
|
socket
|
|
|> assign_form(%{})
|
|
|> put_flash(:info, "You have been unsubscribed from all emails.")}
|
|
|
|
{:error, reason} ->
|
|
{:noreply, put_flash(socket, :error, reason)}
|
|
end
|
|
end
|
|
|
|
defp assign_form(socket, params) do
|
|
email = handle_params(params)
|
|
assign(socket, :form, to_form(%{"email" => email}))
|
|
end
|
|
|
|
defp handle_params(%{"email" => email}), do: email
|
|
|
|
defp handle_params(_params), do: ""
|
|
end
|