BigW Consortium Gitlab

awardable.rb 2.51 KB
Newer Older
1 2 3 4
module Awardable
  extend ActiveSupport::Concern

  included do
5
    has_many :award_emoji, -> { includes(:user).order(:id) }, as: :awardable, dependent: :destroy
6 7

    if self < Participable
8 9
      # By default we always load award_emoji user association
      participant :award_emoji
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
    end
  end

  module ClassMethods
    def order_upvotes_desc
      order_votes_desc(AwardEmoji::UPVOTE_NAME)
    end

    def order_downvotes_desc
      order_votes_desc(AwardEmoji::DOWNVOTE_NAME)
    end

    def order_votes_desc(emoji_name)
      awardable_table = self.arel_table
      awards_table = AwardEmoji.arel_table

      join_clause = awardable_table.join(awards_table, Arel::Nodes::OuterJoin).on(
        awards_table[:awardable_id].eq(awardable_table[:id]).and(
          awards_table[:awardable_type].eq(self.name).and(
            awards_table[:name].eq(emoji_name)
          )
        )
      ).join_sources

      joins(join_clause).group(awardable_table[:id]).reorder("COUNT(award_emoji.id) DESC")
    end
  end

38
  def grouped_awards(with_thumbs: true)
39 40
    # By default we always load award_emoji user association
    awards = award_emoji.group_by(&:name)
41 42

    if with_thumbs
43 44
      awards[AwardEmoji::UPVOTE_NAME]   ||= []
      awards[AwardEmoji::DOWNVOTE_NAME] ||= []
45 46 47 48 49 50
    end

    awards
  end

  def downvotes
51
    award_emoji.downvotes.count
52 53 54
  end

  def upvotes
55
    award_emoji.upvotes.count
56 57 58 59 60 61
  end

  def emoji_awardable?
    true
  end

62 63 64 65 66
  def awardable_votes?(name)
    AwardEmoji::UPVOTE_NAME == name || AwardEmoji::DOWNVOTE_NAME == name
  end

  def user_can_award?(current_user, name)
67 68 69 70 71
    if user_authored?(current_user)
      !awardable_votes?(normalize_name(name))
    else
      true
    end
72 73
  end

74 75 76 77 78 79
  def user_authored?(current_user)
    author = self.respond_to?(:author) ? self.author : self.user

    author == current_user
  end

80 81 82 83 84 85
  def awarded_emoji?(emoji_name, current_user)
    award_emoji.where(name: emoji_name, user: current_user).exists?
  end

  def create_award_emoji(name, current_user)
    return unless emoji_awardable?
86
    award_emoji.create(name: normalize_name(name), user: current_user)
87 88 89 90 91 92 93 94 95 96 97 98 99
  end

  def remove_award_emoji(name, current_user)
    award_emoji.where(name: name, user: current_user).destroy_all
  end

  def toggle_award_emoji(emoji_name, current_user)
    if awarded_emoji?(emoji_name, current_user)
      remove_award_emoji(emoji_name, current_user)
    else
      create_award_emoji(emoji_name, current_user)
    end
  end
100 101 102 103 104 105

  private

  def normalize_name(name)
    Gitlab::AwardEmoji.normalize_emoji_name(name)
  end
106
end