restrict ammo groups by user_id

This commit is contained in:
shibao 2022-02-08 00:21:22 -05:00
parent 8e4bcf7abd
commit ab9a73769f
3 changed files with 29 additions and 14 deletions

View File

@ -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

View File

@ -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!()
)

View File

@ -92,10 +92,10 @@
<hr class="hr">
<div>
<%= if @ammo_type.ammo_groups |> Enum.empty?() do %>
<%= if @ammo_groups |> Enum.empty?() do %>
No ammo for this type
<% else %>
<%= for ammo_group <- @ammo_type.ammo_groups do %>
<%= for ammo_group <- @ammo_groups do %>
<.ammo_group_card ammo_group={ammo_group} />
<% end %>
<% end %>