From 69eebc82cc4c1d1f6fd518c391c72abe000c0411 Mon Sep 17 00:00:00 2001 From: shibao Date: Tue, 15 Feb 2022 21:56:01 -0500 Subject: [PATCH] calculate shot groups in average cost --- lib/cannery/ammo.ex | 3 ++- lib/cannery/ammo/ammo_group.ex | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/cannery/ammo.ex b/lib/cannery/ammo.ex index 26b03508..769e0b91 100644 --- a/lib/cannery/ammo.ex +++ b/lib/cannery/ammo.ex @@ -60,9 +60,10 @@ defmodule Cannery.Ammo do ) do Repo.one!( from ag in AmmoGroup, + left_join: sg in assoc(ag, :shot_groups), where: ag.ammo_type_id == ^ammo_type_id, where: not (ag.price_paid |> is_nil()), - select: sum(ag.price_paid) / sum(ag.count) + select: sum(ag.price_paid) / (sum(ag.count) + sum(sg.count)) ) end diff --git a/lib/cannery/ammo/ammo_group.ex b/lib/cannery/ammo/ammo_group.ex index 8b15224e..97231aed 100644 --- a/lib/cannery/ammo/ammo_group.ex +++ b/lib/cannery/ammo/ammo_group.ex @@ -9,7 +9,7 @@ defmodule Cannery.Ammo.AmmoGroup do use Ecto.Schema import Ecto.Changeset alias Cannery.Ammo.{AmmoGroup, AmmoType} - alias Cannery.{Accounts.User, Containers.Container} + alias Cannery.{Accounts.User, ActivityLog.ShotGroup, Containers.Container} alias Ecto.{Changeset, UUID} @primary_key {:id, :binary_id, autogenerate: true} @@ -24,6 +24,8 @@ defmodule Cannery.Ammo.AmmoGroup do belongs_to :container, Container belongs_to :user, User + has_many :shot_groups, ShotGroup + timestamps() end