summaryrefslogtreecommitdiff
path: root/app/services/concerns/users/participable_service.rb
blob: a3cc6014fd3a47c69badf4efd878645cfed371d9 (plain)
1
2
3
4
5
6
7
8
9
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# frozen_string_literal: true

module Users
  module ParticipableService
    extend ActiveSupport::Concern

    included do
      attr_reader :noteable
    end

    def noteable_owner
      return [] unless noteable && noteable.author.present?

      [user_as_hash(noteable.author)]
    end

    def participants_in_noteable
      return [] unless noteable

      users = noteable.participants(current_user)
      sorted(users)
    end

    def sorted(users)
      users.uniq.to_a.compact.sort_by(&:username).map do |user|
        user_as_hash(user)
      end
    end

    def groups
      group_counts = GroupMember
                       .in_groups(current_user.authorized_groups)
                       .non_request
                       .count_users_by_group_id

      current_user.authorized_groups.with_route.sort_by(&:path).map do |group|
        group_as_hash(group, group_counts)
      end
    end

    private

    def user_as_hash(user)
      {
        type: user.class.name,
        username: user.username,
        name: user.name,
        avatar_url: user.avatar_url
      }
    end

    def group_as_hash(group, group_counts)
      {
        type: group.class.name,
        username: group.full_path,
        name: group.full_name,
        avatar_url: group.avatar_url,
        count: group_counts.fetch(group.id, 0)
      }
    end
  end
end