cannery/lib/lokal_web/live/invite_live/form_component.ex

90 lines
2.6 KiB
Elixir
Raw Normal View History

2022-02-25 22:13:35 -05:00
defmodule LokalWeb.InviteLive.FormComponent do
@moduledoc """
2023-02-04 14:14:45 -05:00
Livecomponent that can update or create an Lokal.Accounts.Invite
2022-02-25 22:13:35 -05:00
"""
use LokalWeb, :live_component
alias Ecto.Changeset
2023-02-04 14:14:45 -05:00
alias Lokal.Accounts.{Invite, Invites, User}
2022-02-25 22:13:35 -05:00
alias Phoenix.LiveView.Socket
@impl true
@spec update(
%{:invite => Invite.t(), :current_user => User.t(), optional(any) => any},
Socket.t()
) :: {:ok, Socket.t()}
2023-02-04 14:14:45 -05:00
def update(%{invite: _invite} = assigns, socket) do
{:ok, socket |> assign(assigns) |> assign_changeset(%{})}
2022-02-25 22:13:35 -05:00
end
@impl true
2023-02-04 14:14:45 -05:00
def handle_event("validate", %{"invite" => invite_params}, socket) do
{:noreply, socket |> assign_changeset(invite_params)}
2022-02-25 22:13:35 -05:00
end
def handle_event("save", %{"invite" => invite_params}, %{assigns: %{action: action}} = socket) do
save_invite(socket, action, invite_params)
end
2023-02-04 14:14:45 -05:00
defp assign_changeset(
%{assigns: %{action: action, current_user: user, invite: invite}} = socket,
invite_params
) do
changeset_action =
case action do
:new -> :insert
:edit -> :update
end
changeset =
case action do
:new -> Invite.create_changeset(user, "example_token", invite_params)
:edit -> invite |> Invite.update_changeset(invite_params)
end
changeset =
case changeset |> Changeset.apply_action(changeset_action) do
{:ok, _data} -> changeset
{:error, changeset} -> changeset
end
socket |> assign(:changeset, changeset)
end
2022-02-25 22:13:35 -05:00
defp save_invite(
%{assigns: %{current_user: current_user, invite: invite, return_to: return_to}} = socket,
:edit,
invite_params
) do
socket =
case invite |> Invites.update_invite(invite_params, current_user) do
{:ok, %{name: invite_name}} ->
2023-02-04 14:14:45 -05:00
prompt = dgettext("prompts", "%{name} updated successfully", name: invite_name)
socket |> put_flash(:info, prompt) |> push_navigate(to: return_to)
2022-02-25 22:13:35 -05:00
{:error, %Changeset{} = changeset} ->
socket |> assign(:changeset, changeset)
end
{:noreply, socket}
end
defp save_invite(
%{assigns: %{current_user: current_user, return_to: return_to}} = socket,
:new,
invite_params
) do
socket =
case current_user |> Invites.create_invite(invite_params) do
{:ok, %{name: invite_name}} ->
2023-02-04 14:14:45 -05:00
prompt = dgettext("prompts", "%{name} created successfully", name: invite_name)
socket |> put_flash(:info, prompt) |> push_navigate(to: return_to)
2022-02-25 22:13:35 -05:00
{:error, %Changeset{} = changeset} ->
socket |> assign(changeset: changeset)
end
{:noreply, socket}
end
end