philomena/lib/philomena/image_votes.ex

77 lines
1.8 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
alias Philomena.ImageVotes.ImageVote
alias Philomena.UserStatistics
alias Philomena.Images.Image
2019-11-17 00:42:41 +01:00
@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
2020-01-11 05:20:19 +01:00
upvotes = if up, do: 1, else: 0
2019-11-17 03:20:33 +01:00
downvotes = if up, do: 0, else: 1
2019-11-17 00:42:41 +01:00
2020-01-11 05:20:19 +01:00
Multi.new()
2019-11-17 03:20:33 +01:00
|> Multi.insert(:vote, vote)
2020-01-11 05:20:19 +01:00
|> Multi.update_all(:inc_vote_count, image_query,
inc: [upvotes_count: upvotes, downvotes_count: downvotes, score: upvotes - downvotes]
)
|> Multi.run(:inc_vote_stat, fn _repo, _changes ->
UserStatistics.inc_stat(user, :votes_cast, 1)
end)
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)
2020-01-11 05:20:19 +01:00
Multi.new()
2019-11-17 03:20:33 +01:00
|> Multi.delete_all(:unupvote, upvote_query)
|> Multi.delete_all(:undownvote, downvote_query)
2020-01-11 05:20:19 +01:00
|> Multi.run(:dec_votes_count, fn repo,
%{unupvote: {upvotes, nil}, undownvote: {downvotes, nil}} ->
2019-11-17 03:20:33 +01:00
{count, nil} =
image_query
2020-01-11 05:20:19 +01:00
|> repo.update_all(
inc: [upvotes_count: -upvotes, downvotes_count: -downvotes, score: downvotes - upvotes]
)
2019-11-17 03:20:33 +01:00
UserStatistics.inc_stat(user, :votes_cast, -(upvotes + downvotes))
2019-11-17 03:20:33 +01:00
{:ok, count}
end)
2019-11-17 00:42:41 +01:00
end
end