BigW Consortium Gitlab

todos_finder.rb 2.34 KB
Newer Older
1
# TodosFinder
2
#
3
# Used to filter Todos by set of params
4 5 6 7 8 9 10 11 12 13 14
#
# Arguments:
#   current_user - which user use
#   params:
#     action_id: integer
#     author_id: integer
#     project_id; integer
#     state: 'pending' or 'done'
#     type: 'Issue' or 'MergeRequest'
#

15
class TodosFinder
16 17 18 19 20 21 22 23 24 25
  NONE = '0'

  attr_accessor :current_user, :params

  def initialize(current_user, params)
    @current_user = current_user
    @params = params
  end

  def execute
26
    items = current_user.todos
27 28 29 30 31 32
    items = by_action_id(items)
    items = by_author(items)
    items = by_project(items)
    items = by_state(items)
    items = by_type(items)

33
    items.reorder(id: :desc)
34 35 36 37 38
  end

  private

  def action_id?
39
    action_id.present? && [Todo::ASSIGNED, Todo::MENTIONED, Todo::BUILD_FAILED].include?(action_id.to_i)
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
  end

  def action_id
    params[:action_id]
  end

  def author?
    params[:author_id].present?
  end

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

    @author =
      if author? && params[:author_id] != NONE
        User.find(params[:author_id])
      else
        nil
      end
  end

  def project?
    params[:project_id].present?
  end

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

    if project?
      @project = Project.find(params[:project_id])

      unless Ability.abilities.allowed?(current_user, :read_project, @project)
        @project = nil
      end
    else
      @project = nil
    end

    @project
  end

81 82 83 84 85 86
  def projects
    return @projects if defined?(@projects)

    if project?
      @projects = project
    else
87
      @projects = ProjectsFinder.new.execute(current_user)
88 89 90
    end
  end

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  def type?
    type.present? && ['Issue', 'MergeRequest'].include?(type)
  end

  def type
    params[:type]
  end

  def by_action_id(items)
    if action_id?
      items = items.where(action: action_id)
    end

    items
  end

  def by_author(items)
    if author?
      items = items.where(author_id: author.try(:id))
    end

    items
  end

  def by_project(items)
    if project?
      items = items.where(project: project)
118 119
    elsif projects
      items = items.merge(projects).joins(:project)
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    end

    items
  end

  def by_state(items)
    case params[:state]
    when 'done'
      items.done
    else
      items.pending
    end
  end

  def by_type(items)
    if type?
      items = items.where(target_type: type)
    end

    items
  end
end