diff options
Diffstat (limited to 'app/models/concerns/time_trackable.rb')
-rw-r--r-- | app/models/concerns/time_trackable.rb | 32 |
1 files changed, 23 insertions, 9 deletions
diff --git a/app/models/concerns/time_trackable.rb b/app/models/concerns/time_trackable.rb index 6fa2af4e4e6..040e3a2884e 100644 --- a/app/models/concerns/time_trackable.rb +++ b/app/models/concerns/time_trackable.rb @@ -9,27 +9,32 @@ module TimeTrackable extend ActiveSupport::Concern included do - attr_reader :time_spent + attr_reader :time_spent, :time_spent_user alias_method :time_spent?, :time_spent default_value_for :time_estimate, value: 0, allows_nil: false + validates :time_estimate, numericality: { message: 'has an invalid format' }, allow_nil: false + validate :check_negative_time_spent + has_many :timelogs, as: :trackable, dependent: :destroy end - def spend_time(seconds, user) - return if seconds == 0 + def spend_time(options) + @time_spent = options[:duration] + @time_spent_user = options[:user] + @original_total_time_spent = nil - @time_spent = seconds - @time_spent_user = user + return if @time_spent == 0 - if seconds == :reset + if @time_spent == :reset reset_spent_time else add_or_subtract_spent_time end end + alias_method :spend_time=, :spend_time def total_time_spent timelogs.sum(:time_spent) @@ -50,9 +55,18 @@ module TimeTrackable end def add_or_subtract_spent_time - # Exit if time to subtract exceeds the total time spent. - return if time_spent < 0 && (time_spent.abs > total_time_spent) - timelogs.new(time_spent: time_spent, user: @time_spent_user) end + + def check_negative_time_spent + return if time_spent.nil? || time_spent == :reset + + # we need to cache the total time spent so multiple calls to #valid? + # doesn't give a false error + @original_total_time_spent ||= total_time_spent + + if time_spent < 0 && (time_spent.abs > @original_total_time_spent) + errors.add(:time_spent, 'Time to subtract exceeds the total time spent') + end + end end |