diff --git a/lib/cannery/ammo.ex b/lib/cannery/ammo.ex index 1727ef84..b77e2e27 100644 --- a/lib/cannery/ammo.ex +++ b/lib/cannery/ammo.ex @@ -52,7 +52,7 @@ defmodule Cannery.Ammo do """ @spec get_average_cost_for_ammo_type!(AmmoType.t()) :: float() - def get_average_cost_for_ammo_type!(%{id: ammo_type_id}) do + def get_average_cost_for_ammo_type!(%AmmoType{id: ammo_type_id}) do Repo.one!( from ag in AmmoGroup, where: ag.ammo_type_id == ^ammo_type_id, @@ -140,21 +140,34 @@ defmodule Cannery.Ammo do do: AmmoType.changeset(ammo_type, attrs) @doc """ - Returns the list of ammo_groups. + Returns the list of ammo_groups for a user and type. + + ## Examples + + iex> list_ammo_groups_for_type(%AmmoType{id: 123}, %User{id: 123}) + [%AmmoGroup{}, ...] + + """ + @spec list_ammo_groups_for_type(AmmoType.t(), User.t()) :: [AmmoGroup.t()] + def list_ammo_groups_for_type(%AmmoType{id: ammo_type_id}, %User{id: user_id}) do + Repo.all( + from am in AmmoGroup, + where: am.ammo_type_id == ^ammo_type_id, + where: am.user_id == ^user_id + ) + end + + @doc """ + Returns the list of ammo_groups for a user. ## Examples iex> list_ammo_groups(%User{id: 123}) [%AmmoGroup{}, ...] - iex> list_ammo_groups(123) - [%AmmoGroup{}, ...] - """ - @spec list_ammo_groups(User.t() | User.id()) :: [AmmoGroup.t()] - def list_ammo_groups(%{id: user_id}), do: list_ammo_groups(user_id) - - def list_ammo_groups(user_id) do + @spec list_ammo_groups(User.t()) :: [AmmoGroup.t()] + def list_ammo_groups(%User{id: user_id}) do Repo.all(from am in AmmoGroup, where: am.user_id == ^user_id) end diff --git a/lib/cannery_web/live/ammo_type_live/show.ex b/lib/cannery_web/live/ammo_type_live/show.ex index f69a6061..9d6edda3 100644 --- a/lib/cannery_web/live/ammo_type_live/show.ex +++ b/lib/cannery_web/live/ammo_type_live/show.ex @@ -5,7 +5,7 @@ defmodule CanneryWeb.AmmoTypeLive.Show do use CanneryWeb, :live_view import CanneryWeb.AmmoGroupLive.AmmoGroupCard - alias Cannery.{Ammo, Repo} + alias Cannery.{Ammo} @impl true def mount(_params, session, socket) do @@ -13,14 +13,16 @@ defmodule CanneryWeb.AmmoTypeLive.Show do end @impl true - def handle_params(%{"id" => id}, _, socket) do - ammo_type = Ammo.get_ammo_type!(id) |> Repo.preload(:ammo_groups) + def handle_params(%{"id" => id}, _, %{assigns: %{current_user: current_user}} = socket) do + ammo_type = Ammo.get_ammo_type!(id) + ammo_groups = ammo_type |> Ammo.list_ammo_groups_for_type(current_user) socket = socket |> assign( page_title: page_title(socket.assigns.live_action), ammo_type: ammo_type, + ammo_groups: ammo_groups, avg_cost_per_round: ammo_type |> Ammo.get_average_cost_for_ammo_type!() ) diff --git a/lib/cannery_web/live/ammo_type_live/show.html.heex b/lib/cannery_web/live/ammo_type_live/show.html.heex index a62e26d8..1b79cbfc 100644 --- a/lib/cannery_web/live/ammo_type_live/show.html.heex +++ b/lib/cannery_web/live/ammo_type_live/show.html.heex @@ -92,10 +92,10 @@