cannery/lib/cannery_web/components/add_shot_group_component.ex

83 lines
2.4 KiB
Elixir
Raw Normal View History

2022-02-15 17:33:45 -05:00
defmodule CanneryWeb.Components.AddShotGroupComponent do
@moduledoc """
Livecomponent that can create a ShotGroup
"""
use CanneryWeb, :live_component
alias Cannery.{Accounts.User, ActivityLog, ActivityLog.ShotGroup, Ammo.AmmoGroup}
alias Ecto.Changeset
2022-11-10 22:01:32 -05:00
alias Phoenix.LiveView.{JS, Socket}
2022-02-15 17:33:45 -05:00
@impl true
@spec update(
%{
required(:current_user) => User.t(),
required(:ammo_group) => AmmoGroup.t(),
optional(any()) => any()
},
Socket.t()
) :: {:ok, Socket.t()}
2022-07-01 21:39:08 -04:00
def update(%{ammo_group: ammo_group, current_user: current_user} = assigns, socket) do
2022-02-15 17:33:45 -05:00
changeset =
%ShotGroup{date: Date.utc_today()}
2022-07-01 21:39:08 -04:00
|> ShotGroup.create_changeset(current_user, ammo_group, %{})
2022-02-15 17:33:45 -05:00
{:ok, socket |> assign(assigns) |> assign(:changeset, changeset)}
end
@impl true
def handle_event(
"validate",
%{"shot_group" => shot_group_params},
2022-07-01 21:39:08 -04:00
%{assigns: %{ammo_group: ammo_group, current_user: current_user}} = socket
2022-02-15 17:33:45 -05:00
) do
2022-07-01 21:39:08 -04:00
params = shot_group_params |> process_params(ammo_group)
2022-02-15 17:33:45 -05:00
changeset = %ShotGroup{} |> ShotGroup.create_changeset(current_user, ammo_group, params)
2022-02-15 17:33:45 -05:00
changeset =
case changeset |> Changeset.apply_action(:validate) do
{:ok, _data} -> changeset
{:error, changeset} -> changeset
end
2022-02-15 17:33:45 -05:00
{:noreply, socket |> assign(:changeset, changeset)}
end
def handle_event(
"save",
%{"shot_group" => shot_group_params},
%{
2022-07-01 21:39:08 -04:00
assigns: %{ammo_group: ammo_group, current_user: current_user, return_to: return_to}
2022-02-15 17:33:45 -05:00
} = socket
) do
socket =
shot_group_params
|> process_params(ammo_group)
|> ActivityLog.create_shot_group(current_user, ammo_group)
|> case do
{:ok, _shot_group} ->
prompt = dgettext("prompts", "Shots recorded successfully")
socket |> put_flash(:info, prompt) |> push_navigate(to: return_to)
2022-02-15 17:33:45 -05:00
{:error, %Changeset{} = changeset} ->
2022-02-15 17:33:45 -05:00
socket |> assign(changeset: changeset)
end
{:noreply, socket}
end
# calculate count from shots left
defp process_params(params, %AmmoGroup{count: count}) do
shot_group_count =
if params |> Map.get("ammo_left", "") == "" do
nil
2022-02-15 17:33:45 -05:00
else
new_count = params |> Map.get("ammo_left") |> String.to_integer()
count - new_count
2022-02-15 17:33:45 -05:00
end
params |> Map.put("count", shot_group_count)
2022-02-15 17:33:45 -05:00
end
end