discourse/app/models/user_notification_schedule.rb
Mark VanLandingham 1a7922bea2
FEATURE: Create notification schedule to automatically set do not disturb time (#11665)
This adds a new table UserNotificationSchedules which stores monday-friday start and ends times that each user would like to receive notifications (with a Boolean enabled to remove the use of the schedule). There is then a background job that runs every day and creates do_not_disturb_timings for each user with an enabled notification schedule. The job schedules timings 2 days in advance. The job is designed so that it can be run at any point in time, and it will not create duplicate records.

When a users saves their notification schedule, the schedule processing service will run and schedule do_not_disturb_timings. If the user should be in DND due to their schedule, the user will immediately be put in DND (message bus publishes this state).

The UI for a user's notification schedule is in user -> preferences -> notifications. By default every day is 8am - 5pm when first enabled.
2021-01-20 10:31:52 -06:00

46 lines
1.2 KiB
Ruby

# frozen_string_literal: true
class UserNotificationSchedule < ActiveRecord::Base
belongs_to :user
DEFAULT = -> {
attrs = { enabled: false }
7.times do |n|
attrs["day_#{n}_start_time".to_sym] = 480
attrs["day_#{n}_end_time".to_sym] = 1020
end
attrs
}.call
validate :has_valid_times
validates :enabled, inclusion: { in: [ true, false ] }
scope :enabled, -> { where(enabled: true) }
def create_do_not_disturb_timings(delete_existing: false)
user.do_not_disturb_timings.where(scheduled: true).destroy_all if delete_existing
UserNotificationScheduleProcessor.create_do_not_disturb_timings_for(self)
end
private
def has_valid_times
7.times do |n|
start_key = "day_#{n}_start_time"
end_key = "day_#{n}_end_time"
if self[start_key].nil? || self[start_key] > 1410 || self[start_key] < -1
errors.add(start_key, "is invalid")
end
if self[end_key].nil? || self[end_key] > 1440
errors.add(end_key, "is invalid")
end
if self[start_key] && self[end_key] && self[start_key] > self[end_key]
errors.add(start_key, "is after end time")
end
end
end
end