show average cost per round for ammo types

This commit is contained in:
shibao 2022-02-06 00:40:01 -05:00
parent ad25164c16
commit c8945607ea
3 changed files with 41 additions and 4 deletions

View File

@ -37,6 +37,30 @@ defmodule Cannery.Ammo do
@spec get_ammo_type!(AmmoType.id()) :: AmmoType.t() @spec get_ammo_type!(AmmoType.id()) :: AmmoType.t()
def get_ammo_type!(id), do: Repo.get!(AmmoType, id) def get_ammo_type!(id), do: Repo.get!(AmmoType, id)
@doc """
Gets the average cost of a single ammo type
Raises `Ecto.NoResultsError` if the Ammo type does not exist.
## Examples
iex> get_ammo_type!(123)
%AmmoType{}
iex> get_ammo_type!(456)
** (Ecto.NoResultsError)
"""
@spec get_average_cost_for_ammo_type!(AmmoType.t()) :: float()
def get_average_cost_for_ammo_type!(%{id: ammo_type_id}) do
Repo.one!(
from ag in AmmoGroup,
where: ag.ammo_type_id == ^ammo_type_id,
where: not (ag.price_paid |> is_nil()),
select: sum(ag.price_paid) / sum(ag.count)
)
end
@doc """ @doc """
Creates a ammo_type. Creates a ammo_type.

View File

@ -14,11 +14,14 @@ defmodule CanneryWeb.AmmoTypeLive.Show do
@impl true @impl true
def handle_params(%{"id" => id}, _, socket) do def handle_params(%{"id" => id}, _, socket) do
ammo_type = Ammo.get_ammo_type!(id) |> Repo.preload(:ammo_groups)
socket = socket =
socket socket
|> assign( |> assign(
page_title: page_title(socket.assigns.live_action), page_title: page_title(socket.assigns.live_action),
ammo_type: Ammo.get_ammo_type!(id) |> Repo.preload(:ammo_groups) ammo_type: ammo_type,
avg_cost_per_round: ammo_type |> Ammo.get_average_cost_for_ammo_type!()
) )
{:noreply, socket} {:noreply, socket}

View File

@ -76,6 +76,16 @@
</span> </span>
<% end %> <% end %>
<% end %> <% end %>
<%= if @avg_cost_per_round do %>
<h3 class="mb-2 sm:mr-4 title text-lg">
Average Price paid:
</h3>
<span class="mb-4 sm:mb-2 text-primary-600">
<%= @avg_cost_per_round |> :erlang.float_to_binary(decimals: 2) %>
</span>
<% end %>
</div> </div>
<hr class="hr"> <hr class="hr">