New plugin: email customers appointment reminders

Reminders for redmine_qbo_calendar appointments, to the customer's email in
QuickBooks, sent from your own mailbox through Google Workspace's SMTP relay
(or Gmail SMTP with an app password, or Redmine's email settings).

- Schedule: N days before at a set time, only within sending hours, not within
  N hours of the appointment; rescheduling sends one for the new time
- Plain text + HTML from an editable template with placeholders and sections,
  calendar (.ics) attachment, Message-ID on the sending domain
- Each reminder claimed in the database before sending (no duplicates across
  processes); failures retried 3 times
- Appointment page: status and Send now / Send again; customer page: turn
  reminders off; settings: test email, recent reminders, send due now
- Runs on page loads every 10 minutes, or from cron via
  rake redmine:appointment_reminders:send
- README covers Google Workspace setup and SPF/DKIM/DMARC

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-31 22:30:12 -04:00
commit 7c09b58708
28 files changed
+1482

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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 RedmineQboReminders
# How often page loads may start a run (when "Check on page loads" is on)
CHECK_EVERY = 10 * 60
def self.setup
RedmineQboReminders::Hooks::ViewHookListener
RedmineQboReminders::Hooks::AppointmentHookListener
RedmineQboReminders::Hooks::CustomerHookListener
end
# Starts a run in the background, at most every CHECK_EVERY seconds (page loads call this). Without cron,
# reminders go out while someone is using Redmine.
def self.check_soon
settings = Settings.current
return unless settings.enabled? && settings.check_on_page_loads?
return if @last_check && Time.now - @last_check < CHECK_EVERY
@last_check = Time.now
# Shared between Redmine's processes when its cache is; the claim in Sender stops double sends anyway
return unless Rails.cache.write('redmine_qbo_reminders:last_check', Time.now.to_i, unless_exist: true,
expires_in: CHECK_EVERY)
AppointmentRemindersJob.perform_later
rescue StandardError => e
Rails.logger.warn "[RedmineQboReminders] Could not start a run: #{e.message}"
end
end
@@ -0,0 +1,18 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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 RedmineQboReminders
module Hooks
# The reminder's status (and a Send button) on redmine_qbo_calendar's appointment page
class AppointmentHookListener < Redmine::Hook::ViewListener
render_on :show_customer_appointment, partial: 'appointment_reminders/appointment'
end
end
end
@@ -0,0 +1,18 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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 RedmineQboReminders
module Hooks
# Turning reminders on or off for a customer, on the customer page
class CustomerHookListener < Redmine::Hook::ViewListener
render_on :show_customer_view_right, partial: 'appointment_reminders/customer'
end
end
end
@@ -0,0 +1,21 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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 RedmineQboReminders
module Hooks
# Page loads start a reminder run every few minutes (RedmineQboReminders.check_soon); adds nothing to the page
class ViewHookListener < Redmine::Hook::ViewListener
def view_layouts_base_html_head(context = {})
RedmineQboReminders.check_soon if User.current.logged?
''
end
end
end
end
+59
View File
@@ -0,0 +1,59 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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 RedmineQboReminders
# A calendar file (iCalendar) for the appointment, attached to the reminder so the customer can add it
# to their calendar with a tap. Published, not an invitation, so mail apps don't ask them to RSVP.
module Ics
module_function
# starts_at: a Time; minutes: how long the event is
def build(uid:, starts_at:, summary:, minutes: 60, location: nil, description: nil, now: Time.now)
fmt = ->(t) { t.utc.strftime('%Y%m%dT%H%M%SZ') }
lines = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//redmine_qbo_reminders//EN',
'CALSCALE:GREGORIAN',
'METHOD:PUBLISH',
'BEGIN:VEVENT',
"UID:#{uid}",
"DTSTAMP:#{fmt.call(now)}",
"DTSTART:#{fmt.call(starts_at)}",
"DTEND:#{fmt.call(starts_at + minutes * 60)}",
"SUMMARY:#{escape(summary)}"
]
lines << "LOCATION:#{escape(location)}" if location.to_s.strip != ''
lines << "DESCRIPTION:#{escape(description)}" if description.to_s.strip != ''
lines += ['END:VEVENT', 'END:VCALENDAR']
lines.map { |line| fold(line) }.join("\r\n") + "\r\n"
end
def escape(text)
text.to_s.strip.gsub('\\', '\\\\\\\\').gsub(/\r?\n/, '\\n').gsub(',', '\\,').gsub(';', '\\;')
end
# Lines longer than 75 bytes continue on the next line, which starts with a space
def fold(line)
parts = []
current = +''
line.each_char do |ch|
limit = parts.empty? ? 75 : 74
if (current + ch).bytesize > limit
parts << current
current = +''
end
current << ch
end
parts << current
parts.join("\r\n ")
end
end
end
+70
View File
@@ -0,0 +1,70 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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 RedmineQboReminders
# One reminder: who it's to and what it says, built from an appointment and the settings
class Message
attr_reader :settings, :values, :starts_at, :uid
# values: the placeholders' values (see Template); starts_at: the appointment's time in the shop's zone
def initialize(settings:, values:, starts_at:, uid:)
@settings = settings
@values = settings.shop_values.merge(values.transform_keys(&:to_s))
@starts_at = starts_at
@uid = uid
end
# Built from an appointment (redmine_qbo_calendar's CustomerAppointment)
def self.for(appointment, settings, customer_name: nil, first_name: nil)
starts_at = settings.schedule.appointment_time(appointment.date)
customer = appointment.customer
name = customer_name || customer&.name.to_s
values = {
'customer' => name,
'first_name' => first_name.presence || name.split(/\s+/).first.to_s,
'vehicle' => appointment.respond_to?(:vehicle) ? appointment.vehicle&.to_s : nil,
'subject' => appointment.subject
}.merge(when_values(starts_at))
new(settings: settings, values: values, starts_at: starts_at,
uid: "appointment-#{appointment.id}@#{settings.mail_domain}")
end
# {{day}} "Monday, November 2", {{date}} "11/02/2026", {{time}} "9:00 AM"
def self.when_values(starts_at)
{
'day' => starts_at.strftime('%A, %B %-d'),
'date' => starts_at.strftime('%m/%d/%Y'),
'time' => starts_at.strftime('%-l:%M %p')
}
end
def subject
Template.render_line(settings['subject'].presence || Template::DEFAULT_SUBJECT, values)
end
def text
Template.render(settings['body'].presence || Template::DEFAULT_BODY, values)
end
def html
Template.html(text)
end
# The calendar attachment, or nil when it's turned off
def ics
return nil unless settings.attach_calendar?
shop = values['shop_name'].to_s.strip
summary = shop.empty? ? 'Appointment' : "Appointment at #{shop}"
summary += " – #{values['vehicle']}" if values['vehicle'].to_s.strip != ''
Ics.build(uid: uid, starts_at: starts_at, summary: summary, location: values['shop_address'],
description: values['shop_phone'].to_s.strip.empty? ? nil : "Questions or need to reschedule? Call #{values['shop_phone']}")
end
end
end
@@ -0,0 +1,60 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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 RedmineQboReminders
# Where an appointment's reminder stands, for the appointment page:
# :sent sent (reminder.sent_at, to email)
# :failed the last try failed (reminder.error); :given_up when it won't be tried again on schedule
# :sending being sent right now
# :scheduled will go out at `at` to email
# :off reminders are turned off in the plugin's settings
# :opted_out turned off for this customer
# :status the appointment's status doesn't get reminders (e.g. Cancelled)
# :no_customer, :no_email
# :too_late too close to (or past) the appointment to send on schedule
class ReminderStatus
attr_reader :state, :at, :email, :reminder
def self.for(appointment, settings: Settings.current, now: Time.now)
new(appointment, settings, now)
end
def initialize(appointment, settings, now)
@reminder = AppointmentReminder.find_by(customer_appointment_id: appointment.id, appointment_date: appointment.date)
@state = compute(appointment, settings, now)
end
def sent?
state == :sent
end
private
def compute(appointment, settings, now)
if reminder
@email = reminder.email
return :sent if reminder.sent?
return :sending if reminder.status == 'pending' && !reminder.stale?
return(reminder.retry? && settings.enabled? ? :failed : :given_up) if reminder.failed? || reminder.stale?
end
return :off unless settings.enabled?
return :status unless settings.remind_status?(appointment.status)
return :no_customer if appointment.customer.nil?
return :opted_out if ReminderOptOut.opted_out?(appointment.customer)
@email = Sender.customer_email(appointment.customer)
return :no_email if @email.nil?
schedule = settings.schedule
@at = schedule.next_send(schedule.appointment_time(appointment.date), now)
@at ? :scheduled : :too_late
end
end
end
+85
View File
@@ -0,0 +1,85 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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 RedmineQboReminders
# When an appointment's reminder goes out. Times are the shop's wall-clock time (the time zone set in the
# plugin's settings), the way appointments are entered and shown.
#
# A reminder is due once its send time has passed (days_before days ahead of the appointment, at send_at),
# while the appointment is still more than min_lead_hours away, and only between window_start and
# window_end, so a late run never emails customers in the middle of the night.
class Schedule
attr_reader :zone, :days_before, :send_at, :window_start, :window_end, :min_lead_hours
def initialize(zone:, days_before: 1, send_at: '16:00', window_start: '08:00', window_end: '20:00', min_lead_hours: 2)
@zone = zone
@days_before = [days_before.to_i, 0].max
@send_at = minutes(send_at, 16 * 60)
@window_start = minutes(window_start, 8 * 60)
@window_end = minutes(window_end, 20 * 60)
@min_lead_hours = [min_lead_hours.to_f, 0].max
end
# The appointment's time (stored as the time entered) as a time in the shop's zone
def appointment_time(datetime)
zone.local(datetime.year, datetime.month, datetime.day, datetime.hour, datetime.min)
end
# When the reminder for an appointment at this (shop) time goes out
def send_time(appointment_at)
day = appointment_at.to_date - days_before
zone.local(day.year, day.month, day.day, send_at / 60, send_at % 60)
end
# Too close to the appointment to bother (or already past)
def too_late?(appointment_at, now)
now >= appointment_at - (min_lead_hours * 3600)
end
def in_window?(now)
local = now.in_time_zone(zone)
m = local.hour * 60 + local.min
m >= window_start && m < window_end
end
def due?(appointment_at, now)
now >= send_time(appointment_at) && !too_late?(appointment_at, now) && in_window?(now)
end
# When a not-yet-due reminder will go out: its send time, moved to the next sending window if it falls
# outside one. nil when it's too late to send.
def next_send(appointment_at, now)
at = [send_time(appointment_at), now].max.in_time_zone(zone)
unless in_window?(at)
m = at.hour * 60 + at.min
day = m >= window_end ? at.to_date + 1 : at.to_date
at = zone.local(day.year, day.month, day.day, window_start / 60, window_start % 60)
end
too_late?(appointment_at, at) ? nil : at
end
# Appointments worth looking at now: a little either side of the reminder lead, wide enough to cover
# the difference between the server's and the shop's time zone
def lookahead(now)
[now - 1.day, now + (days_before + 2).days]
end
private
# "16:30" -> 990
def minutes(value, default)
h, m = value.to_s.split(':', 2).map { |v| Integer(v, 10) }
return default if h.nil? || h.negative? || h > 23 || m.to_i.negative? || m.to_i > 59
h * 60 + m.to_i
rescue ArgumentError, TypeError
default
end
end
end
+134
View File
@@ -0,0 +1,134 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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 RedmineQboReminders
# Emails the reminders that are due. Run by the rake task (cron), and on page loads every few minutes when
# that's turned on. Safe to run often and from several places at once: each reminder is claimed in the
# database before it's sent, so a customer never gets two for the same appointment time.
class Sender
Result = Struct.new(:sent, :failed, :skipped) do
def to_s
"#{sent} sent, #{failed} failed, #{skipped} skipped"
end
end
attr_reader :settings, :now, :result
def self.run(now: Time.now)
new(now: now).run
end
def initialize(settings: Settings.current, now: Time.now)
@settings = settings
@now = now
@result = Result.new(0, 0, 0)
end
def run
return result unless settings.enabled?
schedule = settings.schedule
return result unless schedule.in_window?(now)
from, to = schedule.lookahead(now)
CustomerAppointment.where(date: from..to).includes(:customer).find_each do |appointment|
consider(appointment, schedule)
end
log "Run finished: #{result}" if result.sent + result.failed > 0
result
end
# Sends an appointment's reminder now, whatever the schedule says (the appointment page's button).
# Returns the AppointmentReminder, or nil when the customer has no email address.
def send_now(appointment, user: nil)
email = self.class.customer_email(appointment.customer)
return nil if email.nil?
existing = AppointmentReminder.find_by(customer_appointment_id: appointment.id, appointment_date: appointment.date)
deliver(appointment, email, existing, user: user)
end
# The customer's email address in QuickBooks (the first, when there are several), or nil
def self.customer_email(customer)
return nil if customer.nil?
address = customer.email.to_s.split(/[,;]/).map(&:strip).find { |a| a.match?(/\A[^@\s]+@[^@\s]+\.[^@\s]+\z/) }
address.presence
rescue StandardError => e
Rails.logger.warn "[RedmineQboReminders] Could not read the email of customer #{customer&.id}: #{e.message}"
nil
end
# The customer's first name in QuickBooks, falling back to the first word of their name
def self.first_name(customer)
customer.respond_to?(:given_name) ? customer.given_name.to_s.strip.presence : nil
rescue StandardError
nil
end
private
def consider(appointment, schedule)
at = schedule.appointment_time(appointment.date)
return unless settings.remind_status?(appointment.status) && schedule.due?(at, now)
customer = appointment.customer
return skip(appointment, 'no customer') if customer.nil?
return skip(appointment, 'customer turned reminders off') if ReminderOptOut.opted_out?(customer)
existing = AppointmentReminder.find_by(customer_appointment_id: appointment.id, appointment_date: appointment.date)
return if existing && !existing.retry?
email = self.class.customer_email(customer)
return skip(appointment, 'customer has no email address') if email.nil?
deliver(appointment, email, existing)
end
def deliver(appointment, email, existing, user: nil)
reminder = claim(appointment, email, existing)
return nil if reminder.nil?
message = Message.for(appointment, settings, first_name: self.class.first_name(appointment.customer))
AppointmentReminderMailer.reminder(message, email).deliver_now
reminder.update!(status: 'sent', sent_at: Time.now, sent_by: user, error: nil)
result.sent += 1
log "Sent the reminder for appointment ##{appointment.id} to #{email}"
reminder
rescue StandardError => e
result.failed += 1
log "Could not send the reminder for appointment ##{appointment.id} to #{email}: #{e.class}: #{e.message}"
reminder&.update_columns(status: 'failed', error: "#{e.class}: #{e.message}".truncate(1000), updated_at: Time.now)
reminder
end
# Marks the reminder as being sent, or nil when another run got to it first
def claim(appointment, email, existing)
if existing.nil?
AppointmentReminder.create!(customer_appointment: appointment, appointment_date: appointment.date,
email: email, status: 'pending', attempts: 1)
else
claimed = AppointmentReminder.where(id: existing.id, attempts: existing.attempts)
.update_all(status: 'pending', attempts: existing.attempts + 1, email: email,
error: nil, updated_at: Time.now)
claimed.zero? ? nil : existing.reload
end
rescue ActiveRecord::RecordNotUnique
nil
end
def skip(appointment, reason)
result.skipped += 1
log "Skipped appointment ##{appointment.id}: #{reason}"
nil
end
def log(msg)
Rails.logger.info "[RedmineQboReminders] #{msg}"
end
end
end
+129
View File
@@ -0,0 +1,129 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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 RedmineQboReminders
# The plugin's settings (Administration » Plugins » Configure), with defaults
class Settings
DEFAULTS = {
'enabled' => '0',
'from_name' => '',
'from_address' => '',
'reply_to' => '',
# 'redmine': Redmine's own email settings (config/configuration.yml); 'smtp': the server below
'delivery' => 'smtp',
'smtp_address' => 'smtp-relay.gmail.com',
'smtp_port' => '587',
'smtp_domain' => '',
'smtp_user_name' => '',
'smtp_password' => '',
'time_zone' => 'Eastern Time (US & Canada)',
'days_before' => '1',
'send_at' => '16:00',
'window_start' => '08:00',
'window_end' => '20:00',
'min_lead_hours' => '2',
'statuses' => ['Scheduled'],
'check_on_page_loads' => '1',
'attach_calendar' => '1',
'shop_name' => '',
'shop_phone' => '',
'shop_address' => '',
'subject' => Template::DEFAULT_SUBJECT,
'body' => Template::DEFAULT_BODY
}.freeze
def self.current
new(Setting.plugin_redmine_qbo_reminders)
end
def initialize(values = {})
@values = DEFAULTS.merge((values || {}).to_h.transform_keys(&:to_s).reject { |_, v| v.nil? })
end
def [](key)
@values[key.to_s]
end
def enabled?
self['enabled'].to_s == '1'
end
def check_on_page_loads?
self['check_on_page_loads'].to_s == '1'
end
def attach_calendar?
self['attach_calendar'].to_s == '1'
end
# Appointment statuses that get reminders; a blank status counts as Scheduled (the form's first choice)
def statuses
Array(self['statuses']).map(&:to_s).reject(&:empty?)
end
def remind_status?(status)
statuses.include?(status.to_s.presence || 'Scheduled')
end
def zone
ActiveSupport::TimeZone[self['time_zone'].to_s] || ActiveSupport::TimeZone['Eastern Time (US & Canada)']
end
def schedule
Schedule.new(zone: zone, days_before: self['days_before'], send_at: self['send_at'],
window_start: self['window_start'], window_end: self['window_end'],
min_lead_hours: self['min_lead_hours'])
end
def from_address
self['from_address'].to_s.strip.presence || (defined?(Setting) && Setting.respond_to?(:mail_from) ? Setting.mail_from.to_s : '')
end
# "Ocean State Off Road <sales@example.com>", quoting the name when it needs it
def from
address = from_address
name = self['from_name'].to_s.strip.presence || self['shop_name'].to_s.strip.presence
return address if name.nil? || address.include?('<')
name = %("#{name.gsub(/(["\\])/, '\\\\\1')}") if name =~ /[()<>\[\]:;@\\,."]/
"#{name} <#{address}>"
end
def reply_to
self['reply_to'].to_s.strip.presence
end
# The domain mail is sent from (sales@example.com -> example.com): the SMTP greeting and Message-IDs
def mail_domain
self['smtp_domain'].to_s.strip.presence || from_address[/@([^>\s]+)/, 1] || 'localhost'
end
# Options for ActionMailer's mail(): empty to use Redmine's email settings
def delivery_options
return {} unless self['delivery'] == 'smtp'
smtp = {
address: self['smtp_address'].to_s.strip.presence || 'smtp-relay.gmail.com',
port: (self['smtp_port'].presence || 587).to_i,
domain: mail_domain,
enable_starttls_auto: true,
open_timeout: 15,
read_timeout: 30
}
if self['smtp_user_name'].to_s.strip != ''
smtp.merge!(user_name: self['smtp_user_name'].to_s.strip, password: self['smtp_password'].to_s, authentication: :plain)
end
{ delivery_method: :smtp, delivery_method_options: smtp }
end
# Shop details for the message
def shop_values
{ 'shop_name' => self['shop_name'], 'shop_phone' => self['shop_phone'], 'shop_address' => self['shop_address'] }
end
end
end
+69
View File
@@ -0,0 +1,69 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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.
require 'cgi'
module RedmineQboReminders
# The reminder's wording, from the settings. Placeholders:
# {{first_name}} {{customer}} {{day}} {{date}} {{time}} {{vehicle}} {{subject}}
# {{shop_name}} {{shop_phone}} {{shop_address}}
# A section shows only when its placeholder has a value ({{#vehicle}}for your {{vehicle}}{{/vehicle}}), and
# an inverted one only when it doesn't ({{^vehicle}}...{{/vehicle}}).
module Template
PLACEHOLDERS = %w[first_name customer day date time vehicle subject shop_name shop_phone shop_address].freeze
DEFAULT_SUBJECT = 'Reminder: your appointment {{day}} at {{time}}'
DEFAULT_BODY = <<~TEXT.strip
Hi {{first_name}},
This is a reminder of your appointment{{#vehicle}} for your {{vehicle}}{{/vehicle}}{{#shop_name}} at {{shop_name}}{{/shop_name}} on {{day}} at {{time}}.
Please reply to this email to confirm{{#shop_phone}}, or call us at {{shop_phone}} if you need to reschedule{{/shop_phone}}{{^shop_phone}}, or to let us know if you need to reschedule{{/shop_phone}}.
Thank you,
{{shop_name}}
{{shop_address}}
{{shop_phone}}
TEXT
module_function
# The text with placeholders filled in (values: { "vehicle" => "2022 Jeep Gladiator", ... })
def render(text, values)
values = values.transform_keys(&:to_s).transform_values { |v| v.to_s.strip }
out = text.to_s.gsub(/\{\{([#^])(\w+)\}\}(.*?)\{\{\/\2\}\}/m) do
present = values[$2].to_s != ''
($1 == '#') == present ? $3 : ''
end
out = out.gsub(/\{\{(\w+)\}\}/) { values[$1].to_s }
# Lines left empty by missing values (e.g. no shop phone) collapse, but paragraph breaks stay
out.gsub(/[ \t]+$/, '').gsub(/\n{3,}/, "\n\n").strip
end
# A one-line version for the subject
def render_line(text, values)
render(text, values).gsub(/\s+/, ' ').strip
end
# Plain text as simple HTML: paragraphs at blank lines, line breaks kept
def html(text)
paragraphs = text.split(/\n{2,}/).map do |para|
"<p style=\"margin:0 0 1em\">#{para.split("\n").map { |line| CGI.escapeHTML(line) }.join('<br>')}</p>"
end
<<~HTML
<!DOCTYPE html>
<html><head><meta charset="utf-8"></head>
<body style="font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:1.5;color:#222">
#{paragraphs.join("\n")}
</body></html>
HTML
end
end
end
+19
View File
@@ -0,0 +1,19 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#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.
namespace :redmine do
namespace :appointment_reminders do
desc 'Email the appointment reminders that are due (run it from cron, e.g. every 15 minutes)'
task send: :environment do
result = RedmineQboReminders::Sender.run
puts "Appointment reminders: #{result}"
end
end
end