philomena/lib/philomena/image_votes.ex

66 lines
1.5 KiB
Elixir
Raw Normal View History

2019-11-17 00:42:41 +01:00
defmodule Philomena.ImageVotes do
@moduledoc """
The ImageVotes context.
"""
import Ecto.Query, warn: false
2019-11-17 03:20:33 +01:00
alias Ecto.Multi
2019-11-17 00:42:41 +01:00
2019-11-17 03:20:33 +01:00
alias Philomena.Images.Image
2019-11-17 00:42:41 +01:00
alias Philomena.ImageVotes.ImageVote
@doc """
Creates a image_vote.
"""
2019-11-17 03:20:33 +01:00
def create_vote_transaction(image, user, up) do
vote =
%ImageVote{image_id: image.id, user_id: user.id, up: up}
|> ImageVote.changeset(%{})
2019-11-17 00:42:41 +01:00
2019-11-17 03:20:33 +01:00
image_query =
Image
|> where(id: ^image.id)
2019-11-17 00:42:41 +01:00
2019-11-17 03:20:33 +01:00
upvotes = if up, do: 1, else: 0
downvotes = if up, do: 0, else: 1
2019-11-17 00:42:41 +01:00
2019-11-17 03:20:33 +01:00
Multi.new
|> Multi.insert(:vote, vote)
|> Multi.update_all(:inc_vote_count, image_query, inc: [upvotes_count: upvotes, downvotes_count: downvotes, score: upvotes - downvotes])
2019-11-17 00:42:41 +01:00
end
@doc """
Deletes a ImageVote.
"""
2019-11-17 03:20:33 +01:00
def delete_vote_transaction(image, user) do
upvote_query =
ImageVote
|> where(image_id: ^image.id)
|> where(user_id: ^user.id)
|> where(up: true)
downvote_query =
ImageVote
|> where(image_id: ^image.id)
|> where(user_id: ^user.id)
|> where(up: false)
image_query =
Image
|> where(id: ^image.id)
Multi.new
|> Multi.delete_all(:unupvote, upvote_query)
|> Multi.delete_all(:undownvote, downvote_query)
|> Multi.run(:dec_votes_count, fn repo, %{unupvote: {upvotes, nil}, undownvote: {downvotes, nil}} ->
{count, nil} =
image_query
|> repo.update_all(inc: [upvotes_count: -upvotes, downvotes_count: -downvotes, score: downvotes - upvotes])
{:ok, count}
end)
2019-11-17 00:42:41 +01:00
end
end