summaryrefslogtreecommitdiff
path: root/app/finders/labels_finder.rb
blob: 6ace14a4bb5d934b1ec96134a419bef66908867c (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class LabelsFinder < UnionFinder
  def initialize(current_user, params = {})
    @current_user = current_user
    @params = params
  end

  def execute(authorized_only: true)
    @authorized_only = authorized_only

    items = find_union(label_ids, Label)
    items = with_title(items)
    sort(items)
  end

  private

  attr_reader :current_user, :params, :authorized_only

  def label_ids
    label_ids = []

    if project
      label_ids << project.group.labels if project.group.present?
      label_ids << project.labels
    else
      label_ids << Label.where(group_id: projects.group_ids)
      label_ids << Label.where(project_id: projects.select(:id))
    end

    label_ids
  end

  def sort(items)
    items.reorder(title: :asc)
  end

  def with_title(items)
    items = items.where(title: title) if title
    items
  end

  def group_id
    params[:group_id].presence
  end

  def project_id
    params[:project_id].presence
  end

  def projects_ids
    params[:project_ids].presence
  end

  def title
    params[:title].presence || params[:name].presence
  end

  def project
    return @project if defined?(@project)

    if project_id
      @project = find_project
    else
      @project = nil
    end

    @project
  end

  def find_project
    if authorized_only
      available_projects.find_by(id: project_id)
    else
      Project.find_by(id: project_id)
    end
  end

  def projects
    return @projects if defined?(@projects)

    @projects = authorized_only ? available_projects : Project.all
    @projects = @projects.in_namespace(group_id) if group_id
    @projects = @projects.where(id: projects_ids) if projects_ids
    @projects = @projects.reorder(nil)

    @projects
  end

  def available_projects
    @available_projects ||= ProjectsFinder.new.execute(current_user)
  end
end