request_params.rb 2.14 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
# frozen_string_literal: true

module Gitlab
  module Analytics
    module CycleAnalytics
      class RequestParams
        include ActiveModel::Model
        include ActiveModel::Validations
        include ActiveModel::Attributes

11
        MAX_RANGE_DAYS = 180.days.freeze
12
        DEFAULT_DATE_RANGE = 30.days
13

14 15
        attr_writer :project_ids

16 17 18
        attribute :created_after, :date
        attribute :created_before, :date

19 20
        attr_accessor :group

21 22 23 24
        validates :created_after, presence: true
        validates :created_before, presence: true

        validate :validate_created_before
25
        validate :validate_date_range
26

27 28 29 30 31 32 33
        def initialize(params = {})
          params[:created_before] ||= Date.today.at_end_of_day
          params[:created_after] ||= default_created_after(params[:created_before])

          super(params)
        end

34 35 36 37
        def project_ids
          Array(@project_ids)
        end

38 39 40 41 42 43 44 45 46
        def to_data_attributes
          {}.tap do |attrs|
            attrs[:group] = group_data_attributes if group
            attrs[:project_ids] = project_ids if project_ids.any?
            attrs[:created_after] = created_after.iso8601
            attrs[:created_before] = created_before.iso8601
          end
        end

47 48
        private

49 50 51 52 53 54 55 56
        def group_data_attributes
          {
            id: group.id,
            name: group.name,
            full_path: group.full_path
          }
        end

57 58 59 60 61
        def validate_created_before
          return if created_after.nil? || created_before.nil?

          errors.add(:created_before, :invalid) if created_after > created_before
        end
62 63 64 65 66 67 68 69

        def validate_date_range
          return if created_after.nil? || created_before.nil?

          if (created_before - created_after).days > MAX_RANGE_DAYS
            errors.add(:created_after, s_('CycleAnalytics|The given date range is larger than 180 days'))
          end
        end
70 71 72 73 74 75 76 77

        def default_created_after(start_date = nil)
          if start_date
            (start_date.to_time - DEFAULT_DATE_RANGE).to_datetime
          else
            DEFAULT_DATE_RANGE.ago.utc.beginning_of_day
          end
        end
78 79 80 81
      end
    end
  end
end