BigW Consortium Gitlab

time_trackable.rb 2.16 KB
Newer Older
1 2 3 4 5 6
# == TimeTrackable concern
#
# Contains functionality related to objects that support time tracking.
#
# Used by Issue and MergeRequest.
#
Lin Jen-Shin committed
7

8 9 10 11
module TimeTrackable
  extend ActiveSupport::Concern

  included do
12
    attr_reader :time_spent, :time_spent_user, :spent_at
13 14 15 16 17

    alias_method :time_spent?, :time_spent

    default_value_for :time_estimate, value: 0, allows_nil: false

18 19 20
    validates :time_estimate, numericality: { message: 'has an invalid format' }, allow_nil: false
    validate  :check_negative_time_spent

21
    has_many :timelogs, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
22 23
  end

24
  # rubocop:disable Gitlab/ModuleWithInstanceVariables
25 26
  def spend_time(options)
    @time_spent = options[:duration]
27
    @time_spent_user = User.find(options[:user_id])
28
    @spent_at = options[:spent_at]
29
    @original_total_time_spent = nil
30

31
    return if @time_spent == 0
32

33
    if @time_spent == :reset
34 35 36 37 38
      reset_spent_time
    else
      add_or_subtract_spent_time
    end
  end
39
  alias_method :spend_time=, :spend_time
40
  # rubocop:enable Gitlab/ModuleWithInstanceVariables
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

  def total_time_spent
    timelogs.sum(:time_spent)
  end

  def human_total_time_spent
    Gitlab::TimeTrackingFormatter.output(total_time_spent)
  end

  def human_time_estimate
    Gitlab::TimeTrackingFormatter.output(time_estimate)
  end

  private

  def reset_spent_time
57
    timelogs.new(time_spent: total_time_spent * -1, user: @time_spent_user) # rubocop:disable Gitlab/ModuleWithInstanceVariables
58 59
  end

60
  # rubocop:disable Gitlab/ModuleWithInstanceVariables
61
  def add_or_subtract_spent_time
62 63 64 65 66
    timelogs.new(
      time_spent: time_spent,
      user: @time_spent_user,
      spent_at: @spent_at
    )
67
  end
68
  # rubocop:enable Gitlab/ModuleWithInstanceVariables
69 70 71 72

  def check_negative_time_spent
    return if time_spent.nil? || time_spent == :reset

73
    if time_spent < 0 && (time_spent.abs > original_total_time_spent)
74 75 76
      errors.add(:time_spent, 'Time to subtract exceeds the total time spent')
    end
  end
77 78 79 80 81 82

  # we need to cache the total time spent so multiple calls to #valid?
  # doesn't give a false error
  def original_total_time_spent
    @original_total_time_spent ||= total_time_spent
  end
83
end