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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
This commit is contained in:
Claude committed 2026-10-29 07:06:08 -04:00
1 parent 626db60658
commit 78f53d5d5a
11 files changed
+398

No files matched your search

+5
View File
@@ -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
@@ -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
@@ -0,0 +1,77 @@
<div class="contextual">
<%= link_to sprite_icon(:reload, l(:label_stopwatch_refresh)), stopwatch_running_timers_path, class: 'icon icon-reload' %>
</div>
<h2><%= l(:label_stopwatch_running_timers) %></h2>
<% if @rows.empty? %>
<p class="nodata"><%= l(:label_stopwatch_no_running_timers) %></p>
<% else %>
<div class="autoscroll">
<table class="list stopwatch-running-timers">
<thead>
<tr>
<th><%= l(:field_user) %></th>
<th><%= l(:field_issue) %></th>
<th><%= l(:field_project) %></th>
<th><%= l(:field_activity) %></th>
<th><%= l(:label_stopwatch_started_at) %></th>
<th><%= l(:label_stopwatch_running_for) %></th>
<th><%= l(:label_stopwatch_entry_total) %></th>
<th></th>
</tr>
</thead>
<tbody>
<% @rows.each do |row| %>
<% entry = row.time_entry %>
<tr class="<%= cycle('odd', 'even') %>" id="stopwatch-running-timer-<%= row.user.id %>">
<td class="user"><%= avatar(row.user, size: 16) %> <%= link_to_user row.user %></td>
<td class="issue">
<% if row.issue %>
<%= row.issue.visible? ? link_to_issue(row.issue, truncate: 60) : "##{row.issue.id}" %>
<% end %>
</td>
<td class="project"><%= link_to_project(row.project) if row.project %></td>
<td class="activity"><%= entry&.activity %></td>
<td class="started">
<%= 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)) %>
</td>
<td class="hours running"><%= html_hours(format_hours(row.timer.session_hours)) %></td>
<td class="hours"><%= html_hours(format_hours(row.timer.time_spent)) %></td>
<td class="buttons">
<% 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 %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
<p class="stopwatch-running-timers-help"><em class="info"><%= l(:text_stopwatch_running_timers_help) %></em></p>
<% 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)) -%>
+15
View File
@@ -1,3 +1,18 @@
tr.time-entry.running td.hours {
color: red;
}
/* 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;
}
+19
View File
@@ -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:
+3
View File
@@ -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
+10
View File
@@ -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,
+48
View File
@@ -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
+50
View File
@@ -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
+90
View File
@@ -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
+32
View File
@@ -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