A platform for community discussion. Free, open, simple.
FEATURE: Notify admins of upcoming changes and log events (#37003)
Martin Brennanfb9bb3198384
diff --git a/app/assets/stylesheets/common/base/menu-panel.scss b/app/assets/stylesheets/common/base/menu-panel.scssindex 52ede19e243..ec99f93ea2f 100644--- a/app/assets/stylesheets/common/base/menu-panel.scss+++ b/app/assets/stylesheets/common/base/menu-panel.scss@@ -756,7 +756,7 @@.item-description {color: var(--primary);- @include line-clamp(2);+ @include line-clamp(3);}.icon-avatar {diff --git a/app/models/notification.rb b/app/models/notification.rbindex d1248d992a4..7d4cf76e1e4 100644--- a/app/models/notification.rb+++ b/app/models/notification.rb@@ -161,6 +161,8 @@ class Notification < ActiveRecord::Baseadmin_problems: 38,linked_consolidated: 39,chat_watched_thread: 40,+ upcoming_change_available: 41,+ upcoming_change_automatically_promoted: 42,following: 800, # Used by https://github.com/discourse/discourse-followfollowing_created_topic: 801, # Used by https://github.com/discourse/discourse-followfollowing_replied: 802, # Used by https://github.com/discourse/discourse-followdiff --git a/app/models/upcoming_change_event.rb b/app/models/upcoming_change_event.rbnew file mode 100644index 00000000000..0247f939696--- /dev/null+++ b/app/models/upcoming_change_event.rb@@ -0,0 +1,41 @@+# frozen_string_literal: true++class UpcomingChangeEvent < ActiveRecord::Base+ belongs_to :acting_user, class_name: "User"++ validates :event_type, presence: true+ validates :upcoming_change_name, presence: true++ enum :event_type,+ {+ added: 0,+ removed: 1,+ automatically_promoted: 2,+ manual_opt_in: 3,+ manual_opt_out: 4,+ status_changed: 5,+ admins_notified_available_change: 6,+ admins_notified_automatic_promotion: 7,+ }++ default_scope { order(:created_at) }+end++# == Schema Information+#+# Table name: upcoming_change_events+#+# id :bigint not null, primary key+# event_data :json+# event_type :integer not null+# upcoming_change_name :string not null+# created_at :datetime not null+# updated_at :datetime not null+# acting_user_id :bigint+#+# Indexes+#+# idx_upcoming_change_events_unique_once_off (upcoming_change_name,event_type) UNIQUE WHERE (event_type = ANY (ARRAY[0, 1, 6, 7]))+# index_upcoming_change_events_on_event_type (event_type)+# index_upcoming_change_events_on_upcoming_change_name (upcoming_change_name)+#diff --git a/app/models/user_history.rb b/app/models/user_history.rbindex d65a7eb49f5..a0f9103fe28 100644--- a/app/models/user_history.rb+++ b/app/models/user_history.rb@@ -160,6 +160,7 @@ class UserHistory < ActiveRecord::Basestop_impersonating: 121,upcoming_change_toggled: 122,change_site_setting_groups: 123,+ upcoming_change_available: 124,)end@@ -286,6 +287,7 @@ class UserHistory < ActiveRecord::Basestop_impersonatingupcoming_change_toggledchange_site_setting_groups+ upcoming_change_available]enddiff --git a/app/serializers/current_user_serializer.rb b/app/serializers/current_user_serializer.rbindex a7717ec58d5..12f491921a0 100644--- a/app/serializers/current_user_serializer.rb+++ b/app/serializers/current_user_serializer.rb@@ -76,6 +76,7 @@ class CurrentUserSerializer < BasicUserSerializer:can_view_raw_email,:login_method,:has_unseen_features,+ :has_new_upcoming_changes,:can_see_emails,:can_localize_content?,:effective_locale,@@ -142,12 +143,24 @@ class CurrentUserSerializer < BasicUserSerializerscope.can_send_private_messages?end+ def include_has_unseen_features?+ object.staff?+ end+def has_unseen_featuresDiscourseUpdates.has_unseen_features?(object.id)end- def include_has_unseen_features?- object.staff?+ def include_has_new_upcoming_changes?+ SiteSetting.enable_upcoming_changes && object.staff?+ end++ def has_new_upcoming_changes+ last_visited = object.custom_fields["last_visited_upcoming_changes_at"]++ scope = UpcomingChangeEvent.added+ scope = scope.where("created_at > ?", Time.zone.parse(last_visited)) if last_visited.present?+ scope.exists?enddef can_post_anonymouslydiff --git a/app/services/notification/action/bulk_create.rb b/app/services/notification/action/bulk_create.rbnew file mode 100644index 00000000000..12b35f4477a--- /dev/null+++ b/app/services/notification/action/bulk_create.rb@@ -0,0 +1,83 @@+# frozen_string_literal: true++# Bulk creates notifications using insert_all! for efficiency, then manually+# handles the after_commit callbacks that would normally run on individual creates:+# - MessageBus notification state publishing per user+# - Email processing via NotificationEmailer+# - DiscourseEvent.trigger(:notification_created, notification)+#+# @example+# Notification::Action::BulkCreate.call(+# records: [+# { user_id: 1, notification_type: Notification.types[:custom], data: "{}".to_json },+# { user_id: 2, notification_type: Notification.types[:custom], data: "{}".to_json },+# ]+# )+#+class Notification::Action::BulkCreate < Service::ActionBase+ # Array of notification attribute hashes.+ # Required keys: :user_id, :notification_type, :data+ # Optional keys: :topic_id, :post_number, :high_priority+ option :records++ # Skip email sending for all notifications+ option :skip_send_email, default: -> { false }++ def call+ return [] if records.blank?++ insert_notifications+ publish_notification_states+ post_process_notifications++ @notification_ids+ end++ private++ def insert_notifications+ now = Time.zone.now++ rows =+ records.map do |record|+ {+ user_id: record[:user_id],+ notification_type: record[:notification_type],+ data: record[:data],+ topic_id: record[:topic_id],+ post_number: record[:post_number],+ high_priority:+ record[:high_priority] ||+ Notification.high_priority_types.include?(record[:notification_type]),+ read: false,+ created_at: now,+ updated_at: now,+ }+ end++ result = Notification.insert_all!(rows, returning: %i[id user_id])+ @notification_ids = result.rows.map(&:first)+ @user_ids_from_insert = result.rows.map(&:second).uniq+ end++ def publish_notification_states+ User.where(id: @user_ids_from_insert).find_each(&:publish_notifications_state)+ end++ def post_process_notifications+ Notification+ .where(id: @notification_ids)+ .includes(:user)+ .find_each do |notification|+ if !skip_send_email+ if notification.user.do_not_disturb?+ ShelvedNotification.create(notification_id: notification.id)+ else+ NotificationEmailer.process_notification(notification)+ end+ end++ DiscourseEvent.trigger(:notification_created, notification)+ end+ end+enddiff --git a/app/services/staff_action_logger.rb b/app/services/staff_action_logger.rbindex d406b20317d..43ce4a630aa 100644--- a/app/services/staff_action_logger.rb+++ b/app/services/staff_action_logger.rb@@ -275,6 +275,17 @@ class StaffActionLogger)end+ def log_upcoming_change_available(setting_name, opts = {})+ raise Discourse::InvalidParameters.new(:setting_name) if setting_name.blank?+ UserHistory.create!(+ params(opts).merge(+ action: UserHistory.actions[:upcoming_change_available],+ subject: setting_name,+ details: SiteSetting.humanized_name(setting_name),+ ),+ )+ end+def log_site_setting_groups_change(setting_name, previous_value, new_value, opts = {})unless setting_name.present? && SiteSetting.respond_to?(setting_name)raise Discourse::InvalidParameters.new(:setting_name)diff --git a/app/services/upcoming_changes/action/notify_admins_of_available_change.rb b/app/services/upcoming_changes/action/notify_admins_of_available_change.rbnew file mode 100644index 00000000000..b48d15c2dff--- /dev/null+++ b/app/services/upcoming_changes/action/notify_admins_of_available_change.rb@@ -0,0 +1,55 @@+# frozen_string_literal: true++# Intended to be called from UpcomingChanges::Action::TrackStatusChanges, and+# UpcomingChanges::Action::TrackAddedChanges, not standalone.+#+# Send a notification to all admins that the upcoming change is available for+# them to opt-in to.+#+# This will either happen when the change is added, or when the status of the+# change is changed to the promotion status minus one.+class UpcomingChanges::Action::NotifyAdminsOfAvailableChange < Service::ActionBase+ # The name of the upcoming change (site setting name)+ option :change_name++ # All admins that are not bots+ option :all_admins++ def call+ notify_admins+ create_event+ log_action+ true+ end++ private++ def notify_admins+ data = {+ upcoming_change_name: change_name,+ upcoming_change_humanized_name: SiteSetting.humanized_name(change_name),+ }.to_json++ records =+ all_admins.map do |admin|+ {+ user_id: admin.id,+ notification_type: Notification.types[:upcoming_change_available],+ data:,+ }+ end++ Notification::Action::BulkCreate.call(records:)+ end++ def create_event+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_available_change,+ upcoming_change_name: change_name,+ )+ end++ def log_action+ StaffActionLogger.new(Discourse.system_user).log_upcoming_change_available(change_name)+ end+enddiff --git a/app/services/upcoming_changes/action/track_added_changes.rb b/app/services/upcoming_changes/action/track_added_changes.rbnew file mode 100644index 00000000000..af751dd0c5c--- /dev/null+++ b/app/services/upcoming_changes/action/track_added_changes.rb@@ -0,0 +1,57 @@+# frozen_string_literal: true++# Intended to be called from UpcomingChanges::Track service,+# not standalone.+#+# Look at UpcomingChangeEvent to get all event_type: added (0) events+# * Compare with SiteSetting.upcoming_change_site_settings to see if there are any missing+# * If so, create an `added` event for the added changes+# * Send notifications to all admins if the change is the correct status (promotion_status - 1)+class UpcomingChanges::Action::TrackAddedChanges < Service::ActionBase+ # Every admin user that are not bots+ option :all_admins++ def call+ added_changes = []+ notified_changes = []++ (SiteSetting.upcoming_change_site_settings - previously_added_changes).each do |change_name|+ added_changes << change_name+ UpcomingChangeEvent.create!(event_type: :added, upcoming_change_name: change_name)++ # We only want to notify admins once the change has reached a certain status,+ # which is the promotion status minus one (previous status).+ #+ # Therefore, we may register the `added` event above in one deploy, then+ # send a notification to admins that the UC is available in a later deploy.+ notify_at_status =+ UpcomingChanges.previous_status(SiteSetting.promote_upcoming_changes_on_status)++ if UpcomingChanges.meets_or_exceeds_status?(change_name, notify_at_status)+ # However, we want to skip notifying if the change already meets the+ # promotion status criteria. The UpcomingChanges::Promote service will+ # handle it instead.+ #+ # We don't want to notify admins that a change is available then+ # immediately notify them it's enabled.+ if !UpcomingChanges.meets_or_exceeds_status?(+ change_name,+ SiteSetting.promote_upcoming_changes_on_status.to_sym,+ )+ notified =+ UpcomingChanges::Action::NotifyAdminsOfAvailableChange.call(change_name:, all_admins:)+ notified_changes << change_name if notified+ end+ end+ end++ { added_changes:, notified_changes: }+ end++ private++ def previously_added_changes+ @previously_added_changes ||=+ UpcomingChangeEvent.added.pluck(:upcoming_change_name).uniq.map(&:to_sym)+ end+enddiff --git a/app/services/upcoming_changes/action/track_removed_changes.rb b/app/services/upcoming_changes/action/track_removed_changes.rbnew file mode 100644index 00000000000..014a39c21fa--- /dev/null+++ b/app/services/upcoming_changes/action/track_removed_changes.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++# Intended to be called from UpcomingChanges::Track service,+# not standalone.+#+# Lookup any event_type: added (0) events and compare with removed (1) events+# * If there are any added that are no longer in SiteSetting.upcoming_change_site_settings+# with no corresponding removed (1) event, create a removed event for them.+#+# We do not need to notify admins about removed changes.+class UpcomingChanges::Action::TrackRemovedChanges < Service::ActionBase+ def call+ previously_added_changes.filter_map do |change_name|+ next if SiteSetting.upcoming_change_site_settings.include?(change_name)+ next if previously_removed_changes.include?(change_name)++ UpcomingChangeEvent.create!(event_type: :removed, upcoming_change_name: change_name)+ change_name+ end+ end++ private++ def previously_added_changes+ @previously_added_changes ||=+ UpcomingChangeEvent.added.pluck(:upcoming_change_name).uniq.map(&:to_sym)+ end++ def previously_removed_changes+ @previously_removed_changes ||=+ UpcomingChangeEvent.removed.pluck(:upcoming_change_name).uniq.map(&:to_sym)+ end+enddiff --git a/app/services/upcoming_changes/action/track_status_changes.rb b/app/services/upcoming_changes/action/track_status_changes.rbnew file mode 100644index 00000000000..804e0c47843--- /dev/null+++ b/app/services/upcoming_changes/action/track_status_changes.rb@@ -0,0 +1,110 @@+# frozen_string_literal: true++# Intended to be called from UpcomingChanges::Track service,+# not standalone.+#+# Lookup any previous event_type: status_changed (5) events for the change+# * If there are none, create one for the current status+# * Send an appropriate notification to admins+# * If the change was also added at the same time, and the status is correct (promotion_status - 1),+# then don't send another notification+# * If the change was not added, send a notification about the status change if it's the correct+# status (promotion_status - 1) to indicate it's available to admins+class UpcomingChanges::Action::TrackStatusChanges < Service::ActionBase+ # Every admin user that are not bots+ option :all_admins++ # All changes that were added at the same time, we already added events+ # and notified admins for them.+ option :added_changes++ # All changes that were removed at the same time, we don't care about+ # their statuses anymore.+ option :removed_changes++ def call+ status_changes = {}+ notified_changes = []++ SiteSetting.upcoming_change_site_settings.each do |change_name|+ if no_previous_status_event?(change_name)+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: change_name,+ event_data: {+ previous_value: nil,+ new_value: UpcomingChanges.change_status(change_name),+ },+ )+ status_changes[change_name] = {+ previous_value: "N/A",+ new_value: UpcomingChanges.change_status(change_name),+ }+ next+ end++ next if added_changes.include?(change_name)+ next if removed_changes.include?(change_name)++ previous_status = previous_status_for(change_name)+ current_status = UpcomingChanges.change_status(change_name)++ if status_changed?(previous_status, current_status)+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: change_name,+ event_data: {+ previous_value: previous_status,+ new_value: current_status,+ },+ )+ status_changes[change_name] = { previous_value: previous_status, new_value: current_status }++ # If admins were already notified about this change, don't notify them again.+ # This can happen if the change was added and it already met the promotion status+ # minus one (previous status) criteria for notification.+ #+ # However, if the status was later changed and it meets the promotion status+ # minus one (previous status) criteria for notification, then we should notify+ # admins here.+ if should_notify_admins?(change_name)+ notified =+ UpcomingChanges::Action::NotifyAdminsOfAvailableChange.call(change_name:, all_admins:)+ notified_changes << change_name if notified+ end+ end+ end++ { status_changes:, notified_changes: }+ end++ private++ def previous_status_events+ @previous_status_events ||= UpcomingChangeEvent.status_changed.to_a+ end++ def no_previous_status_event?(change_name)+ previous_status_events.none? { |event| event.upcoming_change_name == change_name.to_s }+ end++ def previous_status_for(change_name)+ previous_status_events+ .select { |event| event.upcoming_change_name == change_name.to_s }+ .last+ .event_data[+ "new_value"+ ]+ end++ def status_changed?(previous_status, current_status)+ previous_status&.to_sym != current_status+ end++ def should_notify_admins?(change_name)+ !UpcomingChangeEvent.exists?(+ upcoming_change_name: change_name,+ event_type: :admins_notified_available_change,+ )+ end+enddiff --git a/app/services/upcoming_changes/list.rb b/app/services/upcoming_changes/list.rbindex f2d9d3e74f6..6d90ec08d83 100644--- a/app/services/upcoming_changes/list.rb+++ b/app/services/upcoming_changes/list.rb@@ -7,6 +7,7 @@ class UpcomingChanges::Listmodel :upcoming_changes, optional: truestep :load_upcoming_change_groupsstep :sort_changes+ step :update_last_visitedprivate@@ -76,4 +77,11 @@ class UpcomingChanges::Listdef sort_changes(upcoming_changes:)context[:upcoming_changes] = upcoming_changes.sort_by { |change| change[:setting] }end++ def update_last_visited(guardian:)+ return if guardian.user.is_system_user? || guardian.user.bot?++ guardian.user.custom_fields["last_visited_upcoming_changes_at"] = Time.current.iso8601+ guardian.user.save_custom_fields+ endenddiff --git a/app/services/upcoming_changes/promote.rb b/app/services/upcoming_changes/promote.rbindex 6789d1300a6..2a8d7c9d1b3 100644--- a/app/services/upcoming_changes/promote.rb+++ b/app/services/upcoming_changes/promote.rb@@ -22,6 +22,8 @@ class UpcomingChanges::Promotepolicy :setting_not_already_enabledstep :toggle_upcoming_changestep :log_promotion+ step :notify_admins+ step :create_eventprivate@@ -84,4 +86,34 @@ class UpcomingChanges::Promote{ context: },)end++ def notify_admins(params:)+ data = {+ upcoming_change_name: params.setting_name,+ upcoming_change_humanized_name: SiteSetting.humanized_name(params.setting_name),+ }.to_json++ records =+ User+ .human_users+ .admins+ .pluck(:id)+ .map do |admin_id|+ {+ user_id: admin_id,+ notification_type: Notification.types[:upcoming_change_automatically_promoted],+ data:,+ }+ end++ Notification::Action::BulkCreate.call(records:)+ end++ def create_event(params:)+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_automatic_promotion,+ upcoming_change_name: params.setting_name,+ acting_user: Discourse.system_user,+ )+ endenddiff --git a/app/services/upcoming_changes/toggle.rb b/app/services/upcoming_changes/toggle.rbindex e4c6493949c..1fe562dd9b8 100644--- a/app/services/upcoming_changes/toggle.rb+++ b/app/services/upcoming_changes/toggle.rb@@ -18,6 +18,11 @@ class UpcomingChanges::Togglepolicy :setting_is_availabletransaction { step :toggle }+ only_if(:should_log_change) do+ step :log_change+ step :log_event+ end+privatedef current_user_is_admin(guardian:)@@ -34,23 +39,37 @@ class UpcomingChanges::Toggle# about upcoming changes via "What's new?" experimental toggles# before we update that UI.if SiteSetting.enable_upcoming_changes- previous_value = SiteSetting.public_send(params.setting_name)+ context[:previous_value] = SiteSetting.public_send(params.setting_name)SiteSetting.send("#{params.setting_name}=", params.enabled)+ else+ SiteSetting.public_send("#{params.setting_name}=", params.enabled)+ end+ end- if options.log_change- StaffActionLogger.new(guardian.user).log_upcoming_change_toggle(- params.setting_name,- previous_value,- params.enabled,- { context: I18n.t("staff_action_logs.upcoming_changes.log_manually_toggled") },- )- end+ def should_log_change(options:)+ options.log_change+ end++ def log_change(params:, guardian:, options:)+ if SiteSetting.enable_upcoming_changes+ StaffActionLogger.new(guardian.user).log_upcoming_change_toggle(+ params.setting_name,+ context[:previous_value],+ params.enabled,+ { context: I18n.t("staff_action_logs.upcoming_changes.log_manually_toggled") },+ )else- if options.log_change- SiteSetting.set_and_log(params.setting_name, params.enabled, guardian.user)- else- SiteSetting.public_send("#{params.setting_name}=", params.enabled)- end+ SiteSetting.log(params.setting_name, params.enabled, context[:previous_value], guardian.user)endend++ def log_event(params:, guardian:, options:)+ return unless SiteSetting.enable_upcoming_changes++ UpcomingChangeEvent.create!(+ event_type: params.enabled ? :manual_opt_in : :manual_opt_out,+ upcoming_change_name: params.setting_name,+ acting_user: guardian.user,+ )+ endenddiff --git a/app/services/upcoming_changes/track.rb b/app/services/upcoming_changes/track.rbnew file mode 100644index 00000000000..b37a87d58bf--- /dev/null+++ b/app/services/upcoming_changes/track.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++# Handles tracking the addition, removal, and status changes of upcoming changes,+# via UpcomingChangeEvent records, and subsequently notifying admins that the+# upcoming change is available for them to opt-in to, based on certain criteria+# that are explained in the Action classes.+#+# Called from the TrackingInitializer in the config/initializers/015-track-upcoming-changes.rb file.+class UpcomingChanges::Track+ include Service::Base++ model :all_admins+ model :added_changes, optional: true+ model :removed_changes, optional: true+ model :status_changes, optional: true++ private++ def fetch_all_admins+ User.human_users.admins+ end++ def fetch_added_changes(all_admins:)+ result = UpcomingChanges::Action::TrackAddedChanges.call(all_admins:)+ context[:notified_admins_for_added_changes] = result[:notified_changes]+ result[:added_changes]+ end++ def fetch_removed_changes+ UpcomingChanges::Action::TrackRemovedChanges.call+ end++ def fetch_status_changes(added_changes:, removed_changes:, all_admins:)+ result =+ UpcomingChanges::Action::TrackStatusChanges.call(+ all_admins:,+ added_changes:,+ removed_changes:,+ )+ context[:notified_admins_for_added_changes] += result[:notified_changes]+ result[:status_changes]+ end+enddiff --git a/config/initializers/015-track-upcoming-changes.rb b/config/initializers/015-track-upcoming-changes.rbnew file mode 100644index 00000000000..f516aeaa00e--- /dev/null+++ b/config/initializers/015-track-upcoming-changes.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true+#+# Tracks both the addition and removal of upcoming changes by+# observing site_settings/settings.yml files and writing to+# an upcoming change event log.+#+# Added upcoming changes will send a notification to site admins+# to inform them that the change is now available to opt-in,+# as long as the status of the change is one less than+# SiteSetting.promote_upcoming_changes_on_status. For example,+# if a site has `beta` for the promotion status, we only notify+# admins when the change reaches `alpha`.+#+# We may end up with separate added & status change events, and+# the admin should only be notified when the status is actually+# SiteSetting.promote_upcoming_changes_on_status - 1 OR gte+# SiteSetting.promote_upcoming_changes_on_status.+#+# Removed upcoming changes will be logged. After some time,+# if the setting related to the change no longer exists, the+# setting value in the site_settings table will be deleted+# in a cleanup job.++require "upcoming_changes"+require "upcoming_changes/tracking_initializer"++Rails.application.config.after_initialize { UpcomingChanges::TrackingInitializer.call }diff --git a/config/initializers/015_promote_upcoming_changes.rb b/config/initializers/015_promote_upcoming_changes.rbdeleted file mode 100644index bd694b1ee91..00000000000--- a/config/initializers/015_promote_upcoming_changes.rb+++ /dev/null@@ -1,91 +0,0 @@-# frozen_string_literal: true-#-# Promotes upcoming changes (defined in site_settings.yml) based-# on their status, and the configured promote_upcoming_changes_on_status-# site setting for the site.--require_relative "../../lib/upcoming_changes"--Rails.application.config.after_initialize { UpcomingChanges::AutoPromotionInitializer.call }--class UpcomingChanges::AutoPromotionInitializer- def self.log_prefix(site)- "[Upcoming changes promoter (#{site})]:"- end-- def self.verbose_log(site, level, message)- return unless SiteSetting.upcoming_change_verbose_logging- Rails.logger.public_send(level, "#{log_prefix(site)} #{message}")- end-- def self.call- RailsMultisite::ConnectionManagement.safe_each_connection do |site|- next if !SiteSetting.enable_upcoming_changes-- verbose_log(site, :info, "Starting promotion check for upcoming changes.")-- if SiteSetting.upcoming_change_site_settings.empty?- verbose_log(site, :info, "No upcoming changes present.")- next- end-- SiteSetting.upcoming_change_site_settings.each do |setting_name|- UpcomingChanges::Promote.call(- params: {- setting_name:,- promotion_status_threshold: SiteSetting.promote_upcoming_changes_on_status,- },- guardian: Guardian.new(Discourse.system_user),- ) do |result|- on_failed_policy(:meets_promotion_criteria) do- verbose_log(- site,- :warn,- "'#{setting_name}' did not meet promotion criteria. Current status is #{UpcomingChanges.change_status(setting_name)}, required status is #{SiteSetting.promote_upcoming_changes_on_status}.",- )- end-- on_failed_policy(:setting_not_modified) do- verbose_log(- site,- :warn,- "'#{setting_name}' has already been modified by an admin, skipping promotion.",- )- end-- on_failed_policy(:setting_not_already_enabled) do- verbose_log(site, :warn, "'#{setting_name}' is already enabled, skipping promotion.")- end-- on_failed_contract do |contract|- verbose_log(- site,- :error,- "Contract failure when promoting '#{setting_name}': #{contract.errors.full_messages.join(", ")}",- )- end-- on_failed_step(:toggle_upcoming_change) do- verbose_log(- site,- :error,- "Failed to promote '#{setting_name}' via toggle_upcoming_change, an unexpected error occurred.",- )- end-- on_failure do |error|- verbose_log(- site,- :error,- "Failed to promote '#{setting_name}', an unexpected error occurred.",- )- end-- on_success do- verbose_log(site, :info, "Successfully promoted '#{setting_name}' to enabled.")- end- end- end- end- end-enddiff --git a/config/initializers/016-promote-upcoming-changes.rb b/config/initializers/016-promote-upcoming-changes.rbnew file mode 100644index 00000000000..b2e3f76647f--- /dev/null+++ b/config/initializers/016-promote-upcoming-changes.rb@@ -0,0 +1,10 @@+# frozen_string_literal: true+#+# Promotes upcoming changes (defined in site_settings.yml) based+# on their status, and the configured promote_upcoming_changes_on_status+# site setting for the site.++require "upcoming_changes"+require "upcoming_changes/auto_promotion_initializer"++Rails.application.config.after_initialize { UpcomingChanges::AutoPromotionInitializer.call }diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 16298f7096a..3605ddc68d8 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -3280,6 +3280,13 @@ en:votes_released: "%{description} - completed"new_features: "New features available!"admin_problems: "New advice on your site dashboard"+ upcoming_changes:+ available:+ title: "Upcoming changes"+ description: "'%{changeName}' is available for preview"+ automatically_promoted:+ title: "Upcoming changes"+ description: "'%{changeName}' has been automatically enabled"dismiss_confirmation:body:default:@@ -7789,6 +7796,7 @@ en:change_theme_site_setting: "change theme site setting"stop_impersonating: "stop impersonating"upcoming_change_toggled: "upcoming change toggled"+ upcoming_change_available: "upcoming change available"change_site_setting_groups: "change site setting groups"discourse_id_regenerate_credentials: "regenerate Discourse ID credentials"screened_emails:diff --git a/db/migrate/20260108060111_create_upcoming_change_events.rb b/db/migrate/20260108060111_create_upcoming_change_events.rbnew file mode 100644index 00000000000..b4a9728a8f5--- /dev/null+++ b/db/migrate/20260108060111_create_upcoming_change_events.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++class CreateUpcomingChangeEvents < ActiveRecord::Migration[8.0]+ def change+ create_table :upcoming_change_events do |t|+ t.integer :event_type, null: false+ t.string :upcoming_change_name, null: false+ t.json :event_data+ t.bigint :acting_user_id++ t.timestamps+ end++ add_index :upcoming_change_events, :event_type+ add_index :upcoming_change_events, :upcoming_change_name+ add_index :upcoming_change_events,+ %i[upcoming_change_name event_type],+ unique: true,+ name: "idx_upcoming_change_events_unique_once_off",+ where: "event_type IN (0, 1, 6, 7)" # added, removed, admins_notified_available_change, admins_notified_automatic_promotion+ end+enddiff --git a/frontend/discourse/admin/routes/admin-config/upcoming-changes.js b/frontend/discourse/admin/routes/admin-config/upcoming-changes.jsindex e8616f0645b..564412d9482 100644--- a/frontend/discourse/admin/routes/admin-config/upcoming-changes.js+++ b/frontend/discourse/admin/routes/admin-config/upcoming-changes.js@@ -1,8 +1,11 @@+import { service } from "@ember/service";import { ajax } from "discourse/lib/ajax";import DiscourseRoute from "discourse/routes/discourse";import { i18n } from "discourse-i18n";export default class AdminConfigUpcomingChangesRoute extends DiscourseRoute {+ @service currentUser;+titleToken() {return i18n("admin.config.upcoming_changes.title");}@@ -12,4 +15,8 @@ export default class AdminConfigUpcomingChangesRoute extends DiscourseRoute {(result) => result.upcoming_changes);}++ activate() {+ this.currentUser.set("has_new_upcoming_changes", false);+ }}diff --git a/frontend/discourse/app/lib/notification-types-manager.js b/frontend/discourse/app/lib/notification-types-manager.jsindex 665de7915c2..4eadd4a56b7 100644--- a/frontend/discourse/app/lib/notification-types-manager.js+++ b/frontend/discourse/app/lib/notification-types-manager.js@@ -14,6 +14,8 @@ import MembershipRequestAccepted from "discourse/lib/notification-types/membershimport MembershipRequestConsolidated from "discourse/lib/notification-types/membership-request-consolidated";import MovedPost from "discourse/lib/notification-types/moved-post";import NewFeatures from "discourse/lib/notification-types/new-features";+import UpcomingChangeAutomaticallyPromoted from "discourse/lib/notification-types/upcoming-change-automatically-promoted";+import UpcomingChangeAvailable from "discourse/lib/notification-types/upcoming-change-available";import WatchingFirstPost from "discourse/lib/notification-types/watching-first-post";const CLASS_FOR_TYPE = {@@ -32,6 +34,8 @@ const CLASS_FOR_TYPE = {moved_post: MovedPost,new_features: NewFeatures,admin_problems: AdminProblems,+ upcoming_change_available: UpcomingChangeAvailable,+ upcoming_change_automatically_promoted: UpcomingChangeAutomaticallyPromoted,watching_first_post: WatchingFirstPost,};diff --git a/frontend/discourse/app/lib/notification-types/upcoming-change-automatically-promoted.js b/frontend/discourse/app/lib/notification-types/upcoming-change-automatically-promoted.jsnew file mode 100644index 00000000000..4d09852c543--- /dev/null+++ b/frontend/discourse/app/lib/notification-types/upcoming-change-automatically-promoted.js@@ -0,0 +1,26 @@+import getURL from "discourse/lib/get-url";+import NotificationTypeBase from "discourse/lib/notification-types/base";+import { i18n } from "discourse-i18n";++export default class extends NotificationTypeBase {+ get label() {+ return i18n("notifications.upcoming_changes.automatically_promoted.title");+ }++ get description() {+ return i18n(+ "notifications.upcoming_changes.automatically_promoted.description",+ {+ changeName: this.notification.data.upcoming_change_humanized_name,+ }+ );+ }++ get linkHref() {+ return getURL("/admin/config/upcoming-changes");+ }++ get icon() {+ return "flask";+ }+}diff --git a/frontend/discourse/app/lib/notification-types/upcoming-change-available.js b/frontend/discourse/app/lib/notification-types/upcoming-change-available.jsnew file mode 100644index 00000000000..9ff9a7793fd--- /dev/null+++ b/frontend/discourse/app/lib/notification-types/upcoming-change-available.js@@ -0,0 +1,23 @@+import getURL from "discourse/lib/get-url";+import NotificationTypeBase from "discourse/lib/notification-types/base";+import { i18n } from "discourse-i18n";++export default class extends NotificationTypeBase {+ get label() {+ return i18n("notifications.upcoming_changes.available.title");+ }++ get description() {+ return i18n("notifications.upcoming_changes.available.description", {+ changeName: this.notification.data.upcoming_change_humanized_name,+ });+ }++ get linkHref() {+ return getURL("/admin/config/upcoming-changes");+ }++ get icon() {+ return "flask";+ }+}diff --git a/frontend/discourse/app/lib/sidebar/admin-sidebar.js b/frontend/discourse/app/lib/sidebar/admin-sidebar.jsindex dea4d69d7c3..9f8024f629a 100644--- a/frontend/discourse/app/lib/sidebar/admin-sidebar.js+++ b/frontend/discourse/app/lib/sidebar/admin-sidebar.js@@ -117,19 +117,19 @@ class SidebarAdminSectionLink extends BaseCustomSidebarSectionLink {}get suffixType() {- if (this.#hasUnseenFeatures) {+ if (this.#hasUnseenFeatures || this.#hasNewUpcomingChanges) {return "icon";}}get suffixValue() {- if (this.#hasUnseenFeatures) {+ if (this.#hasUnseenFeatures || this.#hasNewUpcomingChanges) {return "circle";}}get suffixCSSClass() {- if (this.#hasUnseenFeatures) {+ if (this.#hasUnseenFeatures || this.#hasNewUpcomingChanges) {return "admin-sidebar-nav-link__dot";}}@@ -140,6 +140,13 @@ class SidebarAdminSectionLink extends BaseCustomSidebarSectionLink {this.currentUser.hasUnseenFeatures);}++ get #hasNewUpcomingChanges() {+ return (+ this.adminSidebarNavLink.name === "admin_upcoming_changes" &&+ this.currentUser.hasNewUpcomingChanges+ );+ }}function defineAdminSection(@@ -424,16 +431,22 @@ export default class AdminSidebarPanel extends BaseCustomSidebarPanel {}if (siteSettings.enable_upcoming_changes) {- this.adminNavManager.amendLinksToSection("root", [- {- name: "admin_upcoming_changes",- route: "adminConfig.upcomingChanges",- label: "admin.config.upcoming_changes.title",- description: "admin.config.upcoming_changes.header_description",- icon: "flask",- keywords: "admin.config.upcoming_changes.keywords",- },- ]);+ const rootSection = this.adminNavManager.findSection("root");+ const linkExists = rootSection?.links.some(+ (link) => link.name === "admin_upcoming_changes"+ );+ if (!linkExists) {+ this.adminNavManager.amendLinksToSection("root", [+ {+ name: "admin_upcoming_changes",+ route: "adminConfig.upcomingChanges",+ label: "admin.config.upcoming_changes.title",+ description: "admin.config.upcoming_changes.header_description",+ icon: "flask",+ keywords: "admin.config.upcoming_changes.keywords",+ },+ ]);+ }}for (const [sectionName, additionalLinks] of Object.entries(diff --git a/frontend/discourse/app/models/user.js b/frontend/discourse/app/models/user.jsindex da232b059df..8051c7324e1 100644--- a/frontend/discourse/app/models/user.js+++ b/frontend/discourse/app/models/user.js@@ -317,6 +317,11 @@ export default class User extends RestModel.extend(Evented) {return this.staff && this.get("has_unseen_features");}+ @computed("has_new_upcoming_changes")+ get hasNewUpcomingChanges() {+ return this.staff && this.get("has_new_upcoming_changes");+ }+destroySession() {return ajax(`/session/${this.username}`, { type: "DELETE" });}diff --git a/lib/site_setting_extension.rb b/lib/site_setting_extension.rbindex ec5b031c8b3..264c889da93 100644--- a/lib/site_setting_extension.rb+++ b/lib/site_setting_extension.rb@@ -811,6 +811,17 @@ module SiteSettingExtensionendend+ def log(name, value, prev_value, user = Discourse.system_user, detailed_message = nil)+ return if hidden_settings.include?(name.to_sym)+ value = prev_value = "[FILTERED]" if secret_settings.include?(name.to_sym)+ StaffActionLogger.new(user).log_site_setting_change(+ name,+ prev_value,+ value,+ { details: detailed_message }.compact_blank,+ )+ end+def get(name, scoped_to = nil)if has_setting?(name)if themeable[name]@@ -1118,17 +1129,6 @@ module SiteSettingExtensionendend- def log(name, value, prev_value, user = Discourse.system_user, detailed_message = nil)- value = prev_value = "[FILTERED]" if secret_settings.include?(name.to_sym)- return if hidden_settings.include?(name.to_sym)- StaffActionLogger.new(user).log_site_setting_change(- name,- prev_value,- value,- { details: detailed_message }.compact_blank,- )- end-def default_uploads@default_uploads ||= {}diff --git a/lib/upcoming_changes.rb b/lib/upcoming_changes.rbindex c4f90f673bf..dcf31478dfd 100644--- a/lib/upcoming_changes.rb+++ b/lib/upcoming_changes.rb@@ -16,6 +16,16 @@ module UpcomingChanges::Enum.new(experimental: 0, alpha: 100, beta: 200, stable: 300, permanent: 500, never: 9999)end+ def self.previous_status_value(status)+ status_value = self.statuses[status.to_sym]+ self.statuses.values.select { |value| value < status_value }.max || 0+ end++ def self.previous_status(status)+ self.statuses.keys.select { |key| self.statuses[key] < self.statuses[status.to_sym] }.last ||+ :experimental+ end+def self.image_exists?(change_setting_name)File.exist?(File.join(Rails.public_path, self.image_path(change_setting_name)))enddiff --git a/lib/upcoming_changes/auto_promotion_initializer.rb b/lib/upcoming_changes/auto_promotion_initializer.rbnew file mode 100644index 00000000000..deb591bc974--- /dev/null+++ b/lib/upcoming_changes/auto_promotion_initializer.rb@@ -0,0 +1,91 @@+# frozen_string_literal: true++module UpcomingChanges+ class AutoPromotionInitializer+ def self.log_prefix(site)+ "[Upcoming changes promoter (#{site})]: "+ end++ def self.verbose_log(site, level, message)+ return unless SiteSetting.upcoming_change_verbose_logging+ Rails.logger.public_send(level, "#{log_prefix(site)} #{message}")+ end++ def self.call+ RailsMultisite::ConnectionManagement.safe_each_connection do |site|+ next if !SiteSetting.enable_upcoming_changes++ verbose_log(site, :info, "Starting promotion check for upcoming changes.")++ if SiteSetting.upcoming_change_site_settings.empty?+ verbose_log(site, :info, "No upcoming changes present.")+ next+ end++ DistributedMutex.synchronize("promote_upcoming_changes_#{site}") do+ SiteSetting.upcoming_change_site_settings.each do |setting_name|+ UpcomingChanges::Promote.call(+ params: {+ setting_name:,+ promotion_status_threshold: SiteSetting.promote_upcoming_changes_on_status,+ },+ guardian: Guardian.new(Discourse.system_user),+ ) do |result|+ on_failed_policy(:meets_promotion_criteria) do+ verbose_log(+ site,+ :warn,+ "'#{setting_name}' did not meet promotion criteria. Current status is #{UpcomingChanges.change_status(setting_name)}, required status is #{SiteSetting.promote_upcoming_changes_on_status}.",+ )+ end++ on_failed_policy(:setting_not_modified) do+ verbose_log(+ site,+ :warn,+ "'#{setting_name}' has already been modified by an admin, skipping promotion.",+ )+ end++ on_failed_policy(:setting_not_already_enabled) do+ verbose_log(+ site,+ :warn,+ "'#{setting_name}' is already enabled, skipping promotion.",+ )+ end++ on_failed_contract do |contract|+ verbose_log(+ site,+ :error,+ "Contract failure when promoting '#{setting_name}': #{contract.errors.full_messages.join(", ")}",+ )+ end++ on_failed_step(:toggle_upcoming_change) do+ verbose_log(+ site,+ :error,+ "Failed to promote '#{setting_name}' via toggle_upcoming_change, an unexpected error occurred.",+ )+ end++ on_failure do |error|+ verbose_log(+ site,+ :error,+ "Failed to promote '#{setting_name}', an unexpected error occurred. Error: #{error&.backtrace&.join("\n")}",+ )+ end++ on_success do+ verbose_log(site, :info, "Successfully promoted '#{setting_name}' to enabled.")+ end+ end+ end+ end+ end+ end+ end+enddiff --git a/lib/upcoming_changes/tracking_initializer.rb b/lib/upcoming_changes/tracking_initializer.rbnew file mode 100644index 00000000000..75c6e82a072--- /dev/null+++ b/lib/upcoming_changes/tracking_initializer.rb@@ -0,0 +1,65 @@+# frozen_string_literal: true++module UpcomingChanges+ class TrackingInitializer+ def self.log_prefix(site)+ "[Upcoming changes tracker (#{site})]: "+ end++ def self.verbose_log(site, level, message)+ return unless SiteSetting.upcoming_change_verbose_logging+ Rails.logger.public_send(level, "#{log_prefix(site)} #{message}")+ end++ def self.call+ RailsMultisite::ConnectionManagement.safe_each_connection do |site|+ next if !SiteSetting.enable_upcoming_changes++ verbose_log(site, :info, "Beginning tracking initializer for upcoming changes")++ if SiteSetting.upcoming_change_site_settings.empty?+ verbose_log(site, :info, "No upcoming changes present.")+ next+ end++ DistributedMutex.synchronize("track_upcoming_changes_#{site}") do+ UpcomingChanges::Track.call(guardian: Guardian.new(Discourse.system_user)) do |result|+ on_success do |added_changes:, removed_changes:, notified_admins_for_added_changes:, status_changes:|+ added_changes.each do |change_name|+ verbose_log(site, :info, "added upcoming change '#{change_name}'")+ end++ notified_admins_for_added_changes.each do |change_name|+ verbose_log(+ site,+ :info,+ "notified site admins about added upcoming change '#{change_name}'",+ )+ end++ removed_changes.each do |change_name|+ verbose_log(site, :info, "removed upcoming change '#{change_name}'")+ end++ status_changes.each do |change_name, details|+ verbose_log(+ site,+ :info,+ "status changed for upcoming change '#{change_name}' from #{details[:previous_value]} to #{details[:new_value]}",+ )+ end+ end++ on_failure do |error|+ verbose_log(+ site,+ :error,+ "Failed to track upcoming changes', an unexpected error occurred. Error: #{error&.backtrace&.join("\n")}",+ )+ end+ end+ end+ end+ end+ end+enddiff --git a/spec/multisite/015_promote_upcoming_changes_initializer_spec.rb b/spec/lib/upcoming_changes/auto_promotion_initializer_multisite_spec.rbsimilarity index 54%rename from spec/multisite/015_promote_upcoming_changes_initializer_spec.rbrename to spec/lib/upcoming_changes/auto_promotion_initializer_multisite_spec.rbindex 981af10d1b2..771931f379c 100644--- a/spec/multisite/015_promote_upcoming_changes_initializer_spec.rb+++ b/spec/lib/upcoming_changes/auto_promotion_initializer_multisite_spec.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-RSpec.describe "Promote upcoming changes initializer", type: :multisite do+RSpec.describe UpcomingChanges::AutoPromotionInitializer, type: :multisite docontext "when enable_upcoming_changes is enabled" dobefore doSiteSetting.enable_upcoming_changes = true@@ -10,7 +10,7 @@ RSpec.describe "Promote upcoming changes initializer", type: :multisite do{enable_upload_debug_mode: {impact: "other,developers",- status: :stable,+ status: :beta,impact_type: "feature",impact_role: "admins",},@@ -18,21 +18,24 @@ RSpec.describe "Promote upcoming changes initializer", type: :multisite do)end- it "works for multisites that satisfy promotion criteria" do+ it "promotes changes on sites that satisfy promotion criteria" dotest_multisite_connection("default") do- expect(SiteSetting.enable_upload_debug_mode).to be(false)- end- test_multisite_connection("second") do- expect(SiteSetting.enable_upload_debug_mode).to be(false)- end+ SiteSetting.enable_upload_debug_mode = false+ SiteSetting.promote_upcoming_changes_on_status = :beta- UpcomingChanges::AutoPromotionInitializer.call+ UpcomingChanges::AutoPromotionInitializer.call- test_multisite_connection("default") doexpect(SiteSetting.enable_upload_debug_mode).to be(true)end++ # beta status doesn't meet stable threshold, so should not be promotedtest_multisite_connection("second") do- expect(SiteSetting.enable_upload_debug_mode).to be(true)+ SiteSetting.enable_upload_debug_mode = false+ SiteSetting.promote_upcoming_changes_on_status = :stable++ UpcomingChanges::AutoPromotionInitializer.call++ expect(SiteSetting.enable_upload_debug_mode).to be(false)endendenddiff --git a/spec/initializers/015_promote_upcoming_changes_spec.rb b/spec/lib/upcoming_changes/auto_promotion_initializer_spec.rbsimilarity index 95%rename from spec/initializers/015_promote_upcoming_changes_spec.rbrename to spec/lib/upcoming_changes/auto_promotion_initializer_spec.rbindex 96e437523f7..fc0b5b72c31 100644--- a/spec/initializers/015_promote_upcoming_changes_spec.rb+++ b/spec/lib/upcoming_changes/auto_promotion_initializer_spec.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-RSpec.describe "Promote upcoming changes initializer" do+RSpec.describe UpcomingChanges::AutoPromotionInitializer docontext "when enable_upcoming_changes is disabled" dobefore doSiteSetting.enable_upcoming_changes = false@@ -42,6 +42,11 @@ RSpec.describe "Promote upcoming changes initializer" do)end+ it "synchronizes execution using DistributedMutex" do+ DistributedMutex.expects(:synchronize).with("promote_upcoming_changes_default").yields+ UpcomingChanges::AutoPromotionInitializer.call+ end+context "when the change does not meet the promotion criteria" dobefore { SiteSetting.promote_upcoming_changes_on_status = :never }diff --git a/spec/lib/upcoming_changes/tracking_initializer_multisite_spec.rb b/spec/lib/upcoming_changes/tracking_initializer_multisite_spec.rbnew file mode 100644index 00000000000..74798435868--- /dev/null+++ b/spec/lib/upcoming_changes/tracking_initializer_multisite_spec.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::TrackingInitializer, type: :multisite do+ context "when enable_upcoming_changes is enabled" do+ before do+ SiteSetting.enable_upcoming_changes = true+ SiteSetting.upcoming_change_verbose_logging = true+ SiteSetting.promote_upcoming_changes_on_status = :stable++ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: :beta,+ impact_type: "feature",+ impact_role: "admins",+ },+ },+ )+ end++ it "tracks changes across all sites" do+ test_multisite_connection("default") do+ Fabricate(:admin)+ SiteSetting.enable_upcoming_changes = true+ SiteSetting.promote_upcoming_changes_on_status = :stable+ UpcomingChangeEvent.where(upcoming_change_name: :enable_upload_debug_mode).delete_all++ UpcomingChanges::TrackingInitializer.call++ expect(+ UpcomingChangeEvent.exists?(+ upcoming_change_name: :enable_upload_debug_mode,+ event_type: :added,+ ),+ ).to be(true)+ end++ test_multisite_connection("second") do+ Fabricate(:admin)+ SiteSetting.enable_upcoming_changes = true+ SiteSetting.promote_upcoming_changes_on_status = :stable+ UpcomingChangeEvent.where(upcoming_change_name: :enable_upload_debug_mode).delete_all++ UpcomingChanges::TrackingInitializer.call++ expect(+ UpcomingChangeEvent.exists?(+ upcoming_change_name: :enable_upload_debug_mode,+ event_type: :added,+ ),+ ).to be(true)+ end+ end+ end+enddiff --git a/spec/lib/upcoming_changes/tracking_initializer_spec.rb b/spec/lib/upcoming_changes/tracking_initializer_spec.rbnew file mode 100644index 00000000000..40373d50f44--- /dev/null+++ b/spec/lib/upcoming_changes/tracking_initializer_spec.rb@@ -0,0 +1,176 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::TrackingInitializer do+ context "when enable_upcoming_changes is disabled" do+ before do+ SiteSetting.enable_upcoming_changes = false+ SiteSetting.promote_upcoming_changes_on_status = :stable+ end++ it "does nothing" do+ SiteSetting.expects(:upcoming_change_site_settings).never+ UpcomingChanges::TrackingInitializer.call+ end+ end++ context "when enable_upcoming_changes is enabled" do+ before do+ SiteSetting.enable_upcoming_changes = true+ SiteSetting.upcoming_change_verbose_logging = true+ SiteSetting.promote_upcoming_changes_on_status = :stable+ end++ context "when there are upcoming changes to track" do+ fab!(:admin)++ before do+ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: :beta,+ impact_type: "other",+ impact_role: "developers",+ },+ enable_user_tips: {+ impact: "feature,all_members",+ status: :alpha,+ impact_type: "feature",+ impact_role: "all_members",+ },+ },+ )+ end++ it "synchronizes execution using DistributedMutex" do+ DistributedMutex.expects(:synchronize).with("track_upcoming_changes_default").yields+ UpcomingChanges::TrackingInitializer.call+ end++ context "when changes are newly added" do+ before do+ UpcomingChangeEvent.where(+ upcoming_change_name: %i[enable_upload_debug_mode enable_user_tips],+ ).delete_all+ end++ it "logs added changes" do+ track_log_messages do |logger|+ UpcomingChanges::TrackingInitializer.call+ expect(logger.infos.join("\n")).to include(+ "added upcoming change 'enable_upload_debug_mode'",+ )+ expect(logger.infos.join("\n")).to include("added upcoming change 'enable_user_tips'")+ end+ end+ end++ context "when admins are notified about an available change" do+ before do+ UpcomingChangeEvent.where(+ upcoming_change_name: %i[enable_upload_debug_mode enable_user_tips],+ ).delete_all+ end++ it "logs that admins were notified" do+ track_log_messages do |logger|+ UpcomingChanges::TrackingInitializer.call+ expect(logger.infos.join("\n")).to include(+ "notified site admins about added upcoming change 'enable_upload_debug_mode'",+ )+ end+ end++ it "does not log notification for changes that do not meet status threshold" do+ track_log_messages do |logger|+ UpcomingChanges::TrackingInitializer.call+ expect(logger.infos.join("\n")).not_to include(+ "notified site admins about added upcoming change 'enable_user_tips'",+ )+ end+ end+ end++ context "when changes are removed" do+ before do+ UpcomingChangeEvent.create!(event_type: :added, upcoming_change_name: :old_removed_change)+ end++ after { UpcomingChangeEvent.where(upcoming_change_name: :old_removed_change).delete_all }++ it "logs removed changes" do+ track_log_messages do |logger|+ UpcomingChanges::TrackingInitializer.call+ expect(logger.infos.join("\n")).to include(+ "removed upcoming change 'old_removed_change'",+ )+ end+ end+ end++ context "when status changes for an existing change" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :enable_upload_debug_mode,+ )+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :enable_upload_debug_mode,+ event_data: {+ "previous_value" => nil,+ "new_value" => "alpha",+ },+ )+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :enable_upload_debug_mode,+ )+ end++ it "logs status changes" do+ track_log_messages do |logger|+ UpcomingChanges::TrackingInitializer.call+ expect(logger.infos.join("\n")).to include(+ "status changed for upcoming change 'enable_upload_debug_mode' from alpha to beta",+ )+ end+ end+ end+ end++ context "when the UpcomingChanges::Track service has an unexpected failure" do+ before do+ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: :stable,+ impact_type: "other",+ impact_role: "developers",+ },+ },+ )+ end++ it "logs the error" do+ failing_track =+ Class.new(UpcomingChanges::Track) do+ def run!+ context.fail(error: "Simulated failure")+ raise Service::Base::Failure.new(context)+ end+ end++ stub_const(UpcomingChanges, "Track", failing_track) do+ track_log_messages do |logger|+ UpcomingChanges::TrackingInitializer.call+ expect(logger.errors.join("\n")).to include(+ "Failed to track upcoming changes', an unexpected error occurred.",+ )+ end+ end+ end+ end+ end+enddiff --git a/spec/lib/upcoming_changes_spec.rb b/spec/lib/upcoming_changes_spec.rbindex aba793eb0c9..0875b24f396 100644--- a/spec/lib/upcoming_changes_spec.rb+++ b/spec/lib/upcoming_changes_spec.rb@@ -195,6 +195,58 @@ RSpec.describe UpcomingChanges doendend+ describe ".previous_status_value" do+ it "returns 0 for experimental (lowest status)" do+ expect(described_class.previous_status_value(:experimental)).to eq(0)+ end++ it "returns 0 for alpha" do+ expect(described_class.previous_status_value(:alpha)).to eq(0)+ end++ it "returns 100 for beta" do+ expect(described_class.previous_status_value(:beta)).to eq(100)+ end++ it "returns 200 for stable" do+ expect(described_class.previous_status_value(:stable)).to eq(200)+ end++ it "returns 300 for permanent" do+ expect(described_class.previous_status_value(:permanent)).to eq(300)+ end++ it "accepts string status names" do+ expect(described_class.previous_status_value("stable")).to eq(200)+ end+ end++ describe ".previous_status" do+ it "returns :experimental for experimental (lowest status)" do+ expect(described_class.previous_status(:experimental)).to eq(:experimental)+ end++ it "returns :experimental for alpha" do+ expect(described_class.previous_status(:alpha)).to eq(:experimental)+ end++ it "returns :alpha for beta" do+ expect(described_class.previous_status(:beta)).to eq(:alpha)+ end++ it "returns :beta for stable" do+ expect(described_class.previous_status(:stable)).to eq(:beta)+ end++ it "returns :stable for permanent" do+ expect(described_class.previous_status(:permanent)).to eq(:stable)+ end++ it "accepts string status names" do+ expect(described_class.previous_status("stable")).to eq(:beta)+ end+ end+describe ".history_for" dofab!(:admin)diff --git a/spec/requests/api/schemas/json/site_response.json b/spec/requests/api/schemas/json/site_response.jsonindex d22980efc05..801f956f13f 100644--- a/spec/requests/api/schemas/json/site_response.json+++ b/spec/requests/api/schemas/json/site_response.json@@ -122,6 +122,12 @@"chat_watched_thread": {"type": "integer"},+ "upcoming_change_available": {+ "type": "integer"+ },+ "upcoming_change_automatically_promoted": {+ "type": "integer"+ },"assigned": {"type": "integer"},diff --git a/spec/services/notification/action/bulk_create_spec.rb b/spec/services/notification/action/bulk_create_spec.rbnew file mode 100644index 00000000000..6da331eec6c--- /dev/null+++ b/spec/services/notification/action/bulk_create_spec.rb@@ -0,0 +1,230 @@+# frozen_string_literal: true++RSpec.describe Notification::Action::BulkCreate do+ describe ".call" do+ subject(:action) { described_class.call(records:, **options) }++ fab!(:user1, :user) { Fabricate(:user, last_seen_at: 1.hour.ago) }+ fab!(:user2, :user) { Fabricate(:user, last_seen_at: 1.hour.ago) }++ let(:options) { {} }++ context "when records is empty" do+ let(:records) { [] }++ it "returns an empty array" do+ expect(action).to eq([])+ end++ it "does not create any notifications" do+ expect { action }.not_to change { Notification.count }+ end+ end++ context "when records is nil" do+ let(:records) { nil }++ it "returns an empty array" do+ expect(action).to eq([])+ end+ end++ context "with a single notification" do+ let(:records) do+ [+ {+ user_id: user1.id,+ notification_type: Notification.types[:custom],+ data: { message: "test" }.to_json,+ },+ ]+ end+ let(:notification) { Notification.find(action.first) }++ it "creates the notification" do+ expect { action }.to change { Notification.count }.by(1)+ end++ it "returns the notification ids" do+ expect(action.length).to eq(1)+ expect(notification).to be_present+ end++ it "sets the correct notification attributes" do+ expect(notification).to have_attributes(+ user: user1,+ notification_type: Notification.types[:custom],+ read: false,+ data_hash: {+ "message" => "test",+ },+ )+ end++ it "publishes notification state to the user" do+ messages = MessageBus.track_publish("/notification/#{user1.id}") { action }++ expect(messages.length).to eq(1)+ end++ it "triggers the notification_created event" do+ events = DiscourseEvent.track_events(:notification_created) { action }++ expect(events.length).to eq(1)+ expect(events.first[:params].first.user_id).to eq(user1.id)+ end++ it "processes email via NotificationEmailer" do+ NotificationEmailer.expects(:process_notification).once+ action+ end+ end++ context "with multiple notifications for different users" do+ let(:records) do+ [+ {+ user_id: user1.id,+ notification_type: Notification.types[:custom],+ data: { message: "test1" }.to_json,+ },+ {+ user_id: user2.id,+ notification_type: Notification.types[:custom],+ data: { message: "test2" }.to_json,+ },+ ]+ end++ it "creates all notifications" do+ expect { action }.to change { Notification.count }.by(2)+ end++ it "returns all notification ids" do+ notification_ids = action+ expect(notification_ids.length).to eq(2)+ end++ it "publishes notification state to each user" do+ messages1 = MessageBus.track_publish("/notification/#{user1.id}") { action }+ expect(messages1.length).to eq(1)+ end++ it "triggers the notification_created event for each notification" do+ events = DiscourseEvent.track_events(:notification_created) { action }++ expect(events.length).to eq(2)+ expect(events.map { |e| e[:params].first.user_id }).to contain_exactly(user1.id, user2.id)+ end+ end++ context "with high_priority notification type" do+ let(:records) do+ [+ {+ user_id: user1.id,+ notification_type: Notification.types[:private_message],+ data: {}.to_json,+ },+ ]+ end++ it "sets high_priority to true based on notification type" do+ notification_ids = action+ notification = Notification.find(notification_ids.first)++ expect(notification.high_priority).to eq(true)+ end+ end++ context "with explicit high_priority option" do+ let(:records) do+ [+ {+ user_id: user1.id,+ notification_type: Notification.types[:custom],+ data: {}.to_json,+ high_priority: true,+ },+ ]+ end++ it "respects the explicit high_priority value" do+ notification_ids = action+ notification = Notification.find(notification_ids.first)++ expect(notification.high_priority).to eq(true)+ end+ end++ context "when user is in do not disturb mode" do+ before do+ Fabricate(+ :do_not_disturb_timing,+ user: user1,+ starts_at: 1.hour.ago,+ ends_at: 1.hour.from_now,+ )+ end++ let(:records) do+ [{ user_id: user1.id, notification_type: Notification.types[:custom], data: {}.to_json }]+ end++ it "creates a shelved notification instead of processing email" do+ expect { action }.to change { ShelvedNotification.count }.by(1)+ end++ it "does not process email via NotificationEmailer" do+ NotificationEmailer.expects(:process_notification).never+ action+ end+ end++ context "with skip_send_email option" do+ let(:options) { { skip_send_email: true } }+ let(:records) do+ [{ user_id: user1.id, notification_type: Notification.types[:custom], data: {}.to_json }]+ end++ it "does not process email via NotificationEmailer" do+ NotificationEmailer.expects(:process_notification).never+ action+ end++ it "does not create shelved notifications" do+ expect { action }.not_to change { ShelvedNotification.count }+ end++ it "still triggers the notification_created event" do+ events = DiscourseEvent.track_events(:notification_created) { action }++ expect(events.length).to eq(1)+ end+ end++ context "with optional attributes" do+ fab!(:topic)++ let(:records) do+ [+ {+ user_id: user1.id,+ notification_type: Notification.types[:replied],+ data: {}.to_json,+ topic_id: topic.id,+ post_number: 3,+ },+ ]+ end++ it "sets topic_id and post_number" do+ notification_ids = action+ notification = Notification.find(notification_ids.first)++ expect(notification.topic_id).to eq(topic.id)+ expect(notification.post_number).to eq(3)+ end+ end+ end+enddiff --git a/spec/services/upcoming_changes/action/notify_admins_of_available_change_spec.rb b/spec/services/upcoming_changes/action/notify_admins_of_available_change_spec.rbnew file mode 100644index 00000000000..3e7de48fecf--- /dev/null+++ b/spec/services/upcoming_changes/action/notify_admins_of_available_change_spec.rb@@ -0,0 +1,70 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::Action::NotifyAdminsOfAvailableChange do+ subject(:result) { described_class.call(change_name:, all_admins:) }++ before do+ mock_upcoming_change_metadata(+ {+ test_upcoming_change: {+ impact: "feature,all_members",+ status: :beta,+ impact_type: "feature",+ impact_role: "all_members",+ },+ },+ )+ end++ fab!(:admin_1, :admin)+ fab!(:admin_2, :admin)++ let(:all_admins) { [admin_1, admin_2] }+ let(:change_name) { :test_upcoming_change }++ describe ".call" do+ let(:notification) do+ Notification.find_by(+ notification_type: Notification.types[:upcoming_change_available],+ user_id: admin_1.id,+ )+ end++ it "returns true" do+ expect(result).to eq(true)+ end++ it "creates a notification for each admin" do+ expect { result }.to change {+ Notification.where(notification_type: Notification.types[:upcoming_change_available]).count+ }.by(2)+ end++ it "creates notifications with correct data" do+ result++ expect(JSON.parse(notification.data)).to include(+ "upcoming_change_name" => "test_upcoming_change",+ "upcoming_change_humanized_name" => SiteSetting.humanized_name(:test_upcoming_change),+ )+ end++ it "creates an admins_notified_available_change event" do+ expect { result }.to change {+ UpcomingChangeEvent.where(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :test_upcoming_change,+ ).count+ }.by(1)+ end++ it "logs a staff action" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:upcoming_change_available],+ subject: "test_upcoming_change",+ ).count+ }.by(1)+ end+ end+enddiff --git a/spec/services/upcoming_changes/action/track_added_changes_spec.rb b/spec/services/upcoming_changes/action/track_added_changes_spec.rbnew file mode 100644index 00000000000..632fd2e6c3a--- /dev/null+++ b/spec/services/upcoming_changes/action/track_added_changes_spec.rb@@ -0,0 +1,143 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::Action::TrackAddedChanges do+ let(:enable_upload_debug_mode_status) { :experimental }+ let(:show_user_menu_avatars_status) { :beta }++ before do+ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: enable_upload_debug_mode_status,+ impact_type: "other",+ impact_role: "developers",+ },+ show_user_menu_avatars: {+ impact: "feature,all_members",+ status: show_user_menu_avatars_status,+ impact_type: "feature",+ impact_role: "all_members",+ },+ },+ )+ end++ def scoped_events+ UpcomingChangeEvent.where(+ upcoming_change_name: %i[enable_upload_debug_mode show_user_menu_avatars],+ )+ end++ fab!(:admin_1, :admin)+ fab!(:admin_2, :admin)++ describe ".call" do+ subject(:result) { described_class.call(all_admins: [admin_1, admin_2]) }++ before { scoped_events.where(event_type: :added).delete_all }++ it "creates UpcomingChangeEvent entries for new upcoming changes" do+ expect { result }.to change { scoped_events.where(event_type: :added).count }.by(2)+ end++ it "returns the added changes" do+ expect(result[:added_changes]).to include(:enable_upload_debug_mode, :show_user_menu_avatars)+ end++ context "when there are previously added changes" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :enable_upload_debug_mode,+ )+ end++ it "does not re-record previously added changes" do+ expect { result }.not_to change {+ scoped_events.where(+ event_type: :added,+ upcoming_change_name: :enable_upload_debug_mode,+ ).count+ }+ end++ it "returns only the newly added changes for the scoped settings" do+ expect(result[:added_changes]).to include(:show_user_menu_avatars)+ expect(result[:added_changes]).not_to include(:enable_upload_debug_mode)+ end+ end++ context "when the change status meets promotion_status - 1" do+ let(:show_user_menu_avatars_status) { :beta }++ before { SiteSetting.promote_upcoming_changes_on_status = "stable" }++ it "notifies all admins" do+ expect { result }.to change {+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .where("data::text LIKE ?", "%show_user_menu_avatars%")+ .count+ }.by(2)+ end++ it "includes the change in notified_changes" do+ expect(result[:notified_changes]).to include(:show_user_menu_avatars)+ end++ it "creates an admins_notified_available_change event" do+ expect { result }.to change {+ scoped_events.where(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :show_user_menu_avatars,+ ).count+ }.by(1)+ end++ it "creates a UserHistory entry for the upcoming change" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:upcoming_change_available],+ subject: "show_user_menu_avatars",+ ).count+ }.by(1)+ end+ end++ context "when the change status does not meet promotion_status - 1" do+ let(:enable_upload_debug_mode_status) { :alpha }+ let(:show_user_menu_avatars_status) { :alpha }++ before { SiteSetting.promote_upcoming_changes_on_status = "stable" }++ it "does not notify admins for the scoped alpha changes" do+ expect { result }.not_to change { Notification.count }+ end++ it "does not include the scoped changes in notified_changes" do+ expect(result[:notified_changes]).to be_empty+ end+ end++ context "when change is added at exactly promotion status threshold" do+ let(:show_user_menu_avatars_status) { :stable }++ before { SiteSetting.promote_upcoming_changes_on_status = "stable" }++ it "does not notify admins (Promote service will handle it)" do+ result+ expect(+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .where("data::text LIKE ?", "%show_user_menu_avatars%")+ .count,+ ).to eq(0)+ end++ it "does not include the change in notified_changes" do+ expect(result[:notified_changes]).not_to include(:show_user_menu_avatars)+ end+ end+ end+enddiff --git a/spec/services/upcoming_changes/action/track_removed_changes_spec.rb b/spec/services/upcoming_changes/action/track_removed_changes_spec.rbnew file mode 100644index 00000000000..788c751c92c--- /dev/null+++ b/spec/services/upcoming_changes/action/track_removed_changes_spec.rb@@ -0,0 +1,78 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::Action::TrackRemovedChanges do+ before do+ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: :experimental,+ impact_type: "other",+ impact_role: "developers",+ },+ show_user_menu_avatars: {+ impact: "feature,all_members",+ status: :beta,+ impact_type: "feature",+ impact_role: "all_members",+ },+ },+ )+ end++ def scoped_events+ UpcomingChangeEvent.where(+ upcoming_change_name: %i[enable_upload_debug_mode show_user_menu_avatars old_removed_change],+ )+ end++ describe ".call" do+ subject(:result) { described_class.call }++ before do+ UpcomingChangeEvent.create!(event_type: :added, upcoming_change_name: :old_removed_change)+ scoped_events.where(event_type: :removed).delete_all+ end++ it "creates a removed event for changes no longer in site settings" do+ expect { result }.to change {+ UpcomingChangeEvent.where(+ event_type: :removed,+ upcoming_change_name: :old_removed_change,+ ).count+ }.by(1)+ end++ it "returns the removed changes" do+ expect(result).to include(:old_removed_change)+ end++ it "does not create a removed event for current changes" do+ expect { result }.not_to change {+ scoped_events.where(+ event_type: :removed,+ upcoming_change_name: :enable_upload_debug_mode,+ ).count+ }+ end++ context "when there are previously removed changes" do+ before do+ UpcomingChangeEvent.create!(event_type: :removed, upcoming_change_name: :old_removed_change)+ end++ it "does not re-record previously removed changes" do+ expect { result }.not_to change {+ UpcomingChangeEvent.where(+ event_type: :removed,+ upcoming_change_name: :old_removed_change,+ ).count+ }+ end++ it "does not include previously removed changes in result" do+ expect(result).not_to include(:old_removed_change)+ end+ end+ end+enddiff --git a/spec/services/upcoming_changes/action/track_status_changes_spec.rb b/spec/services/upcoming_changes/action/track_status_changes_spec.rbnew file mode 100644index 00000000000..fc6ba4d3c03--- /dev/null+++ b/spec/services/upcoming_changes/action/track_status_changes_spec.rb@@ -0,0 +1,318 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::Action::TrackStatusChanges do+ let(:enable_upload_debug_mode_status) { :experimental }+ let(:show_user_menu_avatars_status) { :beta }++ before do+ mock_upcoming_change_metadata(+ {+ enable_upload_debug_mode: {+ impact: "other,developers",+ status: enable_upload_debug_mode_status,+ impact_type: "other",+ impact_role: "developers",+ },+ show_user_menu_avatars: {+ impact: "feature,all_members",+ status: show_user_menu_avatars_status,+ impact_type: "feature",+ impact_role: "all_members",+ },+ },+ )+ end++ def scoped_events+ UpcomingChangeEvent.where(+ upcoming_change_name: %i[enable_upload_debug_mode show_user_menu_avatars],+ )+ end++ fab!(:admin_1, :admin)+ fab!(:admin_2, :admin)+ let(:added_changes) { [] }+ let(:removed_changes) { [] }++ describe ".call" do+ subject(:result) do+ described_class.call(all_admins: [admin_1, admin_2], added_changes:, removed_changes:)+ end++ before do+ scoped_events.where(event_type: :status_changed).delete_all+ scoped_events.where(event_type: :added).delete_all+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :enable_upload_debug_mode,+ )+ UpcomingChangeEvent.create!(event_type: :added, upcoming_change_name: :show_user_menu_avatars)+ end++ context "when there are no previous status changes" do+ it "creates a status_changed event for the current status" do+ expect { result }.to change { scoped_events.where(event_type: :status_changed).count }.by(2)+ end++ it "sets previous_value to nil in the event data" do+ result+ event =+ scoped_events.find_by(+ event_type: :status_changed,+ upcoming_change_name: :enable_upload_debug_mode,+ )+ expect(event.event_data["previous_value"]).to be_nil+ end++ it "sets new_value to the current status in the event data" do+ result+ event =+ scoped_events.find_by(+ event_type: :status_changed,+ upcoming_change_name: :enable_upload_debug_mode,+ )+ expect(event.event_data["new_value"]).to eq("experimental")+ end++ it "returns N/A as previous_value in the result" do+ expect(result[:status_changes][:enable_upload_debug_mode]).to eq(+ { previous_value: "N/A", new_value: :experimental },+ )+ end+ end++ context "when there are added changes in the same run" do+ let(:added_changes) { [:enable_upload_debug_mode] }++ before do+ scoped_events.where(event_type: :added).delete_all+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :enable_upload_debug_mode,+ event_data: {+ "previous_value" => nil,+ "new_value" => "alpha",+ },+ )+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :show_user_menu_avatars,+ event_data: {+ "previous_value" => nil,+ "new_value" => "beta",+ },+ )+ end++ it "does not create additional status change events for added changes" do+ expect { result }.not_to change {+ scoped_events.where(+ event_type: :status_changed,+ upcoming_change_name: :enable_upload_debug_mode,+ ).count+ }+ end+ end++ context "when there are removed changes in the same run" do+ let(:removed_changes) { [:old_removed_change] }++ before do+ UpcomingChangeEvent.create!(event_type: :added, upcoming_change_name: :old_removed_change)+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :old_removed_change,+ event_data: {+ "previous_value" => nil,+ "new_value" => "beta",+ },+ )+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :enable_upload_debug_mode,+ event_data: {+ "previous_value" => nil,+ "new_value" => "experimental",+ },+ )+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :show_user_menu_avatars,+ event_data: {+ "previous_value" => nil,+ "new_value" => "beta",+ },+ )+ end++ it "does not create a status change event for removed changes" do+ expect { result }.not_to change {+ UpcomingChangeEvent.where(+ event_type: :status_changed,+ upcoming_change_name: :old_removed_change,+ ).count+ }+ end+ end++ context "when the status has changed from a previous value" do+ let(:show_user_menu_avatars_status) { :stable }++ before do+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :show_user_menu_avatars,+ event_data: {+ "previous_value" => nil,+ "new_value" => "beta",+ },+ )+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :enable_upload_debug_mode,+ event_data: {+ "previous_value" => nil,+ "new_value" => "experimental",+ },+ )+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :show_user_menu_avatars,+ )+ end++ it "creates a status_changed event with correct data" do+ expect { result }.to change {+ scoped_events.where(+ event_type: :status_changed,+ upcoming_change_name: :show_user_menu_avatars,+ ).count+ }.by(1)+ end++ it "records the previous and new status values" do+ result+ result+ expect(+ scoped_events+ .where(event_type: :status_changed, upcoming_change_name: :show_user_menu_avatars)+ .order(:created_at)+ .last,+ ).to have_attributes(event_data: { "previous_value" => "beta", "new_value" => "stable" })+ end++ it "returns the status change in the result" do+ expect(result[:status_changes][:show_user_menu_avatars]).to eq(+ { previous_value: "beta", new_value: :stable },+ )+ end+ end++ context "when status has not changed" do+ let(:show_user_menu_avatars_status) { :beta }++ before do+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :show_user_menu_avatars,+ event_data: {+ "previous_value" => nil,+ "new_value" => "beta",+ },+ )+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :enable_upload_debug_mode,+ event_data: {+ "previous_value" => nil,+ "new_value" => "experimental",+ },+ )+ end++ it "does not create a new status_changed event" do+ expect { result }.not_to change { scoped_events.where(event_type: :status_changed).count }+ end+ end++ context "when an added change did not meet promotion_status - 1 initially" do+ let(:show_user_menu_avatars_status) { :beta }++ before do+ SiteSetting.promote_upcoming_changes_on_status = "stable"+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :show_user_menu_avatars,+ event_data: {+ "previous_value" => nil,+ "new_value" => "alpha",+ },+ )+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :enable_upload_debug_mode,+ event_data: {+ "previous_value" => nil,+ "new_value" => "experimental",+ },+ )+ end++ it "notifies all admins when status now meets threshold" do+ expect { result }.to change {+ Notification+ .where(+ notification_type: Notification.types[:upcoming_change_available],+ user_id: [admin_1.id, admin_2.id],+ )+ .where("data::text LIKE ?", "%show_user_menu_avatars%")+ .count+ }.by(2)+ end++ it "creates an admins_notified_available_change event" do+ expect { result }.to change {+ scoped_events.where(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :show_user_menu_avatars,+ ).count+ }.by(1)+ end++ it "includes the change in notified_changes" do+ expect(result[:notified_changes]).to include(:show_user_menu_avatars)+ end++ it "creates a UserHistory entry for the upcoming change" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:upcoming_change_available],+ subject: "show_user_menu_avatars",+ ).count+ }.by(1)+ end++ context "when admins were already notified" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :show_user_menu_avatars,+ )+ end++ it "does not notify admins again" do+ expect { result }.not_to change {+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .where("data::text LIKE ?", "%show_user_menu_avatars%")+ .count+ }+ end++ it "does not include the change in notified_changes" do+ expect(result[:notified_changes]).not_to include(:show_user_menu_avatars)+ end+ end+ end+ end+enddiff --git a/spec/services/upcoming_changes/list_spec.rb b/spec/services/upcoming_changes/list_spec.rbindex 4ac9301fceb..4b782eedd46 100644--- a/spec/services/upcoming_changes/list_spec.rb+++ b/spec/services/upcoming_changes/list_spec.rb@@ -130,6 +130,36 @@ RSpec.describe UpcomingChanges::List doexpect(mock_setting[:upcoming_change][:enabled_for]).to eq("groups")endend++ it "updates the user's last_visited_upcoming_changes_at custom field" do+ expect { result }.to change {+ admin.reload.custom_fields["last_visited_upcoming_changes_at"]+ }.to be_present+ expect(+ Time.zone.parse(admin.custom_fields["last_visited_upcoming_changes_at"]),+ ).to be_within(1.minute).of(Time.current)+ end++ context "when guardian is the system user" do+ let(:guardian) { Discourse.system_user.guardian }++ it "does not update the custom field" do+ expect { result }.not_to change {+ Discourse.system_user.reload.custom_fields["last_visited_upcoming_changes_at"]+ }+ end+ end++ context "when guardian is a bot" do+ fab!(:bot)+ let(:guardian) { bot.guardian }++ it "does not update the custom field" do+ expect { result }.not_to change {+ bot.reload.custom_fields["last_visited_upcoming_changes_at"]+ }+ end+ endendendenddiff --git a/spec/services/upcoming_changes/promote_spec.rb b/spec/services/upcoming_changes/promote_spec.rbindex a00d3f0e05a..0d25392d2c9 100644--- a/spec/services/upcoming_changes/promote_spec.rb+++ b/spec/services/upcoming_changes/promote_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe UpcomingChanges::Promote do- describe described_class::Contract, type: :model do+ describe UpcomingChanges::Promote::Contract, type: :model dosubject(:contract) { described_class.new }it { is_expected.to validate_presence_of(:setting_name) }@@ -102,6 +102,8 @@ RSpec.describe UpcomingChanges::Promote doendcontext "when everything is ok" do+ fab!(:admin_2, :admin)+let(:promotion_status_threshold) { :beta }it { is_expected.to run_successfully }@@ -126,6 +128,31 @@ RSpec.describe UpcomingChanges::Promote do),)end++ it "notifies admins about the upcoming change" do+ expect { result }.to change {+ Notification.where(+ notification_type: Notification.types[:upcoming_change_automatically_promoted],+ user_id: [admin.id, admin_2.id],+ ).count+ }.by(2)++ expect(Notification.last.data).to eq(+ {+ upcoming_change_name: :enable_upload_debug_mode,+ upcoming_change_humanized_name: "Enable upload debug mode",+ }.to_json,+ )+ end++ it "creates an admins_notified_automatic_promotion event" do+ expect { result }.to change {+ UpcomingChangeEvent.where(+ event_type: :admins_notified_automatic_promotion,+ upcoming_change_name: :enable_upload_debug_mode,+ ).count+ }.by(1)+ endendendenddiff --git a/spec/services/upcoming_changes/toggle_spec.rb b/spec/services/upcoming_changes/toggle_spec.rbindex dac0ecaa1b5..15106878c30 100644--- a/spec/services/upcoming_changes/toggle_spec.rb+++ b/spec/services/upcoming_changes/toggle_spec.rb@@ -1,18 +1,19 @@# frozen_string_literal: trueRSpec.describe UpcomingChanges::Toggle do- describe described_class::Contract, type: :model do+ describe UpcomingChanges::Toggle::Contract, type: :model doit { is_expected.to validate_presence_of :setting_name }enddescribe ".call" do- subject(:result) { described_class.call(params:, **dependencies) }+ subject(:result) { described_class.call(params:, **dependencies, options:) }fab!(:admin)let(:params) { { setting_name:, enabled: } }let(:enabled) { true }let(:setting_name) { :experimental_form_templates }let(:dependencies) { { guardian: } }+ let(:options) { {} }let(:guardian) { admin.guardian }context "when data is invalid" do@@ -36,49 +37,227 @@ RSpec.describe UpcomingChanges::Toggle docontext "when everything's ok" doit { is_expected.to run_successfully }- context "when the setting is enabled" do- let(:enabled) { false }+ context "when enable_upcoming_changes is disabled" do+ context "when log_change is true" do+ let(:options) { { log_change: true } }- before { SiteSetting.experimental_form_templates = true }+ context "when enabling the setting" do+ let(:enabled) { true }- it "disables the specified setting" do- expect { result }.to change { SiteSetting.experimental_form_templates }.to(false)- end- end+ before { SiteSetting.experimental_form_templates = false }++ it "enables the specified setting" do+ expect { result }.to change { SiteSetting.experimental_form_templates }.to(true)+ end++ it "creates an entry in the staff action logs" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:change_site_setting],+ subject: "experimental_form_templates",+ ).count+ }.by(1)+ end++ it "does not create an UpcomingChangeEvent" do+ expect { result }.not_to change { UpcomingChangeEvent.count }+ end+ end++ context "when disabling the setting" do+ let(:enabled) { false }- context "when the setting is disabled" do- let(:enabled) { true }+ before { SiteSetting.experimental_form_templates = true }- before { SiteSetting.experimental_form_templates = false }+ it "disables the specified setting" do+ expect { result }.to change { SiteSetting.experimental_form_templates }.to(false)+ end- it "enables the specified setting" do- expect { result }.to change { SiteSetting.experimental_form_templates }.to(true)+ it "creates an entry in the staff action logs" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:change_site_setting],+ subject: "experimental_form_templates",+ ).count+ }.by(1)+ end++ it "does not create an UpcomingChangeEvent" do+ expect { result }.not_to change { UpcomingChangeEvent.count }+ end+ endend- end- it "creates an entry in the staff action logs" do- expect { result }.to change {- UserHistory.where(- action: UserHistory.actions[:change_site_setting],- subject: "experimental_form_templates",- ).count- }.by(1)+ context "when log_change is false" do+ let(:options) { { log_change: false } }++ context "when enabling the setting" do+ let(:enabled) { true }++ before { SiteSetting.experimental_form_templates = false }++ it "enables the specified setting" do+ expect { result }.to change { SiteSetting.experimental_form_templates }.to(true)+ end++ it "does not create an entry in the staff action logs" do+ expect { result }.not_to change {+ UserHistory.where(+ action: UserHistory.actions[:change_site_setting],+ subject: "experimental_form_templates",+ ).count+ }+ end++ it "does not create an UpcomingChangeEvent" do+ expect { result }.not_to change { UpcomingChangeEvent.count }+ end+ end++ context "when disabling the setting" do+ let(:enabled) { false }++ before { SiteSetting.experimental_form_templates = true }++ it "disables the specified setting" do+ expect { result }.to change { SiteSetting.experimental_form_templates }.to(false)+ end++ it "does not create an entry in the staff action logs" do+ expect { result }.not_to change {+ UserHistory.where(+ action: UserHistory.actions[:change_site_setting],+ subject: "experimental_form_templates",+ ).count+ }+ end++ it "does not create an UpcomingChangeEvent" do+ expect { result }.not_to change { UpcomingChangeEvent.count }+ end+ end+ endendcontext "when enable_upcoming_changes is enabled" dobefore { SiteSetting.enable_upcoming_changes = true }- it "creates an entry in the staff action logs with correct context" do- expect { result }.to change {- UserHistory.where(- action: UserHistory.actions[:upcoming_change_toggled],- subject: "experimental_form_templates",- ).count- }.by(1)-- expect(UserHistory.last.context).to eq(- I18n.t("staff_action_logs.upcoming_changes.log_manually_toggled"),- )+ context "when log_change is true" do+ let(:options) { { log_change: true } }++ context "when enabling the setting" do+ let(:enabled) { true }++ before { SiteSetting.experimental_form_templates = false }++ it "enables the specified setting" do+ expect { result }.to change { SiteSetting.experimental_form_templates }.to(true)+ end++ it "creates an entry in the staff action logs with correct context" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:upcoming_change_toggled],+ subject: "experimental_form_templates",+ ).count+ }.by(1)++ expect(UserHistory.last.context).to eq(+ I18n.t("staff_action_logs.upcoming_changes.log_manually_toggled"),+ )+ end++ it "creates an UpcomingChangeEvent with manual_opt_in event_type" do+ expect { result }.to change {+ UpcomingChangeEvent.where(+ event_type: :manual_opt_in,+ upcoming_change_name: "experimental_form_templates",+ ).count+ }.by(1)+ end+ end++ context "when disabling the setting" do+ let(:enabled) { false }++ before { SiteSetting.experimental_form_templates = true }++ it "disables the specified setting" do+ expect { result }.to change { SiteSetting.experimental_form_templates }.to(false)+ end++ it "creates an entry in the staff action logs with correct context" do+ expect { result }.to change {+ UserHistory.where(+ action: UserHistory.actions[:upcoming_change_toggled],+ subject: "experimental_form_templates",+ ).count+ }.by(1)++ expect(UserHistory.last.context).to eq(+ I18n.t("staff_action_logs.upcoming_changes.log_manually_toggled"),+ )+ end++ it "creates an UpcomingChangeEvent with manual_opt_out event_type" do+ expect { result }.to change {+ UpcomingChangeEvent.where(+ event_type: :manual_opt_out,+ upcoming_change_name: "experimental_form_templates",+ ).count+ }.by(1)+ end+ end+ end++ context "when log_change is false" do+ let(:options) { { log_change: false } }++ context "when enabling the setting" do+ let(:enabled) { true }++ before { SiteSetting.experimental_form_templates = false }++ it "enables the specified setting" do+ expect { result }.to change { SiteSetting.experimental_form_templates }.to(true)+ end++ it "does not create an entry in the staff action logs" do+ expect { result }.not_to change {+ UserHistory.where(+ action: UserHistory.actions[:upcoming_change_toggled],+ subject: "experimental_form_templates",+ ).count+ }+ end++ it "does not create an UpcomingChangeEvent" do+ expect { result }.not_to change { UpcomingChangeEvent.count }+ end+ end++ context "when disabling the setting" do+ let(:enabled) { false }++ before { SiteSetting.experimental_form_templates = true }++ it "disables the specified setting" do+ expect { result }.to change { SiteSetting.experimental_form_templates }.to(false)+ end++ it "does not create an entry in the staff action logs" do+ expect { result }.not_to change {+ UserHistory.where(+ action: UserHistory.actions[:upcoming_change_toggled],+ subject: "experimental_form_templates",+ ).count+ }+ end++ it "does not create an UpcomingChangeEvent" do+ expect { result }.not_to change { UpcomingChangeEvent.count }+ end+ endendendenddiff --git a/spec/services/upcoming_changes/track_spec.rb b/spec/services/upcoming_changes/track_spec.rbnew file mode 100644index 00000000000..0ba241161f8--- /dev/null+++ b/spec/services/upcoming_changes/track_spec.rb@@ -0,0 +1,68 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::Track do+ fab!(:admin_1, :admin)+ fab!(:admin_2, :admin)++ let(:all_admins) { [admin_1, admin_2] }++ describe ".call" do+ subject(:result) { described_class.call(all_admins:) }++ let(:added_changes_result) do+ { added_changes: [:added_change], notified_changes: [:notified_added] }+ end++ let(:removed_changes_result) { [:removed_change] }++ let(:status_changes_result) do+ { status_changes: { status_change: :data }, notified_changes: [:notified_status] }+ end++ before do+ allow(UpcomingChanges::Action::TrackAddedChanges).to receive(:call).and_return(+ added_changes_result,+ )+ allow(UpcomingChanges::Action::TrackRemovedChanges).to receive(:call).and_return(+ removed_changes_result,+ )+ allow(UpcomingChanges::Action::TrackStatusChanges).to receive(:call).and_return(+ status_changes_result,+ )+ end++ it "runs successfully" do+ expect(result).to run_successfully+ end++ it "calls TrackAddedChanges with correct arguments" do+ result+ expect(UpcomingChanges::Action::TrackAddedChanges).to have_received(:call).with(all_admins:)+ end++ it "calls TrackRemovedChanges" do+ result+ expect(UpcomingChanges::Action::TrackRemovedChanges).to have_received(:call)+ end++ it "calls TrackStatusChanges with correct arguments" do+ result+ expect(UpcomingChanges::Action::TrackStatusChanges).to have_received(:call).with(+ all_admins:,+ added_changes: [:added_change],+ removed_changes: [:removed_change],+ )+ end++ it "populates the context with results from actions" do+ expect(result).to have_attributes(+ added_changes: [:added_change],+ removed_changes: [:removed_change],+ status_changes: {+ status_change: :data,+ },+ notified_admins_for_added_changes: %i[notified_added notified_status],+ )+ end+ end+enddiff --git a/spec/system/admin_upcoming_changes_spec.rb b/spec/system/admin_upcoming_changes_spec.rbindex a3790d20aef..d484818bd9a 100644--- a/spec/system/admin_upcoming_changes_spec.rb+++ b/spec/system/admin_upcoming_changes_spec.rb@@ -195,4 +195,40 @@ describe "Admin upcoming changes", type: :system doupcoming_changes_page.filter_controls.select_all_dropdown_option(dropdown_id: "enabled")end++ it "displays a notification dot on the sidebar and clears it when navigating to upcoming changes" do+ sidebar = PageObjects::Components::NavigationMenu::Sidebar.new++ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: "enable_upload_debug_mode",+ )++ visit "/admin"+ sidebar.toggle_all_sections++ expect(sidebar.find_section_link("admin_upcoming_changes")).to have_css(+ ".sidebar-section-link-suffix.admin-sidebar-nav-link__dot",+ )++ sidebar.find_section_link("admin_upcoming_changes").click++ expect(sidebar.find_section_link("admin_upcoming_changes")).to have_no_css(+ ".sidebar-section-link-suffix.admin-sidebar-nav-link__dot",+ )+ end++ it "does not display a notification dot when there are no new added events" do+ sidebar = PageObjects::Components::NavigationMenu::Sidebar.new++ current_user.custom_fields["last_visited_upcoming_changes_at"] = Time.current.iso8601+ current_user.save_custom_fields++ visit "/admin"+ sidebar.toggle_all_sections++ expect(sidebar.find_section_link("admin_upcoming_changes")).to have_no_css(+ ".sidebar-section-link-suffix.admin-sidebar-nav-link__dot",+ )+ endend