milestones_finder.rb 1.46 KB
Newer Older
1 2
# frozen_string_literal: true

Felipe Artur's avatar
Felipe Artur committed
3 4 5
# Search for milestones
#
# params - Hash
6 7
#   project_ids: Array of project ids or single project id or ActiveRecord relation.
#   group_ids: Array of group ids or single group id or ActiveRecord relation.
Felipe Artur's avatar
Felipe Artur committed
8 9 10 11
#   order - Orders by field default due date asc.
#   title - filter by title.
#   state - filters by state.

12
class MilestonesFinder
13 14
  include FinderMethods

15
  attr_reader :params
Felipe Artur's avatar
Felipe Artur committed
16 17 18 19 20 21 22 23 24

  def initialize(params = {})
    @params = params
  end

  def execute
    items = Milestone.all
    items = by_groups_and_projects(items)
    items = by_title(items)
Jacopo's avatar
Jacopo committed
25
    items = by_search_title(items)
Felipe Artur's avatar
Felipe Artur committed
26 27 28 29 30 31 32 33
    items = by_state(items)

    order(items)
  end

  private

  def by_groups_and_projects(items)
34
    items.for_projects_and_groups(params[:project_ids], params[:group_ids])
Felipe Artur's avatar
Felipe Artur committed
35 36
  end

37
  # rubocop: disable CodeReuse/ActiveRecord
Felipe Artur's avatar
Felipe Artur committed
38 39 40 41 42 43 44
  def by_title(items)
    if params[:title]
      items.where(title: params[:title])
    else
      items
    end
  end
45
  # rubocop: enable CodeReuse/ActiveRecord
Felipe Artur's avatar
Felipe Artur committed
46

Jacopo's avatar
Jacopo committed
47 48 49 50 51 52 53 54
  def by_search_title(items)
    if params[:search_title].present?
      items.search_title(params[:search_title])
    else
      items
    end
  end

Felipe Artur's avatar
Felipe Artur committed
55 56 57 58
  def by_state(items)
    Milestone.filter_by_state(items, params[:state])
  end

59
  # rubocop: disable CodeReuse/ActiveRecord
Felipe Artur's avatar
Felipe Artur committed
60
  def order(items)
61 62
    order_statement = Gitlab::Database.nulls_last_order('due_date', 'ASC')
    items.reorder(order_statement).order('title ASC')
63
  end
64
  # rubocop: enable CodeReuse/ActiveRecord
65
end