Calendar review fixes; working day hours setting

- Issues' estimated hours are spread over their working days from start to due date, instead of
  counted in full on both the start and due dates
- Tooltips in the two rightmost columns open leftward again (the rule targeted the old table layout)
- Today scrolls when today is on the page (the check read calendar values that don't exist)
- "Day N of M" on calendar cards and My Page skips holidays; My Page uses the user's date
- Each appointment's working days are worked out once per page (CustomerAppointment#working_days),
  and shared by placement, hours, day numbers and the end date
- The calendar toggles are kept in the session, so changing month loads the page once
- Clicking inside an open tooltip keeps it open; estimates load with the appointments
- Hours in a working day is a plugin setting (default 8)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-02 21:12:31 -05:00
1 parent ae522baf63
commit 3a5d83aa69
12 files changed
+148 -187

No files matched your search

+1
View File
@@ -33,6 +33,7 @@ Add appointments to the redmine calanedar with the abiltiy to attach a QBO custo
* The appointment page lists the issues linked to its estimate, and **Create Issues from Estimate** opens redmine_qbo's Create issues page with the appointment's dates, technician and vehicle.
* Estimate pages in redmine_qbo get an **Add appointment** link. Other plugins can add to the new appointment through the `:qbo_calendar_appointment_params, { customer:, estimate_id:, custom_fields: }` hook (e.g. redmine_qbo_vehicles: the vehicle with the estimate's VIN).
* **Appointment statuses** are set up in the plugin's settings (Administration › Plugins › Configure): name, colour, whether the time counts toward the calendar's hours, and order (the first is the default). Renaming a status keeps its appointments; removing one in use asks which status to move them to. Statuses that don't count hours (e.g. Cancelled) stay on the calendar, crossed out.
* **Hours in a working day** (plugin setting, default 8): multi-day appointments count up to this many hours a day on the calendar, from their first day. Issues' estimated hours are spread over their working days from start to due date.
* **Call-outs**: an employee off work, added with the button next to each day's add button. They show at the top of the day in red stripes, have no customer or status, and never count toward hours. Upgrading (migration 004) turns appointments with the old Call_Out status into call-outs.
---
+16 -4
View File
@@ -73,10 +73,22 @@ class CustomerAppointment < ActiveRecord::Base
# Last working day of the appointment. Weekends and holidays are skipped, matching how the
# calendar spreads a multi-day appointment (a 3-day job starting Friday ends Tuesday).
def due_date
return nil unless date
@due_date_cache ||= {}
@due_date_cache[[start_date, duration.to_i]] ||=
RedmineQboCalendar::WorkingDays.nth_working_day(start_date, duration)
working_days.last
end
# The working days the appointment takes (weekends and holidays skipped), in order: "Day 2 of 3" is the
# second. Pass the holidays when working this out for many appointments, to read them once.
def working_days(holidays: nil)
return [] unless date
@working_days ||= {}
@working_days[[start_date, duration.to_i]] ||=
RedmineQboCalendar::WorkingDays.dates(start_date, duration, **{ holidays: holidays }.compact)
end
# Which working day of the appointment a date is (1 for the first), or nil when it isn't one
def working_day_number(day)
index = working_days.index(day.to_date)
index && index + 1
end
# Appointments the user may see. Requires the global "View customer appointments" permission.
+46 -81
View File
@@ -1,18 +1,20 @@
<%= javascript_include_tag("calendar", plugin: :redmine_qbo_calendar) %>
<%
# Check if toggles are active via query params
# Toggles: kept in the session by CalendarsControllerPatch, so month links keep them
only_appointments = params[:only_appointments] == '1'
hide_past_weeks = params[:hide_past_weeks] == '1'
# Current date context
# Current date context: the Today button scrolls when today is on the page, else opens today's month
today = User.current.today
is_current_month = (calendar.instance_variable_get(:@month) == today.month && calendar.instance_variable_get(:@year) == today.year)
is_current_month = (calendar.startdt..calendar.enddt).cover?(today)
# Get Redmine's configured non-working week days (e.g., ["6", "7"] for Sat/Sun)
# Read once for the whole page
non_working_days = Setting.non_working_week_days || []
all_holidays = Holiday.all
all_holidays = Holiday.all.to_a
working_days_between = lambda do |first, last|
RedmineQboCalendar::WorkingDays.between(first, last, holidays: all_holidays, week_days: non_working_days)
end
# Safely collect all unique CustomerAppointments across the entire calendar date range
# Prefer the list loaded by CalendarsControllerPatch; fall back to the calendar's own events
@@ -21,83 +23,42 @@
calendar.events_on(date)
}.select { |e| e.is_a?(CustomerAppointment) }.uniq
# Lambda to determine if an appointment should render on a specific calendar day
appointment_occurs_on = lambda do |appointment, current_day|
app_datetime = appointment.respond_to?(:date) && appointment.date.present? ? appointment.date : appointment.start_date
return false if app_datetime.nil?
start_date = app_datetime.to_date
target_date = current_day.to_date
return false if target_date < start_date
# Skip rendering on Redmine standard non-working days
return false if non_working_days.include?(target_date.cwday.to_s)
# Skip rendering on custom non-working days (Holidays)
return false if all_holidays.any? { |h| h.occurs_on?(target_date) }
duration = [appointment.duration.to_i, 1].max
date_cursor = start_date
working_days_count = 0
while date_cursor <= target_date
is_standard_weekend = non_working_days.include?(date_cursor.cwday.to_s)
is_custom_holiday = all_holidays.any? { |h| h.occurs_on?(date_cursor) }
# Only increment duration count if it's a standard working day AND not a holiday
unless is_standard_weekend || is_custom_holiday
working_days_count += 1
end
if date_cursor == target_date
return working_days_count <= duration
end
date_cursor += 1 # Pure Ruby Date increment stays a Date object
# Each appointment on each of its working days (weekends and holidays skipped), worked out once:
# { date => [[appointment, day number], ...] }
appointments_by_day = Hash.new { |h, k| h[k] = [] }
all_appointments.each do |appointment|
appointment.working_days(holidays: all_holidays).each_with_index do |date, index|
appointments_by_day[date] << [appointment, index + 1] if date.between?(calendar.startdt, calendar.enddt)
end
false
end
# Lambda to calculate hours for a single event on a specific day (Front-Loaded Method)
calculate_event_hours = lambda do |event, target_day|
if event.is_a?(Issue)
event.estimated_hours.to_f
elsif event.is_a?(CustomerAppointment) && !event.counts_toward_hours?
# Cancelled / call-out appointments stay on the calendar but don't use scheduled time
0.0
elsif event.is_a?(CustomerAppointment)
if event.duration.to_i > 1
app_total_hours = if event.respond_to?(:estimated_hours) && event.estimated_hours.present?
event.estimated_hours.to_f
else
event.duration.to_f * 8.0
end
start_date = (event.respond_to?(:date) && event.date.present? ? event.date : event.start_date).to_date
working_day_index = 0
date_cursor = start_date
while date_cursor < target_day
is_weekend = non_working_days.include?(date_cursor.cwday.to_s)
is_holiday = all_holidays.any? { |h| h.occurs_on?(date_cursor) }
working_day_index += 1 unless is_weekend || is_holiday
date_cursor += 1
end
hours_already_allocated = working_day_index * 8.0
remaining_hours = app_total_hours - hours_already_allocated
[[remaining_hours, 8.0].min, 0.0].max
elsif event.respond_to?(:estimated_hours) && event.estimated_hours.present?
event.estimated_hours.to_f
else
event.duration.to_f
end
# An appointment's hours on its Nth day: multi-day appointments use up to a working day's hours (plugin
# setting, 8 by default) a day from the start (front-loaded); cancelled appointments and call-outs use none
hours_per_day = RedmineQboCalendar.hours_per_day
appointment_hours = lambda do |appointment, day_number|
next 0.0 unless appointment.counts_toward_hours?
if appointment.duration.to_i > 1
total = appointment.estimated_hours.present? ? appointment.estimated_hours.to_f : appointment.duration.to_f * hours_per_day
[[total - (day_number - 1) * hours_per_day, hours_per_day].min, 0.0].max
elsif appointment.estimated_hours.present?
appointment.estimated_hours.to_f
else
0.0
appointment.duration.to_f
end
end
# Issues' estimated hours, spread evenly over the working days from start to due date. Redmine shows an
# issue on its start and due dates only, so counting it on the days it shows would count it twice and
# miss the days between. { date => hours }
issue_hours_by_day = Hash.new(0.0)
unless only_appointments
calendar.instance_variable_get(:@events).to_a.grep(Issue).each do |issue|
next unless issue.estimated_hours.to_f > 0
days = working_days_between.call(issue.start_date || issue.due_date, issue.due_date || issue.start_date)
days = [issue.start_date || issue.due_date].compact if days.empty?
days.each { |d| issue_hours_by_day[d] += issue.estimated_hours.to_f / days.size }
end
end
%>
@@ -186,7 +147,8 @@
week.each do |day|
standard_events = only_appointments ? [] : calendar.events_on(day).reject { |e| e.is_a?(CustomerAppointment) }
matching_appointments = all_appointments.select { |app| appointment_occurs_on.call(app, day) }
day_appointments = appointments_by_day.fetch(day, [])
matching_appointments = day_appointments.map(&:first)
# Call-outs first (who's off that day), then everything else by time
day_events = (standard_events + matching_appointments).sort_by do |event|
@@ -201,12 +163,13 @@
[call_out, time]
end
day_total_hours = day_events.sum { |event| calculate_event_hours.call(event, day) }
day_total_hours = issue_hours_by_day[day] + day_appointments.sum { |appointment, number| appointment_hours.call(appointment, number) }
weekly_total_hours += day_total_hours
# Store it so we don't calculate it twice
week_data[day] = {
events: day_events,
day_numbers: day_appointments.to_h { |appointment, number| [appointment.id, number] },
total_hours: day_total_hours
}
end
@@ -237,6 +200,7 @@
# Retrieve the pre-calculated data for this day
day_events = week_data[day][:events]
total_hours = week_data[day][:total_hours]
day_numbers = week_data[day][:day_numbers]
%>
<%# Added 'week-end' class and background color styling for custom holidays to mimic weekends %>
@@ -342,6 +306,7 @@
locals: {
appointment: event,
day: day,
day_number: day_numbers[event.id],
project: @project
} %>
@@ -1,25 +1,7 @@
<%
non_working_days = Setting.non_working_week_days || []
app_datetime = (appointment.respond_to?(:date) && appointment.date.present?) ? appointment.date : appointment.start_date
start_date = app_datetime.to_date
target_date = day.to_date
# Which working day of the appointment this is (the calendar passes it; weekends and holidays skipped)
duration = [appointment.duration.to_i, 1].max
day_number = 0
if target_date >= start_date
date_cursor = start_date
working_count = 0
while date_cursor <= target_date
unless non_working_days.include?(date_cursor.cwday.to_s)
working_count += 1
end
if date_cursor == target_date
day_number = working_count
break
end
date_cursor += 1
end
end
day_number = local_assigns[:day_number] || appointment.working_day_number(day).to_i
%>
<%
@@ -1,11 +1,11 @@
<h3><%= l(:label_upcoming_appointments, default: 'My Upcoming Appointments') %></h3>
<%
# Get Redmine's configured non-working week days (e.g., ["6", "7"] for Sat/Sun)
non_working_days = Setting.non_working_week_days || []
today = User.current.today
holidays = Holiday.all.to_a
# Safely filter appointments by logged-in user across possible user column names
appointments_scope = CustomerAppointment.all
appointments_scope = CustomerAppointment.includes(:customer, :vehicle)
if CustomerAppointment.column_names.include?('user_id')
appointments_scope = appointments_scope.where(user_id: User.current.id)
elsif CustomerAppointment.column_names.include?('assigned_to_id')
@@ -15,41 +15,18 @@
end
# Look back up to 60 days to capture multi-day appointments starting in the past
raw_appointments = appointments_scope.where('date >= ?', Date.today - 60.days)
raw_appointments = appointments_scope.where('date >= ?', today - 60.days)
expanded_appointments = []
raw_appointments.each do |appointment|
next if appointment.start_date.nil?
start_date = appointment.start_date.to_date
duration = [appointment.duration.to_i, 1].max
date_cursor = start_date
working_days_counted = 0
# Expand appointment dates strictly across working days based on duration
while working_days_counted < duration
unless non_working_days.include?(date_cursor.cwday.to_s)
working_days_counted += 1
# Only list dates falling on or after today
if date_cursor >= Date.today
expanded_appointments << {
appointment: appointment,
date: date_cursor,
day_number: working_days_counted,
total_days: duration
}
end
end
date_cursor += 1
# One row per working day (weekends and holidays skipped, as on the calendar), from today on
expanded_appointments = raw_appointments.flat_map do |appointment|
days = appointment.working_days(holidays: holidays)
days.each_with_index.filter_map do |date, index|
{ appointment: appointment, date: date, day_number: index + 1, total_days: days.size } if date >= today
end
end
# Sort upcoming occurrences chronologically and take top 10
expanded_appointments.sort_by! { |item| item[:date] }
expanded_appointments = expanded_appointments.first(10)
expanded_appointments = expanded_appointments.sort_by { |item| [item[:date], item[:appointment].date] }.first(10)
%>
<% if expanded_appointments.any? %>
+10
View File
@@ -30,6 +30,16 @@
end
%>
<fieldset class="box tabular">
<legend><%= l(:label_calendar) %></legend>
<p>
<label for="settings_hours_per_day"><%= l(:label_hours_per_day) %></label>
<%= number_field_tag 'settings[hours_per_day]', number_with_precision(RedmineQboCalendar.hours_per_day, precision: 2, strip_insignificant_zeros: true),
id: 'settings_hours_per_day', min: 0.5, max: 24, step: 0.5, size: 6 %>
<em class="info"><%= l(:text_hours_per_day) %></em>
</p>
</fieldset>
<fieldset class="box">
<legend><%= l(:label_appointment_statuses) %></legend>
<p><em class="info"><%= l(:text_appointment_statuses) %></em></p>
+13 -41
View File
@@ -6,6 +6,9 @@ document.addEventListener('DOMContentLoaded', function() {
// Allow standard links (like subject title or avatar links) to navigate normally
if (clickedLink) return;
// Clicks inside an open tooltip (e.g. selecting a phone number to copy) leave it open
if (e.target.closest('.appointment-block .tip')) return;
// Close any other open tooltips across the calendar
document.querySelectorAll('.appointment-block.open').forEach(function(block) {
if (block !== clickedBlock) {
@@ -22,9 +25,6 @@ document.addEventListener('DOMContentLoaded', function() {
});
(function() {
const STORAGE_KEY_ONLY_APPTS = 'redmine_cal_only_appointments';
const STORAGE_KEY_HIDE_PAST = 'redmine_cal_hide_past_weeks';
window.scrollToToday = function() {
const todayElement = document.getElementById('today');
if (todayElement) {
@@ -33,53 +33,25 @@ document.addEventListener('DOMContentLoaded', function() {
};
document.addEventListener('DOMContentLoaded', function() {
const urlParams = new URLSearchParams(window.location.search);
let needsRedirect = false;
// Sync "Show Customer Appointments Only" with localStorage if missing from URL
if (!urlParams.has('only_appointments') && localStorage.getItem(STORAGE_KEY_ONLY_APPTS) === '1') {
urlParams.set('only_appointments', '1');
needsRedirect = true;
}
// Sync "Hide Past Weeks" with localStorage if missing from URL
if (!urlParams.has('hide_past_weeks') && localStorage.getItem(STORAGE_KEY_HIDE_PAST) === '1') {
urlParams.set('hide_past_weeks', '1');
needsRedirect = true;
}
if (needsRedirect) {
window.location.search = urlParams.toString();
return;
}
// Automatically scroll to today if present and no hash anchor is in the URL
if (!window.location.hash) {
window.scrollToToday();
}
});
window.toggleOnlyAppointments = function(checked) {
// The toggles are kept in the session (CalendarsControllerPatch), so turning one off sends 0 rather
// than leaving it out
function setToggle(name, checked) {
const urlParams = new URLSearchParams(window.location.search);
if (checked) {
urlParams.set('only_appointments', '1');
localStorage.setItem(STORAGE_KEY_ONLY_APPTS, '1');
} else {
urlParams.delete('only_appointments');
localStorage.setItem(STORAGE_KEY_ONLY_APPTS, '0');
}
urlParams.set(name, checked ? '1' : '0');
window.location.search = urlParams.toString();
}
window.toggleOnlyAppointments = function(checked) {
setToggle('only_appointments', checked);
};
window.toggleHidePastWeeks = function(checked) {
const urlParams = new URLSearchParams(window.location.search);
if (checked) {
urlParams.set('hide_past_weeks', '1');
localStorage.setItem(STORAGE_KEY_HIDE_PAST, '1');
} else {
urlParams.delete('hide_past_weeks');
localStorage.setItem(STORAGE_KEY_HIDE_PAST, '0');
}
window.location.search = urlParams.toString();
setToggle('hide_past_weeks', checked);
};
})();
})();
+6 -3
View File
@@ -151,8 +151,10 @@ table.cal td {
cursor: default;
}
/* Align tooltips to the right on Friday/Saturday columns */
table.cal td:nth-child(n+6) .appointment-block .tip {
/* Tooltips in the two rightmost day columns open leftward, so they stay on screen. Each calendar row is
8 items (week number, then 7 days), so the last two days are items 8n+7 and 8n. */
ul.cal li.calbody:nth-child(8n+7) .appointment-block .tip,
ul.cal li.calbody:nth-child(8n) .appointment-block .tip {
left: auto !important;
right: 0 !important;
}
@@ -460,7 +462,8 @@ table.cal td.today {
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.4) !important;
}
table.cal td:nth-child(n+6) .appointment-block .tip {
ul.cal li.calbody:nth-child(8n+7) .appointment-block .tip,
ul.cal li.calbody:nth-child(8n) .appointment-block .tip {
left: 50% !important;
right: auto !important;
}
+4
View File
@@ -116,3 +116,7 @@ en:
notice_appointments_moved:
one: "Moved 1 appointment from %{from} to %{to}."
other: "Moved %{count} appointments from %{from} to %{to}."
# Calendar settings
label_hours_per_day: "Hours in a working day"
text_hours_per_day: "Multi-day appointments count up to this many hours a day on the calendar, from their first day; one without its own hours counts this many a day. Default 8."
+9
View File
@@ -9,6 +9,15 @@
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module RedmineQboCalendar
DEFAULT_HOURS_PER_DAY = 8.0
# A working day's hours (plugin setting): multi-day appointments use up to this many hours a day on the
# calendar, and one without its own hours takes this many a day
def self.hours_per_day
hours = (Setting.plugin_redmine_qbo_calendar || {})['hours_per_day'].to_f
hours.positive? && hours <= 24 ? hours : DEFAULT_HOURS_PER_DAY
end
def self.setup
# Patches
Customer.prepend(RedmineQboCalendar::Patches::CustomerPatch)
@@ -24,6 +24,17 @@ module RedmineQboCalendar
params[:month] ||= session[:qbo_calendar_month]
end
# The "Hide past weeks" and "Show customer appointments only" toggles stick for the session, so
# month links (which don't carry them) keep them without a second page load
%w[only_appointments hide_past_weeks].each do |name|
key = :"qbo_calendar_#{name}"
if params.key?(name)
session[key] = params[name] == '1'
elsif session[key]
params[name] = '1'
end
end
# 2. Call Redmine core CalendarsController#show
super
@@ -35,7 +46,7 @@ module RedmineQboCalendar
log "events: #{events.inspect}"
# Only users with "View customer appointments" see appointments on the calendar
appointments = CustomerAppointment.visible(User.current).includes(:customer, :vehicle, :user, :project)
appointments = CustomerAppointment.visible(User.current).includes(:customer, :vehicle, :user, :project, :estimate)
# Only load appointments that can appear in the displayed range. Multi-day appointments
# can start before the range, so look back far enough to cover the longest one
+19 -4
View File
@@ -29,17 +29,32 @@ module RedmineQboCalendar
def nth_working_day(start_date, count, holidays: Holiday.all.to_a, week_days: non_working_week_days)
return nil if start_date.nil?
dates(start_date, count, holidays: holidays, week_days: week_days).last || (start_date + MAX_SCAN_DAYS)
end
# The first N working days from start_date (itself included when it's a working day), e.g. a 3-day job
# starting Friday works Fri, Mon and Tue
def dates(start_date, count, holidays: Holiday.all.to_a, week_days: non_working_week_days)
return [] if start_date.nil?
count = [count.to_i, 1].max
cursor = start_date
worked = 0
worked = []
MAX_SCAN_DAYS.times do
worked += 1 unless non_working?(cursor, holidays: holidays, week_days: week_days)
return cursor if worked >= count
worked << cursor unless non_working?(cursor, holidays: holidays, week_days: week_days)
break if worked.size >= count
cursor += 1
end
cursor
worked
end
# The working days from first to last, both included (e.g. the days an issue runs)
def between(first, last, holidays: Holiday.all.to_a, week_days: non_working_week_days)
return [] if first.nil? || last.nil? || last < first
(first..[last, first + MAX_SCAN_DAYS].min).reject { |d| non_working?(d, holidays: holidays, week_days: week_days) }
end
end
end