From c8945607eaeb1735d70314cc12ee57f223753aa6 Mon Sep 17 00:00:00 2001 From: shibao Date: Sun, 6 Feb 2022 00:40:01 -0500 Subject: [PATCH] show average cost per round for ammo types --- lib/cannery/ammo.ex | 24 +++++++++++++++++++ lib/cannery_web/live/ammo_type_live/show.ex | 5 +++- .../live/ammo_type_live/show.html.heex | 16 ++++++++++--- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/lib/cannery/ammo.ex b/lib/cannery/ammo.ex index ab3858ca..1727ef84 100644 --- a/lib/cannery/ammo.ex +++ b/lib/cannery/ammo.ex @@ -37,6 +37,30 @@ defmodule Cannery.Ammo do @spec get_ammo_type!(AmmoType.id()) :: AmmoType.t() 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 """ Creates a ammo_type. diff --git a/lib/cannery_web/live/ammo_type_live/show.ex b/lib/cannery_web/live/ammo_type_live/show.ex index 77e23125..f69a6061 100644 --- a/lib/cannery_web/live/ammo_type_live/show.ex +++ b/lib/cannery_web/live/ammo_type_live/show.ex @@ -14,11 +14,14 @@ defmodule CanneryWeb.AmmoTypeLive.Show do @impl true def handle_params(%{"id" => id}, _, socket) do + ammo_type = Ammo.get_ammo_type!(id) |> Repo.preload(:ammo_groups) + socket = socket |> assign( 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} 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 eb39ca40..353aa552 100644 --- a/lib/cannery_web/live/ammo_type_live/show.html.heex +++ b/lib/cannery_web/live/ammo_type_live/show.html.heex @@ -40,7 +40,7 @@ ] do %> <%= if @ammo_type |> Map.get(field) do %>

- <%= field |> humanize() %> : + <%= field |> humanize() %>:

@@ -57,7 +57,7 @@ :corrosive ] do %>

- <%= field |> humanize() %> : + <%= field |> humanize() %>:

@@ -68,7 +68,7 @@ <%= for field <- [:manufacturer, :sku] do %> <%= if @ammo_type |> Map.get(field) do %>

- <%= field |> humanize() %> : + <%= field |> humanize() %>:

@@ -76,6 +76,16 @@ <% end %> <% end %> + + <%= if @avg_cost_per_round do %> +

+ Average Price paid: +

+ + + <%= @avg_cost_per_round |> :erlang.float_to_binary(decimals: 2) %> + + <% end %>