initial commit

This commit is contained in:
Jens Kraemer
2020-04-22 18:03:56 +08:00
commit 70257cdee0
16 changed files with 331 additions and 0 deletions

3
lib/stopwatch.rb Normal file
View File

@@ -0,0 +1,3 @@
module Stopwatch
end

0
lib/stopwatch/hooks.rb Normal file
View File

View File

@@ -0,0 +1,44 @@
module Stopwatch
class StartTimer
Result = ImmutableStruct.new(:success?, :error)
def initialize(time_entry, user: User.current)
@time_entry = time_entry
@user = user
end
def call
if @time_entry.project && @user.allowed_to?(:log_time, @time_entry.project)
return Result.new(error: :unauthorized)
end
stop_existing_timer
@time_entry.hours = 0 if @time_entry.hours.nil?
if @time_entry.save
start_new_timer
return Result.new(success: true)
else
Rails.logger.error("could not save time entry: \n#{@time_entry.errors.inspect}")
return Result.new(error: :invalid)
end
end
private
def start_new_timer
timer = Timer.new @user
timer.start @time_entry
end
def stop_existing_timer
timer = Timer.new @user
if timer.running?
timer.stop
end
end
end
end

51
lib/stopwatch/timer.rb Normal file
View File

@@ -0,0 +1,51 @@
require 'json'
module Stopwatch
class Timer
attr_reader :user
def initialize(user)
@user = user
end
def running?
data[:started_at].present?
end
def start(time_entry = nil)
fail "timer is already running" if running?
data[:started_at] = Time.now.to_i
data[:time_entry_id] = time_entry.id if time_entry
save
end
def stop
if hours = runtime_hours and
time_entry = TimeEntry.find_by_id(data[:time_entry_id])
time_entry.update_column :hours, time_entry.hours + hours
end
data[:started_at] = nil
save
end
def save
user.pref[:current_timer] = data.to_json
user.pref.save
end
private
def data
@data ||= (t = user.pref[:current_timer]) ? JSON.parse(t).symbolize_keys : {}
end
def runtime_hours
if start = data[:started_at]
runtime = Time.now.to_i - start
return runtime.to_f / 1.hour
end
end
end
end

View File

@@ -0,0 +1,11 @@
module Stopwatch
module UserPatch
def self.apply
User.prepend self unless User < self
end
def timer_running?
Stopwatch::Timer.new(self).running?
end
end
end