cannery/lib/cannery_web/live/container_live/index.ex

83 lines
2.4 KiB
Elixir
Raw Normal View History

2021-09-02 23:31:14 -04:00
defmodule CanneryWeb.ContainerLive.Index do
2022-01-22 21:40:29 -05:00
@moduledoc """
Liveview for showing Cannery.Containers.Container index
"""
2021-09-02 23:31:14 -04:00
use CanneryWeb, :live_view
2022-02-05 01:59:40 -05:00
import CanneryWeb.ContainerLive.ContainerCard
2022-02-07 23:58:29 -05:00
alias Cannery.{Containers, Containers.Container}
2021-09-02 23:31:14 -04:00
@impl true
2021-09-02 23:31:16 -04:00
def mount(_params, session, socket) do
2022-01-31 21:42:24 -05:00
{:ok, socket |> assign_defaults(session) |> display_containers()}
2021-09-02 23:31:14 -04:00
end
@impl true
def handle_params(params, _url, socket) do
{:noreply, apply_action(socket, socket.assigns.live_action, params)}
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
2022-02-09 00:49:47 -05:00
|> assign(:page_title, gettext("Edit Container"))
2021-09-02 23:31:14 -04:00
|> assign(:container, Containers.get_container!(id))
end
defp apply_action(socket, :new, _params) do
socket
2022-02-09 00:49:47 -05:00
|> assign(:page_title, gettext("New Container"))
2021-09-02 23:31:14 -04:00
|> assign(:container, %Container{})
end
defp apply_action(socket, :index, _params) do
socket
2022-02-09 00:49:47 -05:00
|> assign(:page_title, gettext("Listing Containers"))
2021-09-02 23:31:14 -04:00
|> assign(:container, nil)
end
@impl true
def handle_event("delete", %{"id" => id}, socket) do
2022-02-07 23:58:29 -05:00
socket =
socket.assigns.containers
|> Enum.find(fn %{id: container_id} -> id == container_id end)
|> case do
nil ->
2022-02-09 00:49:47 -05:00
socket |> put_flash(:error, dgettext("errors", "Could not find that container"))
2022-02-07 23:58:29 -05:00
container ->
container
2022-02-08 22:10:48 -05:00
|> Containers.delete_container(socket.assigns.current_user)
2022-02-07 23:58:29 -05:00
|> case do
{:ok, container} ->
socket
2022-02-09 00:49:47 -05:00
|> put_flash(
:info,
dgettext("prompts", "%{name} has been deleted", name: container.name)
)
2022-02-07 23:58:29 -05:00
|> display_containers()
{:error, %{action: :delete, errors: [ammo_groups: _error], valid?: false} = changeset} ->
ammo_groups_error = changeset |> changeset_errors(:ammo_groups) |> Enum.join(", ")
2022-02-09 00:49:47 -05:00
socket
|> put_flash(
:error,
dgettext("errors", "Could not delete container: %{error}",
error: ammo_groups_error
)
)
2022-02-07 23:58:29 -05:00
{:error, changeset} ->
socket |> put_flash(:error, changeset |> changeset_errors())
end
end
{:noreply, socket}
2021-09-02 23:31:14 -04:00
end
2022-01-31 21:42:24 -05:00
defp display_containers(%{assigns: %{current_user: current_user}} = socket) do
containers = Containers.list_containers(current_user)
socket |> assign(containers: containers)
2021-09-02 23:31:14 -04:00
end
end