Skip to content

Commit

Permalink
close commissions if they get edited to have fewer proposals/slots th…
Browse files Browse the repository at this point in the history
…an are currently used

Fixes: #575
  • Loading branch information
zkat committed Aug 13, 2023
1 parent bd059f1 commit 053221b
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion lib/banchan/offerings/offerings.ex
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ defmodule Banchan.Offerings do
with {:ok, _actor} <- Studios.check_studio_member(%Studio{id: offering.studio_id}, actor) do
offering = Repo.reload(offering) |> Repo.preload([:options, :gallery_imgs])

open_before? = Repo.one(from o in Offering, where: o.id == ^offering.id, select: o.open)
open_before? = Repo.one(from(o in Offering, where: o.id == ^offering.id, select: o.open))
proposal_count = offering_proposal_count(offering)
used_slots = offering_used_slots(offering, true)

changeset =
offering
Expand All @@ -105,6 +107,18 @@ defmodule Banchan.Offerings do
changeset |> Ecto.Changeset.put_assoc(:gallery_imgs, gallery_images)
end

slots = Ecto.Changeset.get_field(changeset, :slots)
max_proposals = Ecto.Changeset.get_field(changeset, :max_proposals)

changeset =
if (!is_nil(slots) && slots < used_slots) ||
(!is_nil(max_proposals) && max_proposals < proposal_count) do
changeset
|> Ecto.Changeset.put_change(:open, false)
else
changeset
end

old_uploads = offering.gallery_imgs |> Enum.map(& &1.upload_id)

new_uploads =
Expand Down Expand Up @@ -402,6 +416,32 @@ defmodule Banchan.Offerings do
|> Repo.one!()
end

def offering_used_slots(%Offering{} = offering, reload \\ false) do
if reload do
from(c in Commission,
where:
c.offering_id == ^offering.id and
c.status not in [:withdrawn, :approved, :submitted, :rejected],
group_by: [c.offering_id],
select: count(c.id)
)
|> Repo.one()
else
offering.used_slots
end
end

def offering_proposal_count(%Offering{} = offering) do
from(c in Commission,
where:
c.offering_id == ^offering.id and
c.status == :submitted,
group_by: [c.offering_id],
select: count(c.id)
)
|> Repo.one()
end

@doc """
Calculates the offering's available slots. If `reload` is false, this
assumes the offering has been loaded through `list_offerings/1`, which
Expand Down

0 comments on commit 053221b

Please sign in to comment.