summaryrefslogtreecommitdiff
path: root/app/finders/events_finder.rb
blob: 8676925a540d21e1b72f9235ef363f9e8586bced (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
class EventsFinder
  prepend FinderMethods
  prepend FinderWithCrossProjectAccess
  attr_reader :source, :params, :current_user

  requires_cross_project_access unless: -> { source.is_a?(Project) }

  # Used to filter Events
  #
  # Arguments:
  #   source - which user or project to looks for events on
  #   current_user - only return events for projects visible to this user
  #   params:
  #     action: string
  #     target_type: string
  #     before: datetime
  #     after: datetime
  #
  def initialize(params = {})
    @source = params.delete(:source)
    @current_user = params.delete(:current_user)
    @params = params
  end

  def execute
    events = source.events

    events = by_current_user_access(events)
    events = by_action(events)
    events = by_target_type(events)
    events = by_created_at_before(events)
    events = by_created_at_after(events)

    events
  end

  private

  def by_current_user_access(events)
    events.merge(ProjectsFinder.new(current_user: current_user).execute)
      .joins(:project)
  end

  def by_action(events)
    return events unless Event::ACTIONS[params[:action]]

    events.where(action: Event::ACTIONS[params[:action]])
  end

  def by_target_type(events)
    return events unless Event::TARGET_TYPES[params[:target_type]]

    events.where(target_type: Event::TARGET_TYPES[params[:target_type]])
  end

  def by_created_at_before(events)
    return events unless params[:before]

    events.where('events.created_at < ?', params[:before].beginning_of_day)
  end

  def by_created_at_after(events)
    return events unless params[:after]

    events.where('events.created_at > ?', params[:after].end_of_day)
  end
end