Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Insert revert action when reversing vote #367

Merged
merged 1 commit into from
Sep 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions apps/cf/lib/comments/comments.ex
Original file line number Diff line number Diff line change
Expand Up @@ -180,15 +180,25 @@ defmodule CF.Comments do

# Delete prev directly vote if any (without logging a delete action)
Multi.new()
|> Multi.delete_all(:prev_vote, Vote.user_comment_vote(user, comment), returning: [:value])
|> Multi.delete_all(:prev_votes, Vote.user_comment_vote(user, comment), returning: [:value])
|> Multi.run(:revert_vote, fn _repo, %{prev_votes: {_count, prev_votes}} ->
unless Enum.empty?(prev_votes) do
prev_vote = List.first(prev_votes)
prev_vote_type = Vote.vote_type(user, comment, prev_vote.value)
revert_vote_type = reverse_vote_type(prev_vote_type)
DB.Repo.insert(action_revert_vote(user.id, video_id, revert_vote_type, comment))
else
{:ok, nil}
end
end)
|> Multi.insert(:vote, Vote.changeset_new(user, comment, value))
|> Multi.insert(:vote_action, action_vote(user.id, video_id, vote_type, comment))
|> Repo.transaction()
|> case do
{:ok, %{vote: vote, prev_vote: {0, []}}} ->
{:ok, %{vote: vote, prev_votes: {0, []}}} ->
{:ok, comment, %{vote | comment_id: comment.id, comment: comment}, 0}

{:ok, %{vote: vote, prev_vote: {_, [%{value: prev_value}]}}} ->
{:ok, %{vote: vote, prev_votes: {_, [%{value: prev_value}]}}} ->
{:ok, comment, %{vote | comment_id: comment.id, comment: comment}, prev_value}

{:error, _, reason, _} ->
Expand Down
4 changes: 2 additions & 2 deletions apps/db/lib/query/query.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ defmodule DB.Query do
import Ecto.Query

@doc """
Revert sort by last_inserted
Revert sort by last_inserted. Fallsback on `id` in case there's an equality.
"""
@spec order_by_last_inserted_desc(Ecto.Queryable.t()) :: Ecto.Queryable.t()
def order_by_last_inserted_desc(query) do
order_by(query, desc: :inserted_at)
order_by(query, desc: :inserted_at, desc: :id)
end
end