group_members_finder.rb 1015 Bytes
Newer Older
1 2
# frozen_string_literal: true

3
class GroupMembersFinder
4 5 6 7
  def initialize(group)
    @group = group
  end

8
  # rubocop: disable CodeReuse/ActiveRecord
9
  def execute(include_descendants: false)
10
    group_members = @group.members
11
    wheres = []
12

13
    return group_members unless @group.parent || include_descendants
14

15
    wheres << "members.id IN (#{group_members.select(:id).to_sql})"
16

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    if @group.parent
      parents_members = GroupMember.non_request
        .where(source_id: @group.ancestors.select(:id))
        .where.not(user_id: @group.users.select(:id))

      wheres << "members.id IN (#{parents_members.select(:id).to_sql})"
    end

    if include_descendants
      descendant_members = GroupMember.non_request
        .where(source_id: @group.descendants.select(:id))
        .where.not(user_id: @group.users.select(:id))

      wheres << "members.id IN (#{descendant_members.select(:id).to_sql})"
    end
32 33 34

    GroupMember.where(wheres.join(' OR '))
  end
35
  # rubocop: enable CodeReuse/ActiveRecord
36
end