From 78f53d5d5a370c08b1b4f65450224d4505cf7b22 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 07:06:08 -0400 Subject: [PATCH] Running timers page with view/stop permissions - New top-menu page listing running timers: owner, issue, project, activity, start time, time on this run and entry total, oldest first; refreshes every minute - Role permissions "View running timers" and "Stop other users' timers", checked against each timer's project; users can always stop their own - A timer can be stopped at an earlier time (when the person left): hours logged after it are taken off the entry, and the comment notes who stopped it and when - Timers now record when they were started (session_started_at); timers running from before show "unknown" until restarted - Integration tests for permissions, project scoping and stopping; unit tests for Timer#stop_for Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM --- README.md | 5 ++ .../stopwatch_running_timers_controller.rb | 49 ++++++++++ .../stopwatch_running_timers/index.html.erb | 77 ++++++++++++++++ assets/stylesheets/stopwatch.css | 17 +++- config/locales/en.yml | 19 ++++ config/routes.rb | 3 + init.rb | 10 +++ lib/stopwatch/running_timers.rb | 48 ++++++++++ lib/stopwatch/timer.rb | 50 +++++++++++ test/integration/running_timers_test.rb | 90 +++++++++++++++++++ test/unit/timer_test.rb | 32 +++++++ 11 files changed, 399 insertions(+), 1 deletion(-) create mode 100644 app/controllers/stopwatch_running_timers_controller.rb create mode 100644 app/views/stopwatch_running_timers/index.html.erb create mode 100644 lib/stopwatch/running_timers.rb create mode 100644 test/integration/running_timers_test.rb diff --git a/README.md b/README.md index d165aa5..e0e4032 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,11 @@ Rick Barrette (2026): - Issue timers require an issue the user can see; starting twice moves the timer instead of erroring. - Tests run against Redmine 7.0. +- **Running timers page (October 2026):** a top-menu page listing everyone's running timers, with + owner, issue, project, activity, start time, how long it has run and the entry total, oldest first. + Two role permissions: *View running timers* and *Stop other users' timers*, applied per project. + A forgotten timer can be stopped at the time the person actually left; hours logged after that + are taken off the entry, and the entry's comment notes who stopped it. ## Installation diff --git a/app/controllers/stopwatch_running_timers_controller.rb b/app/controllers/stopwatch_running_timers_controller.rb new file mode 100644 index 0000000..108c278 --- /dev/null +++ b/app/controllers/stopwatch_running_timers_controller.rb @@ -0,0 +1,49 @@ +# Lists everyone's running timers, and lets managers stop a timer someone forgot (optionally at the +# time they actually stopped working). +class StopwatchRunningTimersController < StopwatchController + before_action :authorize_view + + def index + @rows = Stopwatch::RunningTimers.visible_to(User.current) + end + + def stop + owner = User.find_by(id: params[:user_id]) + return render_404 unless owner + + timer = Stopwatch::Timer.new(owner) + unless timer.running? + flash[:warning] = l(:notice_stopwatch_timer_not_running, name: owner.name) + return redirect_to stopwatch_running_timers_path + end + + row = Stopwatch::RunningTimers::Row.new(user: owner, timer: timer, time_entry: timer.time_entry) + return deny_access unless row.stoppable_by?(User.current) + + stop_at = nil + if params[:stopped_at].present? + stop_at = parse_user_time(params[:stopped_at]) + unless stop_at + flash[:error] = l(:error_stopwatch_invalid_stop_time) + return redirect_to stopwatch_running_timers_path + end + end + + hours = timer.stop_for(at: stop_at, by: User.current) + flash[:notice] = l(:notice_stopwatch_timer_stopped_for, name: owner.name, hours: format_hours(hours.to_f)) + redirect_to stopwatch_running_timers_path + end + + private + + def authorize_view + User.current.allowed_to?(:view_running_timers, nil, global: true) or deny_access + end + + # The "stopped at" field is a local date and time in the viewer's time zone + def parse_user_time(value) + (User.current.time_zone || Time.zone).parse(value.to_s) + rescue ArgumentError + nil + end +end diff --git a/app/views/stopwatch_running_timers/index.html.erb b/app/views/stopwatch_running_timers/index.html.erb new file mode 100644 index 0000000..b0c528f --- /dev/null +++ b/app/views/stopwatch_running_timers/index.html.erb @@ -0,0 +1,77 @@ +
+ <%= link_to sprite_icon(:reload, l(:label_stopwatch_refresh)), stopwatch_running_timers_path, class: 'icon icon-reload' %> +
+ +

