fixes commission counter updates (#56)

This commit is contained in:
byte[] 2020-03-26 13:18:42 -04:00
parent 84ac9d27d7
commit bc87b287e0
2 changed files with 25 additions and 6 deletions

View file

@ -4,6 +4,7 @@ defmodule Philomena.Commissions do
"""
import Ecto.Query, warn: false
alias Ecto.Multi
alias Philomena.Repo
alias Philomena.Commissions.Commission
@ -146,9 +147,19 @@ defmodule Philomena.Commissions do
"""
def create_item(commission, attrs \\ %{}) do
changeset =
Ecto.build_assoc(commission, :items)
|> Item.changeset(attrs)
|> Repo.insert()
update =
Commission
|> where(id: ^commission.id)
|> update(inc: [commission_items_count: 1])
Multi.new()
|> Multi.insert(:item, changeset)
|> Multi.update_all(:commission, update, [])
|> Repo.isolated_transaction(:serializable)
end
@doc """
@ -182,7 +193,15 @@ defmodule Philomena.Commissions do
"""
def delete_item(%Item{} = item) do
Repo.delete(item)
update =
Commission
|> where(id: ^item.commission_id)
|> update(inc: [commission_items_count: -1])
Multi.new()
|> Multi.delete(:item, item)
|> Multi.update_all(:commission, update, [])
|> Repo.isolated_transaction(:serializable)
end
@doc """

View file

@ -40,7 +40,7 @@ defmodule PhilomenaWeb.Profile.Commission.ItemController do
commission = user.commission
case Commissions.create_item(commission, item_params) do
{:ok, _item} ->
{:ok, _multi} ->
conn
|> put_flash(:info, "Item successfully created.")
|> redirect(to: Routes.profile_commission_path(conn, :show, conn.assigns.user))
@ -92,7 +92,7 @@ defmodule PhilomenaWeb.Profile.Commission.ItemController do
commission = user.commission
item = Repo.get_by!(Item, commission_id: commission.id, id: id)
{:ok, _item} = Commissions.delete_item(item)
{:ok, _multi} = Commissions.delete_item(item)
conn
|> put_flash(:info, "Item deleted successfully.")