<%= l(:label_stopwatch_running_timers) %>

+ +<% if @rows.empty? %> +

<%= l(:label_stopwatch_no_running_timers) %>

+<% else %> +
+ + + + + + + + + + + + + + + <% @rows.each do |row| %> + <% entry = row.time_entry %> + + + + + + + + + + + <% end %> + +
<%= l(:field_user) %><%= l(:field_issue) %><%= l(:field_project) %><%= l(:field_activity) %><%= l(:label_stopwatch_started_at) %><%= l(:label_stopwatch_running_for) %><%= l(:label_stopwatch_entry_total) %>
<%= avatar(row.user, size: 16) %> <%= link_to_user row.user %> + <% if row.issue %> + <%= row.issue.visible? ? link_to_issue(row.issue, truncate: 60) : "##{row.issue.id}" %> + <% end %> + <%= link_to_project(row.project) if row.project %><%= entry&.activity %> + <%= row.started_at ? format_time(row.started_at) : content_tag(:span, l(:label_stopwatch_unknown_start), class: 'stopwatch-unknown', title: l(:text_stopwatch_unknown_start)) %> + <%= html_hours(format_hours(row.timer.session_hours)) %><%= html_hours(format_hours(row.timer.time_spent)) %> + <% if row.stoppable_by?(User.current) %> + <%= form_tag stop_stopwatch_running_timer_path(row.user), method: :post, class: 'stopwatch-stop-form', + data: { confirm: l(:text_stopwatch_confirm_stop, name: row.user.name) } do %> + <% if row.started_at %> + <%# Optional: when the person actually stopped working; blank = now %> + <%= datetime_local_field_tag :stopped_at, nil, + min: row.started_at.in_time_zone(User.current.time_zone || Time.zone).strftime('%Y-%m-%dT%H:%M'), + max: Time.now.in_time_zone(User.current.time_zone || Time.zone).strftime('%Y-%m-%dT%H:%M'), + title: l(:text_stopwatch_stopped_at), 'aria-label': l(:label_stopwatch_stopped_at), + id: "stopped_at_#{row.user.id}" %> + <% end %> + <%= submit_tag l(:label_stopwatch_stop_timer), name: nil, class: 'small' %> + <% end %> + <% end %> +
+
+

<%= l(:text_stopwatch_running_timers_help) %>

+<% end %> + +<%= javascript_tag do %> + // Refresh every minute, unless someone is filling in a stop time + (function () { + setInterval(function () { + var busy = Array.prototype.some.call(document.querySelectorAll('.stopwatch-stop-form input[name="stopped_at"]'), function (el) { + return el.value !== '' || el === document.activeElement; + }); + if (!busy) window.location.reload(); + }, 60000); + })(); +<% end %> + +<% html_title(l(:label_stopwatch_running_timers)) -%> diff --git a/assets/stylesheets/stopwatch.css b/assets/stylesheets/stopwatch.css index 00508e5..45f888a 100644 --- a/assets/stylesheets/stopwatch.css +++ b/assets/stylesheets/stopwatch.css @@ -1,3 +1,18 @@ tr.time-entry.running td.hours { color: red; -} \ No newline at end of file +} +/* Running timers page */ +table.stopwatch-running-timers td.hours.running { + color: red; + font-weight: bold; +} +table.stopwatch-running-timers .stopwatch-stop-form { + display: inline-flex; + gap: 4px; + align-items: center; + margin: 0; +} +.stopwatch-unknown { + color: #888; + cursor: help; +} diff --git a/config/locales/en.yml b/config/locales/en.yml index 50f36d4..c3f48e5 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -1,6 +1,25 @@ en: label_stopwatch_start: Start tracking label_stopwatch_stop: Stop tracking + label_stopwatch_running_timers: Running timers + label_stopwatch_no_running_timers: No timers are running. + label_stopwatch_refresh: Refresh + label_stopwatch_started_at: Started + label_stopwatch_running_for: Running for + label_stopwatch_entry_total: Entry total + label_stopwatch_stop_timer: Stop + label_stopwatch_stopped_at: Stopped at + label_stopwatch_unknown_start: unknown + text_stopwatch_unknown_start: "Started before start times were recorded; it will show once the timer is restarted" + text_stopwatch_stopped_at: "Optional: when they actually stopped working. Hours logged after this time are taken off the entry. Leave blank to stop now." + text_stopwatch_confirm_stop: "Stop %{name}'s timer?" + text_stopwatch_running_timers_help: "Oldest first. To stop a forgotten timer at the time the person left, fill in \"Stopped at\" before pressing Stop; otherwise it stops now." + text_stopwatch_timer_stopped_by: "[Timer stopped by %{name}, at %{time}]" + notice_stopwatch_timer_stopped_for: "Stopped %{name}'s timer (%{hours} on this run)." + notice_stopwatch_timer_not_running: "%{name}'s timer was no longer running." + error_stopwatch_invalid_stop_time: "That stop time couldn't be read. Please pick a date and time." + permission_view_running_timers: View running timers + permission_stop_running_timers: Stop other users' timers text_stopwatch_timer_capped: "[Timer stopped automatically at the %{hours} hour limit - please check these hours]" stopwatch: settings: diff --git a/config/routes.rb b/config/routes.rb index d6f8566..e46a7ce 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -9,6 +9,9 @@ resources :stopwatch_timers, only: %i(new create edit update) do end end +get 'stopwatch/running_timers', to: 'stopwatch_running_timers#index', as: :stopwatch_running_timers +post 'stopwatch/running_timers/:user_id/stop', to: 'stopwatch_running_timers#stop', as: :stop_stopwatch_running_timer + scope 'issues/:issue_id' do post 'timer/start', to: 'stopwatch_issue_timers#start', as: :start_issue_timer post 'timer/stop', to: 'stopwatch_issue_timers#stop', as: :stop_issue_timer diff --git a/init.rb b/init.rb index 829f9a7..6b23fbb 100644 --- a/init.rb +++ b/init.rb @@ -12,6 +12,16 @@ Redmine::Plugin.register :stopwatch do 'max_timer_hours' => '10', }, partial: 'stopwatch/settings' + # Running timers page: see everyone's running timers, and stop one someone forgot. Both are role + # permissions, so they apply to timers on time entries in the projects where the role has them. + permission :view_running_timers, { stopwatch_running_timers: [:index] } + permission :stop_running_timers, { stopwatch_running_timers: [:stop] } + + menu :top_menu, :stopwatch_running_timers, + { controller: 'stopwatch_running_timers', action: 'index' }, + caption: :label_stopwatch_running_timers, + if: ->(*_){ User.current.allowed_to?(:view_running_timers, nil, global: true) } + menu :account_menu, :stopwatch, :new_stopwatch_timer_path, caption: :button_log_time, diff --git a/lib/stopwatch/running_timers.rb b/lib/stopwatch/running_timers.rb new file mode 100644 index 0000000..869bbf8 --- /dev/null +++ b/lib/stopwatch/running_timers.rb @@ -0,0 +1,48 @@ +module Stopwatch + # Everyone's running timers, for the running timers page. + class RunningTimers + Row = Struct.new(:user, :timer, :time_entry, keyword_init: true) do + def project + time_entry&.project + end + + def issue + time_entry&.issue + end + + def started_at + timer.session_started_at + end + + # Whether viewer may stop this timer: their own, or with "Stop running timers" in its project + def stoppable_by?(viewer) + return true if user == viewer + return viewer.admin? if project.nil? + + viewer.allowed_to?(:stop_running_timers, project) + end + end + + # Running timers the viewer may see: their own, plus timers on entries in projects where they have + # "View running timers". Oldest first, so forgotten timers are at the top. + def self.visible_to(viewer) + all.select do |row| + row.user == viewer || + (row.project ? viewer.allowed_to?(:view_running_timers, row.project) : viewer.admin?) + end + end + + def self.all + # Timers live in each user's preferences; only rows mentioning a timer are loaded + UserPreference.where('others LIKE ?', '%current_timer%').includes(:user).filter_map do |pref| + user = pref.user + next unless user + + timer = Timer.new(user) + next unless timer.running? + + Row.new(user: user, timer: timer, time_entry: timer.time_entry) + end.sort_by { |row| [row.started_at ? 0 : 1, row.started_at.to_i, row.user.name] } + end + end +end diff --git a/lib/stopwatch/timer.rb b/lib/stopwatch/timer.rb index 55ea241..dcadf1e 100644 --- a/lib/stopwatch/timer.rb +++ b/lib/stopwatch/timer.rb @@ -7,6 +7,7 @@ module Stopwatch # time_entry_id - the time entry the timer adds to # session_hours - hours already added since the timer was started, for the maximum timer length # tick_token - identifies this start's chain of server-side saves (StopwatchTimerTickJob) + # session_started_at - when the timer was started (started_at moves forward with every save) class Timer class HourFormatter include ApplicationHelper @@ -44,6 +45,7 @@ module Stopwatch data[:session_hours] = 0.0 data[:time_entry_id] = time_entry&.id data[:tick_token] = token + data[:session_started_at] = data[:started_at] save end # Keep saving the time on the server every minute while it runs @@ -54,6 +56,53 @@ module Stopwatch update stop: true end + # Stops the timer for someone else (e.g. a manager on the running timers page). + # at: when the timer should have stopped, e.g. when the person actually left. Hours logged after + # that are taken back off the entry. Must be between the start and now; nil means now. + # by: the user stopping it; noted in the entry's comment. + # Returns the hours this timer session ends up with, or nil if the timer wasn't running. + def stop_for(at: nil, by: nil) + locked do + return nil unless running? + + started = session_started_at + total = session_hours # before saving, so a timer at its limit is trimmed correctly too + apply_elapsed_time(stop: true) + save + + entry = time_entry # fresh copy, after the elapsed time was saved + keep = total + stopped_at = Time.now + if entry && at && started + stopped_at = Time.at(at.to_i.clamp(started.to_i, Time.now.to_i)) + keep = [(stopped_at - started).to_f / 1.hour, total].min + excess = total - keep + entry.update_columns(hours: [entry.read_attribute(:hours).to_f - excess, 0].max) if excess.positive? + end + + if entry && by && by != user + zone = user.time_zone || Time.zone + note = I18n.t(:text_stopwatch_timer_stopped_by, name: by.name, + time: stopped_at.in_time_zone(zone).strftime('%Y-%m-%d %H:%M')) + entry.update_columns(comments: [entry.comments.to_s.presence, note].compact.join(' ').truncate(1024)) + end + + Rails.logger.info "[Stopwatch] Timer for user ##{user.id} stopped by #{by ? "user ##{by.id}" : 'system'}, #{keep.round(2)}h kept" + keep + end + end + + # When this timer was started, or nil for timers started before the start time was recorded + def session_started_at + ts = data[:session_started_at] + ts.present? ? Time.at(ts.to_i) : nil + end + + # Hours this timer has run since it was started (saved plus unsaved, never beyond the limit) + def session_hours + data[:session_hours].to_f + unsaved_hours + end + # Saves the time elapsed since the last save into the time entry, then stops the timer # (stop: true) or keeps it running from now. The timer record is locked meanwhile, so two requests # at the same moment (e.g. two open tabs) can't add the same time twice. Once a timer reaches the @@ -149,6 +198,7 @@ module Stopwatch Rails.logger.info "[Stopwatch] Timer for user ##{user.id} stopped at the #{Stopwatch.max_timer_hours}h limit" if capped data[:started_at] = nil data[:session_hours] = 0.0 + data[:session_started_at] = nil else data[:started_at] = Time.now.to_i data[:session_hours] = data[:session_hours].to_f + hours diff --git a/test/integration/running_timers_test.rb b/test/integration/running_timers_test.rb new file mode 100644 index 0000000..8b6d8bc --- /dev/null +++ b/test/integration/running_timers_test.rb @@ -0,0 +1,90 @@ +require File.expand_path('../test_helper', __dir__) + +class RunningTimersTest < Redmine::IntegrationTest + fixtures :projects, :users, :email_addresses, :user_preferences, :roles, :members, :member_roles, + :trackers, :projects_trackers, :enabled_modules, :issue_statuses, :issues, + :enumerations, :time_entries + + setup do + @issue = Issue.find 1 + @manager = User.find_by_login 'jsmith' # Manager in project 1 + @worker = User.find_by_login 'dlopper' # Developer in project 1 + @entry = TimeEntry.create!(project: @issue.project, issue: @issue, user: @worker, author: @worker, + spent_on: Date.today, hours: 1, activity: TimeEntryActivity.first) + timer = Stopwatch::Timer.new(@worker) + timer.start @entry + data = timer.send(:data) + data[:started_at] = data[:session_started_at] = 3.hours.ago.to_i + timer.save + Role.find(1).remove_permission!(:view_running_timers, :stop_running_timers) + Role.find(2).remove_permission!(:view_running_timers, :stop_running_timers) + end + + def worker_timer + Stopwatch::Timer.new(User.find(@worker.id)) + end + + test "page needs the view permission" do + log_user 'jsmith', 'jsmith' + get '/stopwatch/running_timers' + assert_response 403 + end + + test "lists running timers without a stop button when the user can only view" do + Role.find(1).add_permission!(:view_running_timers) + log_user 'jsmith', 'jsmith' + get '/stopwatch/running_timers' + assert_response :success + assert_select "tr#stopwatch-running-timer-#{@worker.id} td.user", text: /#{@worker.name}/ + assert_select "tr#stopwatch-running-timer-#{@worker.id} td.started", text: /\d/ + assert_select "tr#stopwatch-running-timer-#{@worker.id} form.stopwatch-stop-form", 0 + end + + test "stopping someone else's timer needs the stop permission" do + Role.find(1).add_permission!(:view_running_timers) + log_user 'jsmith', 'jsmith' + post "/stopwatch/running_timers/#{@worker.id}/stop" + assert_response 403 + assert worker_timer.running? + end + + test "manager stops a forgotten timer at the time the person left" do + Role.find(1).add_permission!(:view_running_timers, :stop_running_timers) + log_user 'jsmith', 'jsmith' + get '/stopwatch/running_timers' + assert_select "tr#stopwatch-running-timer-#{@worker.id} form.stopwatch-stop-form" + + left_at = (2.hours.ago).in_time_zone(Time.zone).strftime('%Y-%m-%dT%H:%M') # 1 hour after starting + post "/stopwatch/running_timers/#{@worker.id}/stop", params: { stopped_at: left_at } + assert_redirected_to '/stopwatch/running_timers' + + refute worker_timer.running? + @entry.reload + assert_in_delta 2.0, @entry.hours, 0.02 # 1 hour before + 1 hour of this run + assert_includes @entry.comments, "Timer stopped by #{@manager.name}" + end + + test "stopping without a time stops now" do + Role.find(1).add_permission!(:view_running_timers, :stop_running_timers) + log_user 'jsmith', 'jsmith' + post "/stopwatch/running_timers/#{@worker.id}/stop" + refute worker_timer.running? + assert_in_delta 4.0, @entry.reload.hours, 0.02 + end + + test "users with view permission can stop their own timer" do + Role.find(2).add_permission!(:view_running_timers) + log_user 'dlopper', 'foo' + post "/stopwatch/running_timers/#{@worker.id}/stop" + refute worker_timer.running? + refute_includes @entry.reload.comments.to_s, 'Timer stopped by' + end + + test "timers in other projects are not shown" do + Role.find(1).add_permission!(:view_running_timers) + @entry.update_columns(project_id: 2, issue_id: nil) # jsmith has no view_running_timers in project 2 + log_user 'jsmith', 'jsmith' + get '/stopwatch/running_timers' + assert_select "tr#stopwatch-running-timer-#{@worker.id}", 0 + end +end diff --git a/test/unit/timer_test.rb b/test/unit/timer_test.rb index fbadd45..22c220a 100644 --- a/test/unit/timer_test.rb +++ b/test/unit/timer_test.rb @@ -168,4 +168,36 @@ class TimerTest < ActiveSupport::TestCase assert_no_enqueued_jobs assert_equal hours, @time_entry.reload.hours end + + test "stop_for trims hours logged after the chosen stop time" do + hours = @time_entry.hours + @timer.start @time_entry + data[:started_at] = data[:session_started_at] = 3.hours.ago.to_i + @timer.save + @timer.update # saves the 3 hours, as the server does every minute + + kept = @timer.stop_for(at: 2.hours.ago, by: User.find(2)) + + assert_in_delta 1.0, kept, 0.01 + assert_in_delta hours + 1, @time_entry.reload.hours, 0.01 + assert_includes @time_entry.comments, 'Timer stopped by' + refute Stopwatch::Timer.new(User.find(@user.id)).running? + end + + test "stop_for never moves the stop time outside the run" do + hours = @time_entry.hours + @timer.start @time_entry + data[:started_at] = data[:session_started_at] = 1.hour.ago.to_i + @timer.save + + @timer.stop_for(at: 1.day.from_now) # later than now: stops now + + assert_in_delta hours + 1, @time_entry.reload.hours, 0.01 + end + + test "stop_for by the owner adds no note" do + @timer.start @time_entry + @timer.stop_for(by: @user) + refute_includes @time_entry.reload.comments.to_s, 'Timer stopped by' + end end