A platform for community discussion. Free, open, simple.
FEATURE: Change upcoming change available notification cadence (#40157)
Martin Brennan02edc8a05b07
diff --git a/.skills/discourse-upcoming-changes-authoring/SKILL.md b/.skills/discourse-upcoming-changes-authoring/SKILL.mdindex d8defab8483..21a65f8a11b 100644--- a/.skills/discourse-upcoming-changes-authoring/SKILL.md+++ b/.skills/discourse-upcoming-changes-authoring/SKILL.md@@ -20,7 +20,7 @@ Key methods to understand:- `resolved_value(setting_name)` — Determines the *effective* value of a setting. This is where auto-promotion logic lives: if a setting's status meets/exceeds `promote_upcoming_changes_on_status`, the resolved value is `true` even if the DB default is `false`. Permanent settings always resolve to `true` (admins can't disable them).- `enabled_for_user?(setting_name, user)` — The primary access check. Considers: resolved value, group restrictions, anonymous users (only get access if no group restrictions).- `stats_for_user(user:, acting_guardian:)` — Returns per-change status for a user including *why* they have/don't have access (the `user_enabled_reasons` enum).-- `current_statuses` / `permanent_upcoming_changes` — Cached lookups keyed by git version (one-time cost per deploy). Cleared by `clear_caches!` and automatically when `TrackNotifyStatusChanges` detects changes.+- `current_statuses` / `permanent_upcoming_changes` — Cached lookups keyed by git version (one-time cost per deploy). Cleared by `clear_caches!` and automatically when `TrackStatusChanges` detects changes.**`UpcomingChanges::ConditionalDisplay`** (defined inside `lib/upcoming_changes.rb`) — Hides individual upcoming changes from the admin UI when they don't make sense in the current context (e.g. a Horizon-related change on a site without Horizon installed). Define a `should_display_<upcoming_change_name>?` class method on it to gate a specific change; if no method is defined, the change is always displayed. See [Conditional Display](#conditional-display) below.@@ -40,20 +40,21 @@ All services use `Service::Base`. They're organized under `app/services/upcoming|---------|---------|| `List` | Admin-only, fetches all changes with metadata, group data, and images. Filters out changes whose `ConditionalDisplay.should_display?` returns false. || `Toggle` | Admin enable/disable — updates SiteSetting, clears groups when neither `staff` nor `specific_groups` is in `allow_enabled_for`, validates the requested target against `allow_enabled_for`, logs staff action, fires DiscourseEvent |-| `Track` | Orchestrator called by the scheduled job — delegates to three action sub-services |-| `TrackNotifyAddedChanges` | Compares current settings against event history, creates `added` events |+| `Track` | Orchestrator called by `CheckUpcomingChanges` — delegates to three action sub-services. Does not notify admins about available changes — that happens once a week in `Jobs::NotifyAdminsOfAvailableUpcomingChanges`. |+| `TrackAddedChanges` | Compares current settings against event history, creates `added` events || `TrackRemovedChanges` | Creates `removed` events for settings no longer present |-| `TrackNotifyStatusChanges` | Detects status changes in metadata, creates events, clears caches |+| `TrackStatusChanges` | Detects status changes in metadata, creates events, clears caches || `NotifyPromotions` | Iterates all changes and calls `NotifyPromotion` for each || `NotifyPromotion` | Handles one promotion — checks policies, merges notifications, fires events |-| `NotifyAdminsOfAvailableChange` | Notifies admins when a change reaches one status below promotion threshold |-| `NotificationDataMerger` | Consolidates multiple change notifications into one to avoid spam |+| `NotificationDataMerger` | Consolidates multiple change notifications into one to avoid spam (used by both the weekly availability job and `NotifyPromotion`) |**`SiteSetting::UpsertGroups`** — Manages group assignments for settings (upserts `SiteSettingGroup`, refreshes caches, notifies clients).-### Scheduled Job+### Scheduled Jobs-**`app/jobs/scheduled/check_upcoming_changes.rb`** — Runs every 20 minutes inside a `DistributedMutex`. Calls `Track` then `NotifyPromotions`. Supports verbose logging via the `upcoming_change_verbose_logging` setting.+**`app/jobs/scheduled/check_upcoming_changes.rb`** — Runs every 20 minutes inside a `DistributedMutex`. Calls `Track` (to log `added`/`removed`/`status_changed` events) then `NotifyPromotions` (which sends auto-promotion notifications immediately). Supports verbose logging via the `upcoming_change_verbose_logging` setting. **Does not** send "change available" notifications to admins — that is the weekly job below.++**`app/jobs/scheduled/notify_admins_of_available_upcoming_changes.rb`** — Runs once a week. Collects every change that was either `added` at, or status-changed *to*, `promote_upcoming_changes_on_status - 1` within the last week and has no prior `admins_notified_available_change` or `admins_notified_automatic_promotion` event. Notifies all admins who have `enable_upcoming_change_available_notifications` enabled, consolidating into a single notification per admin via `NotificationDataMerger` (merging with existing unread notifications if present, otherwise creating one new notification per admin covering all newly-available changes). Gated on `UpcomingChanges.should_notify_admins?` so new sites are suppressed. Writes `admins_notified_available_change` events and a `log_upcoming_change_available` staff log entry per change.### Frontend@@ -144,13 +145,13 @@ Some upcoming changes only make sense to show admins under certain conditions- **Display-only**: This affects whether the change appears in the admin UI list, not whether it's enabled. `enabled?` / `enabled_for_user?` still resolve normally — code paths gated on the change continue to work.- **N+1 by design**: `should_display?` is called once per change in the loop. If a gating method does expensive work (DB queries, plugin lookups), memoize inside the method to avoid repeated cost.-- **Notifications still fire**: Conditional display only filters the `List` service result. `TrackNotifyAddedChanges`, `NotifyPromotions`, etc. do not consult `ConditionalDisplay`, so admins may still receive notifications about a hidden change. Consider this when designing the gate — usually the gate should reflect a long-lived condition (plugin missing, theme not installed) rather than transient state.+- **Notifications still fire**: Conditional display only filters the `List` service result. `TrackAddedChanges`, `NotifyAdminsOfAvailableUpcomingChanges`, `NotifyPromotions`, etc. do not consult `ConditionalDisplay`, so admins may still receive notifications about a hidden change. Consider this when designing the gate — usually the gate should reflect a long-lived condition (plugin missing, theme not installed) rather than transient state.## Key Design Decisions### Caching Strategy-The `current_statuses` and `permanent_upcoming_changes` caches are keyed by git version (`Discourse.git_version`). This means they're naturally invalidated on every deploy — no TTL needed. Within a deploy, `TrackNotifyStatusChanges` calls `clear_caches!` when it detects metadata changes. Always call `clear_caches!` in tests after modifying metadata.+The `current_statuses` and `permanent_upcoming_changes` caches are keyed by git version (`Discourse.git_version`). This means they're naturally invalidated on every deploy — no TTL needed. Within a deploy, `TrackStatusChanges` calls `clear_caches!` when it detects metadata changes. Always call `clear_caches!` in tests after modifying metadata.### Auto-Promotion@@ -160,9 +161,11 @@ The `resolved_value` method is the single source of truth for whether a settingWhen multiple changes need notifications, `NotificationDataMerger` consolidates them into a single notification per admin. It finds existing unread notifications and merges the change names array. The frontend notification types handle singular ("Feature X"), dual ("Feature X and Feature Y"), and many ("Feature X and 2 others") display.+For "change available" notifications specifically, merging also happens across the *batch* processed by the weekly `NotifyAdminsOfAvailableUpcomingChanges` job — for admins without an existing unread notification, the job builds a single new notification per admin that lists every newly-available change in that run, rather than emitting one notification per change.+### New Site Notification Suppression-Notifications for `added` and `promoted` changes are skipped on new sites (determined by `Migration::Helpers.new_site?` in `lib/migration/helpers.rb` — a site is "new" if its first schema migration was less than 1 hour ago). This prevents freshly provisioned sites from being flooded with notifications for every existing upcoming change on their first run. The tracking/detection steps still execute — only the notification delivery is suppressed.+Notifications for "change available" and "promoted" are skipped on new sites (determined by `Migration::Helpers.new_site?` in `lib/migration/helpers.rb` — a site is "new" if its first schema migration was less than 1 hour ago). Both the weekly `NotifyAdminsOfAvailableUpcomingChanges` job and the `NotifyPromotion` service guard on `UpcomingChanges.should_notify_admins?`. This prevents freshly provisioned sites from being flooded with notifications for every existing upcoming change on their first run. The tracking/detection steps still execute — only the notification delivery is suppressed.### Group-Based Access@@ -406,7 +409,7 @@ Notification type tests create notifications with `Notification.create()` and ve| Services | `app/services/upcoming_changes/*.rb` || Group upsert | `app/services/site_setting/upsert_groups.rb` || Controller | `admin/config/upcoming_changes_controller.rb` |-| Scheduled job | `app/jobs/scheduled/check_upcoming_changes.rb` |+| Scheduled jobs | `app/jobs/scheduled/check_upcoming_changes.rb`, `app/jobs/scheduled/notify_admins_of_available_upcoming_changes.rb` || Problem check | `app/services/problem_check/upcoming_change_stable_opted_out.rb` || Initializer | `config/initializers/015-track-upcoming-change-toggle.rb` || Admin page | `admin/templates/admin-config/upcoming-changes.gjs` |@@ -423,7 +426,7 @@ Notification type tests create notifications with `Notification.create()` and ve| Request spec | `spec/requests/admin/config/upcoming_changes_controller_spec.rb` || Admin system spec | `spec/system/admin_upcoming_changes_spec.rb` || Member system spec | `spec/system/member_upcoming_changes_spec.rb` |-| Job spec | `spec/jobs/scheduled/check_upcoming_changes_spec.rb` |+| Job specs | `spec/jobs/scheduled/check_upcoming_changes_spec.rb`, `spec/jobs/scheduled/notify_admins_of_available_upcoming_changes_spec.rb` || Multisite spec | `spec/multisite/upcoming_changes_spec.rb` || Page objects | `spec/system/page_objects/pages/admin_upcoming_changes.rb`, `admin_upcoming_change_item.rb` || Test helpers | `spec/support/helpers.rb` (search for `mock_upcoming_change_metadata`) |diff --git a/app/jobs/scheduled/check_upcoming_changes.rb b/app/jobs/scheduled/check_upcoming_changes.rbindex 0e85d0d2ded..4be752d94a9 100644--- a/app/jobs/scheduled/check_upcoming_changes.rb+++ b/app/jobs/scheduled/check_upcoming_changes.rb@@ -25,21 +25,16 @@ module Jobsprivate+ # Note that we do not notify admins about new upcoming changes,+ # or those that reach promotion status - 1, inline in this service.+ # That only happens once a week in Jobs::NotifyAdminsOfAvailableUpcomingChangesdef track_changes(site)UpcomingChanges::Track.call(guardian: Discourse.system_user.guardian) do |result|- on_success do |added_changes:, removed_changes:, notified_admins_for_added_changes:, status_changes:|+ on_success do |added_changes:, removed_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}'")enddiff --git a/app/jobs/scheduled/notify_admins_of_available_upcoming_changes.rb b/app/jobs/scheduled/notify_admins_of_available_upcoming_changes.rbnew file mode 100644index 00000000000..4a65887209a--- /dev/null+++ b/app/jobs/scheduled/notify_admins_of_available_upcoming_changes.rb@@ -0,0 +1,197 @@+# frozen_string_literal: true++module Jobs+ # This job runs weekly to collect all of the available upcoming+ # changes (i.e. those which are promotion status - 1) that we+ # should be notifying all site admins about.+ #+ # This will pick up changes that were:+ #+ # * Added in the last week, if they were added at the same status+ # as promotion status - 1+ # * Changed status to promotion status - 1 in the last week+ #+ # We do not send a notification per change, this would be too many+ # for admins.+ #+ # * For admins who have an existing "upcoming change available" notification+ # that is _unread_, we merge the notification data with any additional+ # upcoming change data. We delete all the old unread notifications,+ # and create a new one per admin instead.+ # * For admins who did not have an existing unread notification, we create+ # a single notification for all available upcoming changes, rather than+ # individual notifications for each change, which could potentially be+ # a lot.+ class NotifyAdminsOfAvailableUpcomingChanges < ::Jobs::Scheduled+ every 1.week++ def execute(args)+ return if !UpcomingChanges.should_notify_admins?+ return if eligible_admins.empty?+ return if upcoming_changes_to_notify.empty?++ existing_notifications =+ Notification.where(+ notification_type: Notification.types[:upcoming_change_available],+ user_id: eligible_admins.map(&:id),+ read: false,+ )+ existing_notification_data_by_user =+ existing_notifications.to_a.index_by(&:user_id).transform_values(&:data)+ new_notification_data_by_user = {}++ bulk_notified_event_new_records = []++ now = Time.zone.now+ upcoming_changes_to_notify.each do |upcoming_change|+ eligible_admins.each do |admin|+ # By setting this to nil, we are indicating the admin doesn't+ # have any existing unread change notification, so the merger+ # just uses the first upcoming change to begin with, then it+ # continues to merge/collect more notifications in this run.+ #+ # This way we can avoid sending multiple notifications per new change+ # to each admin, instead consolidating them into one per admin,+ # while also updating existing unread notifications for admins that+ # have them.+ unless existing_notification_data_by_user.key?(admin.id)+ new_notification_data_by_user[admin.id] ||= nil+ end++ data =+ UpcomingChanges::Action::NotificationDataMerger.call(+ existing_notification_data:+ existing_notification_data_by_user[admin.id] ||+ new_notification_data_by_user[admin.id],+ new_change_name: upcoming_change,+ )++ if existing_notification_data_by_user.key?(admin.id)+ existing_notification_data_by_user[admin.id] = data.to_json+ else+ new_notification_data_by_user[admin.id] = data.to_json+ end+ end++ bulk_notified_event_new_records << {+ event_type: UpcomingChangeEvent.event_types[:admins_notified_available_change],+ upcoming_change_name: upcoming_change,+ created_at: now,+ updated_at: now,+ }+ end++ UpcomingChangeEvent.transaction do+ existing_notifications.presence&.delete_all+ Notification::Action::BulkCreate.call(+ records:+ new_notification_data_by_user+ .merge(existing_notification_data_by_user)+ .map do |admin_id, notification_data|+ {+ user_id: admin_id,+ notification_type: Notification.types[:upcoming_change_available],+ data: notification_data,+ }+ end,+ # NOTE: There isn't an email notification for this notification type,+ # but we will keep this skip param here just as a precaution. If we+ # do decide to add one, we should split this into two separate calls,+ # one for the existing notifications and one for the new notifications,+ # the former of which should have skip_send_email set to true.+ skip_send_email: true,+ )+ UpcomingChangeEvent.insert_all(bulk_notified_event_new_records)++ action_logger = StaffActionLogger.new(Discourse.system_user)+ upcoming_changes_to_notify.each do |upcoming_change|+ action_logger.log_upcoming_change_available(upcoming_change)+ end+ end+ end++ private++ # Since we only notify admins on promote_upcoming_changes_on_status - 1 (e.g.+ # Beta on promote_upcoming_changes_on_status Stable sites), we sometimes have+ # a gap between when we log that the the upcoming change is Added to the+ # site, and when the status changed to promote_upcoming_changes_on_status - 1.+ #+ # Something like:+ #+ # * 2026-04-01 - Change added, status is Experimental+ # * 2026-04-10 - Change moved to Alpha+ # * 2026-04-30 - Change moved to Beta (promote_upcoming_changes_on_status - 1)+ #+ # We only notify admins of the change being available for preview on the last date,+ # not the first. We will know if one of these gaps exist because the Added+ # event will exist, but not the "Admins notified available change" event.+ #+ # We also don't notify admins if we already sent them a notification about the+ # change being auto-promoted, which should be very rare case but we still need to+ # handle it.+ def upcoming_changes_to_notify+ @upcoming_changes_to_notify ||=+ DB.query_single(+ <<~SQL,+ SELECT DISTINCT eligible.upcoming_change_name+ FROM (+ SELECT upcoming_change_name+ FROM upcoming_change_events+ WHERE event_type = :added+ AND created_at >= :since+ AND upcoming_change_name IN (:upcoming_changes_meeting_notify_status)++ UNION++ SELECT latest_status.upcoming_change_name+ FROM (+ SELECT DISTINCT ON (upcoming_change_name)+ upcoming_change_name,+ event_data->>'new_value' AS new_value,+ created_at+ FROM upcoming_change_events+ WHERE event_type = :status_changed+ ORDER BY upcoming_change_name, created_at DESC, id DESC+ ) latest_status+ WHERE latest_status.new_value = :promotion_status_minus_one+ AND latest_status.created_at >= :since+ AND latest_status.upcoming_change_name IN (:upcoming_changes_meeting_notify_status)+ ) eligible+ WHERE NOT EXISTS (+ SELECT 1+ FROM upcoming_change_events notified+ WHERE notified.upcoming_change_name = eligible.upcoming_change_name+ AND (notified.event_type = :admins_notified_available_change+ OR notified.event_type = :admins_notified_automatic_promotion)+ )+ SQL+ added: UpcomingChangeEvent.event_types[:added],+ admins_notified_available_change:+ UpcomingChangeEvent.event_types[:admins_notified_available_change],+ admins_notified_automatic_promotion:+ UpcomingChangeEvent.event_types[:admins_notified_automatic_promotion],+ status_changed: UpcomingChangeEvent.event_types[:status_changed],+ promotion_status_minus_one:+ UpcomingChanges.previous_status(SiteSetting.promote_upcoming_changes_on_status).to_s,+ since: 1.week.ago,+ upcoming_changes_meeting_notify_status:+ SiteSetting.upcoming_change_site_settings.filter do |upcoming_change_name|+ UpcomingChanges.meets_or_exceeds_status?(+ upcoming_change_name,+ UpcomingChanges.previous_status(SiteSetting.promote_upcoming_changes_on_status),+ )+ end,+ )+ end++ def eligible_admins+ @eligible_admins ||=+ User+ .human_users+ .admins+ .joins(:user_option)+ .where(user_options: { enable_upcoming_change_available_notifications: true })+ end+ end+enddiff --git a/app/services/upcoming_changes/action/notification_data_merger.rb b/app/services/upcoming_changes/action/notification_data_merger.rbindex 7df6044f920..65756717d24 100644--- a/app/services/upcoming_changes/action/notification_data_merger.rb+++ b/app/services/upcoming_changes/action/notification_data_merger.rb@@ -1,18 +1,20 @@# frozen_string_literal: true-# Consolidates upcoming change notification data for both available and promoted changes.-# We do this so admins are not overwhelmed by many separate notifications for upcoming changes-# being available or promoted in cases like deployments where this is possible.+# Consolidates upcoming change notification data for both available and promoted+# changes. We do this so admins are not overwhelmed by many separate+# notifications for upcoming changes being available or promoted in cases like+# deployments where this is possible.#-# Used in UpcomingChanges::Action::NotifyAdminsOfAvailableChange and UpcomingChanges::NotifyPromotion,-# and only unread notifications are considered for merging.+# Used in Jobs::Scheduled::NotifyAdminsOfAvailableUpcomingChanges and+# UpcomingChanges::NotifyPromotion, and only unread notifications are considered+# for merging.class UpcomingChanges::Action::NotificationDataMerger < Service::ActionBase- option :existing_notification+ option :existing_notification_dataoption :new_change_namedef call- if existing_notification- existing_data = JSON.parse(existing_notification.data, symbolize_names: true)+ if existing_notification_data+ existing_data = JSON.parse(existing_notification_data, symbolize_names: true)names =Array.wrap(existing_data[:upcoming_change_names] || [existing_data[:upcoming_change_name]])humanized =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.rbdeleted file mode 100644index 596d87e6e0c..00000000000--- a/app/services/upcoming_changes/action/notify_admins_of_available_change.rb+++ /dev/null@@ -1,82 +0,0 @@-# frozen_string_literal: true--# Intended to be called from UpcomingChanges::Action::TrackNotifyStatusChanges, and-# UpcomingChanges::Action::TrackNotifyAddedChanges, 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- eligible_admins = find_eligible_admins- return if eligible_admins.empty?- notify_admins(eligible_admins:)- create_event- log_action- true- end-- private-- def find_eligible_admins- eligible_admin_ids =- UserOption- .where(user_id: all_admins.map(&:id))- .where(enable_upcoming_change_available_notifications: true)- .pluck(:user_id)- .to_set- all_admins.select { |admin| eligible_admin_ids.include?(admin.id) }- end-- def notify_admins(eligible_admins:)- existing_notifications =- Notification.where(- notification_type: Notification.types[:upcoming_change_available],- user_id: eligible_admins.map(&:id),- read: false,- )- existing_notification_rows = existing_notifications.to_a- existing_by_user = existing_notification_rows.index_by(&:user_id)- merge_with_existing = existing_notification_rows.present?-- bulk_notification_new_records =- eligible_admins.map do |admin|- {- user_id: admin.id,- notification_type: Notification.types[:upcoming_change_available],- data:- UpcomingChanges::Action::NotificationDataMerger.call(- existing_notification: existing_by_user[admin.id],- new_change_name: change_name,- ).to_json,- }- end-- Notification.transaction do- existing_notifications.delete_all if merge_with_existing- Notification::Action::BulkCreate.call(- records: bulk_notification_new_records,- skip_send_email: merge_with_existing,- )- end- 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..d08c9415c97--- /dev/null+++ b/app/services/upcoming_changes/action/track_added_changes.rb@@ -0,0 +1,33 @@+# 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+#+# Admins will be notified about newly available upcoming changes+# on a weekly basis via Jobs::NotifyAdminsOfAvailableUpcomingChanges+class UpcomingChanges::Action::TrackAddedChanges < Service::ActionBase+ # Every admin user that are not bots+ option :all_admins++ def call+ added_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)+ end++ added_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_notify_added_changes.rb b/app/services/upcoming_changes/action/track_notify_added_changes.rbdeleted file mode 100644index d34796b43c1..00000000000--- a/app/services/upcoming_changes/action/track_notify_added_changes.rb+++ /dev/null@@ -1,63 +0,0 @@-# 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::TrackNotifyAddedChanges < 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)-- # No point in notifying admins on brand new sites, the upcoming change system- # is more about notifying admins of changes to established sites.- next if !UpcomingChanges.should_notify_admins?-- # 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)- next 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,- )- Rails.logger.info(- "Notifying admins about available change #{change_name} from TrackNotifyAddedChanges",- )- notified =- UpcomingChanges::Action::NotifyAdminsOfAvailableChange.call(change_name:, all_admins:)- notified_changes << change_name if notified- 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_notify_status_changes.rb b/app/services/upcoming_changes/action/track_status_changes.rbsimilarity index 52%rename from app/services/upcoming_changes/action/track_notify_status_changes.rbrename to app/services/upcoming_changes/action/track_status_changes.rbindex fb03d29a21e..9ee93dd1575 100644--- a/app/services/upcoming_changes/action/track_notify_status_changes.rb+++ b/app/services/upcoming_changes/action/track_status_changes.rb@@ -5,17 +5,13 @@## 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::TrackNotifyStatusChanges < Service::ActionBase+class UpcomingChanges::Action::TrackStatusChanges < Service::ActionBase# Every admin user that are not botsoption :all_admins- # All changes that were added at the same time, we already added events- # and notified admins for them.+ # All changes that were added at the same time, we+ # create a special status changed event for these with+ # no previous value.option :added_changes# All changes that were removed at the same time, we don't care about@@ -24,7 +20,6 @@ class UpcomingChanges::Action::TrackNotifyStatusChanges < Service::ActionBasedef callstatus_changes = {}- notified_changes = []SiteSetting.upcoming_change_site_settings.each do |change_name|if no_previous_status_event?(change_name)@@ -59,37 +54,13 @@ class UpcomingChanges::Action::TrackNotifyStatusChanges < Service::ActionBase},)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.- #- # Note that on new sites (< 1 hour old), we don't notify admins about added- # changes, since the upcoming change system is more about notifying admins of- # changes to established sites.- if should_notify_admins?(change_name) &&- !UpcomingChanges.meets_or_exceeds_status?(- change_name,- SiteSetting.promote_upcoming_changes_on_status.to_sym,- )- Rails.logger.info(- "Notifying admins about available change #{change_name} from TrackNotifyStatusChanges",- )- notified =- UpcomingChanges::Action::NotifyAdminsOfAvailableChange.call(change_name:, all_admins:)- notified_changes << change_name if notified- endendend- Discourse.cache.delete(UpcomingChanges.current_statuses_cache_key)+ UpcomingChanges.clear_caches!DiscourseUpdates.clear_latest_new_feature_created_at_cache- { status_changes:, notified_changes: }+ status_changesendprivate@@ -114,11 +85,4 @@ class UpcomingChanges::Action::TrackNotifyStatusChanges < Service::ActionBasedef status_changed?(previous_status, current_status)previous_status&.to_sym != current_statusend-- def should_notify_admins?(change_name)- !UpcomingChangeEvent.exists?(- upcoming_change_name: change_name,- event_type: :admins_notified_available_change,- ) && UpcomingChanges.should_notify_admins?- endenddiff --git a/app/services/upcoming_changes/notify_promotion.rb b/app/services/upcoming_changes/notify_promotion.rbindex d044915241a..0af0ce94d36 100644--- a/app/services/upcoming_changes/notify_promotion.rb+++ b/app/services/upcoming_changes/notify_promotion.rb@@ -97,7 +97,7 @@ class UpcomingChanges::NotifyPromotionnotification_type: Notification.types[:upcoming_change_automatically_promoted],data:UpcomingChanges::Action::NotificationDataMerger.call(- existing_notification: existing_by_user[admin_id],+ existing_notification_data: existing_by_user[admin_id]&.data,new_change_name: params.setting_name,).to_json,}diff --git a/app/services/upcoming_changes/track.rb b/app/services/upcoming_changes/track.rbindex da92fbc778e..7a73cb152b8 100644--- a/app/services/upcoming_changes/track.rb+++ b/app/services/upcoming_changes/track.rb@@ -21,9 +21,7 @@ class UpcomingChanges::Trackenddef fetch_added_changes(all_admins:)- result = UpcomingChanges::Action::TrackNotifyAddedChanges.call(all_admins:)- context[:notified_admins_for_added_changes] = result[:notified_changes]- result[:added_changes]+ UpcomingChanges::Action::TrackAddedChanges.call(all_admins:)enddef fetch_removed_changes@@ -31,13 +29,6 @@ class UpcomingChanges::Trackenddef fetch_status_changes(added_changes:, removed_changes:, all_admins:)- result =- UpcomingChanges::Action::TrackNotifyStatusChanges.call(- all_admins:,- added_changes:,- removed_changes:,- )- context[:notified_admins_for_added_changes] += result[:notified_changes]- result[:status_changes]+ UpcomingChanges::Action::TrackStatusChanges.call(all_admins:, added_changes:, removed_changes:)endenddiff --git a/lib/upcoming_changes.rb b/lib/upcoming_changes.rbindex f4c105e5a98..393934ccffb 100644--- a/lib/upcoming_changes.rb+++ b/lib/upcoming_changes.rb@@ -367,7 +367,7 @@ module UpcomingChanges# to save time in other places in the codebase when we have to figure out# when an upcoming change moved to its current status.#- # This cache is automatically cleared when UpcomingChanges::Action::TrackNotifyStatusChanges+ # This cache is automatically cleared when UpcomingChanges::Action::TrackStatusChanges# is called, since that adds new UpcomingChangeEvent records.def self.current_statusesDiscoursediff --git a/spec/jobs/scheduled/check_upcoming_changes_spec.rb b/spec/jobs/scheduled/check_upcoming_changes_spec.rbindex da6dd6867ba..bb73f575a54 100644--- a/spec/jobs/scheduled/check_upcoming_changes_spec.rb+++ b/spec/jobs/scheduled/check_upcoming_changes_spec.rb@@ -71,32 +71,6 @@ RSpec.describe Jobs::CheckUpcomingChanges doendend- 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|- described_class.new.execute({})- 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|- described_class.new.execute({})- 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" dobefore doUpcomingChangeEvent.create!(event_type: :added, upcoming_change_name: :old_removed_change)@@ -128,10 +102,6 @@ RSpec.describe Jobs::CheckUpcomingChanges do"new_value" => "alpha",},)- UpcomingChangeEvent.create!(- event_type: :admins_notified_available_change,- upcoming_change_name: :enable_upload_debug_mode,- )endit "logs status changes" do@@ -211,10 +181,6 @@ RSpec.describe Jobs::CheckUpcomingChanges doevent_type: :added,upcoming_change_name: :enable_upload_debug_mode,)- UpcomingChangeEvent.create!(- event_type: :admins_notified_available_change,- upcoming_change_name: :enable_upload_debug_mode,- )UpcomingChangeEvent.where(upcoming_change_name: :enable_upload_debug_mode,event_type: :admins_notified_automatic_promotion,@@ -224,10 +190,6 @@ RSpec.describe Jobs::CheckUpcomingChanges doevent_type: :added,upcoming_change_name: :show_user_menu_avatars,)- UpcomingChangeEvent.create!(- event_type: :admins_notified_available_change,- upcoming_change_name: :show_user_menu_avatars,- )UpcomingChangeEvent.create!(event_type: :admins_notified_automatic_promotion,upcoming_change_name: :show_user_menu_avatars,@@ -273,10 +235,6 @@ RSpec.describe Jobs::CheckUpcomingChanges doevent_type: :added,upcoming_change_name: :show_user_menu_avatars,)- UpcomingChangeEvent.create!(- event_type: :admins_notified_available_change,- upcoming_change_name: :show_user_menu_avatars,- )endit "logs promotion of permanent change" dodiff --git a/spec/jobs/scheduled/notify_admins_of_available_upcoming_changes_spec.rb b/spec/jobs/scheduled/notify_admins_of_available_upcoming_changes_spec.rbnew file mode 100644index 00000000000..4f3ab7e5364--- /dev/null+++ b/spec/jobs/scheduled/notify_admins_of_available_upcoming_changes_spec.rb@@ -0,0 +1,366 @@+# frozen_string_literal: true++RSpec.describe Jobs::NotifyAdminsOfAvailableUpcomingChanges do+ subject(:result) { described_class.new.execute({}) }++ before do+ mock_upcoming_change_metadata(+ {+ test_upcoming_change: {+ impact: "feature,all_members",+ status: test_upcoming_change_status,+ impact_type: "feature",+ impact_role: "all_members",+ },+ test_upcoming_change_b: {+ impact: "feature,all_members",+ status: :beta,+ impact_type: "feature",+ impact_role: "all_members",+ },+ test_upcoming_change_c: {+ impact: "feature,all_members",+ status: :beta,+ impact_type: "feature",+ impact_role: "all_members",+ },+ },+ )++ # No upcoming change notifications are sent for new sites+ UpcomingChanges.stubs(:should_notify_admins?).returns(true)+ end++ let(:test_upcoming_change_status) { :beta }+ fab!(:admin_1, :admin)+ fab!(:admin_2, :admin)++ fab!(:new_change_log) do+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :test_upcoming_change,+ created_at: 1.day.ago,+ )+ end+ fab!(:new_change_log_2) do+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :test_upcoming_change_b,+ created_at: 3.days.ago,+ )+ end+ fab!(:old_change_log) do+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :test_upcoming_change_c,+ created_at: 8.days.ago,+ )+ end++ it "creates a notification for each admin for the recently available changes that we have not yet notified" do+ expect { result }.to change {+ Notification.where(notification_type: Notification.types[:upcoming_change_available]).count+ }.by(2)+ expect(+ JSON.parse(+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .last+ .data,+ symbolize_names: true,+ ),+ ).to include(+ upcoming_change_names: %w[test_upcoming_change test_upcoming_change_b],+ upcoming_change_humanized_names: ["Test upcoming change", "Test upcoming change b"],+ count: 2,+ )+ end++ it "does not create a notification for changes where we have notified the admins already" do+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :test_upcoming_change,+ )+ expect { result }.to change {+ Notification.where(notification_type: Notification.types[:upcoming_change_available]).count+ }.by(2)+ expect(+ JSON.parse(+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .last+ .data,+ symbolize_names: true,+ ),+ ).to include(+ upcoming_change_names: %w[test_upcoming_change_b],+ upcoming_change_humanized_names: ["Test upcoming change b"],+ count: 1,+ )+ end++ it "does not create a notification for admins who have disabled upcoming change available notifications" do+ admin_1.user_option.update!(enable_upcoming_change_available_notifications: false)+ expect { result }.to change {+ Notification.where(notification_type: Notification.types[:upcoming_change_available]).count+ }.by(1)+ expect(+ Notification.where(+ user: admin_2,+ notification_type: Notification.types[:upcoming_change_available],+ ).count,+ ).to eq(1)+ expect(+ Notification.where(+ user: admin_1,+ notification_type: Notification.types[:upcoming_change_available],+ ).count,+ ).to eq(0)+ end++ it "does not create a notification if we've already automatically promoted the change" do+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_automatic_promotion,+ upcoming_change_name: :test_upcoming_change,+ acting_user: Discourse.system_user,+ )+ result+ expect(+ JSON.parse(+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .last+ .data,+ symbolize_names: true,+ ),+ ).to include(+ upcoming_change_names: %w[test_upcoming_change_b],+ upcoming_change_humanized_names: ["Test upcoming change b"],+ count: 1,+ )+ end++ it "creates a staff action log for each upcoming change that we are notifying for" do+ expect { result }.to change {+ UserHistory.where(action: UserHistory.actions[:upcoming_change_available]).count+ }.by(2)+ end++ it "creates an admins_notifed_available_change event for each upcoming change that we are notifying for" do+ expect { result }.to change {+ UpcomingChangeEvent.where(event_type: :admins_notified_available_change).count+ }.by(2)+ end++ context "when there are no upcoming changes to notify" do+ before { UpcomingChangeEvent.delete_all }++ it "sends no notifications" do+ expect { result }.not_to change { Notification.count }+ end++ context "when there are existing unread notifications" do+ fab!(:notification) do+ Fabricate(+ :notification,+ notification_type: Notification.types[:upcoming_change_available],+ user: admin_1,+ )+ end++ it "does not delete the existing notifications" do+ old_notification_id = notification.id+ result+ expect(Notification.find_by(id: old_notification_id)).to be_present+ end+ end+ end++ context "when admins should not be notified" do+ before { UpcomingChanges.stubs(:should_notify_admins?).returns(false) }++ it "sends no notifications" do+ expect { result }.not_to change { Notification.count }+ end+ end++ context "when an upcoming change has an old added event" do+ before { new_change_log.update!(created_at: 2.weeks.ago) }++ context "when there is not a recent status change event that matches promotion status - 1" do+ it "does not create notifications for that change" do+ result+ expect(+ JSON.parse(+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .last+ .data,+ symbolize_names: true,+ ),+ ).to include(+ upcoming_change_names: %w[test_upcoming_change_b],+ upcoming_change_humanized_names: ["Test upcoming change b"],+ count: 1,+ )+ end+ end++ context "when there is also a recent status change event that matches promotion status - 1" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :status_changed,+ upcoming_change_name: :test_upcoming_change,+ created_at: 1.day.ago,+ event_data: {+ new_value:+ UpcomingChanges.previous_status(SiteSetting.promote_upcoming_changes_on_status).to_s,+ },+ )+ end++ it "creates notifications for that change" do+ result+ expect(+ JSON.parse(+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .last+ .data,+ symbolize_names: true,+ ),+ ).to include(+ upcoming_change_names: %w[test_upcoming_change test_upcoming_change_b],+ upcoming_change_humanized_names: ["Test upcoming change", "Test upcoming change b"],+ count: 2,+ )+ end++ context "when we have already notified admins of the change" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :admins_notified_available_change,+ upcoming_change_name: :test_upcoming_change,+ )+ end++ it "does not make a notification for the change" do+ result+ expect(+ JSON.parse(+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .last+ .data,+ symbolize_names: true,+ ),+ ).to include(+ upcoming_change_names: %w[test_upcoming_change_b],+ upcoming_change_humanized_names: ["Test upcoming change b"],+ count: 1,+ )+ end+ end+ end+ end++ context "when an admin has an unread notification from a previous week" do+ fab!(:notification) do+ Fabricate(+ :notification,+ notification_type: Notification.types[:upcoming_change_available],+ read: false,+ user: admin_1,+ data: {+ upcoming_change_names: ["test_upcoming_change_ancient"],+ upcoming_change_humanized_names: [+ SiteSetting.humanized_name(:test_upcoming_change_ancient),+ ],+ count: 1,+ }.to_json,+ )+ end++ it "consolidates the notifications including the upcoming change names" do+ existing_notification_id = notification.id+ expect { result }.to change { Notification.where(user_id: admin_2.id).count }.by(+ 1,+ ).and not_change { Notification.where(user_id: admin_1.id).count }++ new_notification =+ Notification.find_by(+ user_id: admin_1.id,+ notification_type: Notification.types[:upcoming_change_available],+ )+ expect(Notification.find_by(id: existing_notification_id)).to be_nil+ data = JSON.parse(new_notification.reload.data)+ expect(data["upcoming_change_names"]).to contain_exactly(+ "test_upcoming_change_ancient",+ "test_upcoming_change",+ "test_upcoming_change_b",+ )+ expect(data["count"]).to eq(3)+ end+ end++ context "when all admins have disabled upcoming change available notifications" do+ before do+ admin_1.user_option.update!(enable_upcoming_change_available_notifications: false)+ admin_2.user_option.update!(enable_upcoming_change_available_notifications: false)+ end++ it "sends no notifications" do+ expect { result }.not_to change {+ Notification.where(notification_type: Notification.types[:upcoming_change_available]).count+ }+ end++ it "logs no staff action logs" do+ expect { result }.not_to change {+ UserHistory.where(action: UserHistory.actions[:upcoming_change_available]).count+ }+ end++ it "logs no admins_notifed_available_change events" do+ expect { result }.not_to change {+ UpcomingChangeEvent.where(event_type: :admins_notified_available_change).count+ }+ end+ end++ context "when there is an added event for an upcoming change that no longer exists" do+ before do+ UpcomingChangeEvent.create!(+ event_type: :added,+ upcoming_change_name: :old_deleted_upcoming_change,+ created_at: 1.day.ago,+ )+ end++ it "does not create a notification for that change" do+ result+ expect(+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .to_a+ .map { |notification| JSON.parse(notification.data)["upcoming_change_names"] || [] }+ .flatten,+ ).not_to include("old_deleted_upcoming_change")+ end+ end++ context "when an upcoming change is added but hasn't reached the promotion status - 1" do+ let(:test_upcoming_change_status) { :experimental }++ it "does not create a notification for that change" do+ result+ expect(+ Notification+ .where(notification_type: Notification.types[:upcoming_change_available])+ .to_a+ .map { |notification| JSON.parse(notification.data)["upcoming_change_names"] || [] }+ .flatten,+ ).not_to include("test_upcoming_change")+ 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.rbdeleted file mode 100644index 8ebd2990a51..00000000000--- a/spec/services/upcoming_changes/action/notify_admins_of_available_change_spec.rb+++ /dev/null@@ -1,284 +0,0 @@-# 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",- },- test_upcoming_change_b: {- 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 array data format" do- result-- data = JSON.parse(notification.data)- expect(data["upcoming_change_names"]).to eq(["test_upcoming_change"])- expect(data["upcoming_change_humanized_names"]).to eq(- [SiteSetting.humanized_name(:test_upcoming_change)],- )- expect(data["count"]).to eq(1)- 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-- context "when there is an existing unread notification" do- before do- Fabricate(- :notification,- user: admin_1,- notification_type: Notification.types[:upcoming_change_available],- read: false,- data: {- upcoming_change_names: ["test_upcoming_change_b"],- upcoming_change_humanized_names: [SiteSetting.humanized_name(:test_upcoming_change_b)],- count: 1,- }.to_json,- )- end-- it "skips sending email when consolidating notifications" do- allow(Notification::Action::BulkCreate).to receive(:call).and_call_original-- result-- expect(Notification::Action::BulkCreate).to have_received(:call).with(- satisfy { |args| args[:skip_send_email] == true },- )- end-- it "consolidates into a single notification per admin" do- result-- notifications =- Notification.where(- notification_type: Notification.types[:upcoming_change_available],- user_id: admin_1.id,- )- expect(notifications.count).to eq(1)-- data = JSON.parse(notifications.first.data)- expect(data["upcoming_change_names"]).to contain_exactly(- "test_upcoming_change_b",- "test_upcoming_change",- )- expect(data["count"]).to eq(2)- end- end-- context "when there is an existing read notification" do- before do- Fabricate(- :notification,- user: admin_1,- notification_type: Notification.types[:upcoming_change_available],- read: true,- data: {- upcoming_change_names: ["test_upcoming_change_b"],- upcoming_change_humanized_names: [SiteSetting.humanized_name(:test_upcoming_change_b)],- count: 1,- }.to_json,- )- end-- it "does not skip sending email when not consolidating notifications" do- allow(Notification::Action::BulkCreate).to receive(:call).and_call_original-- result-- expect(Notification::Action::BulkCreate).to have_received(:call).with(- satisfy { |args| args[:skip_send_email] == false },- )- end-- it "does not consolidate with the read notification" do- result-- notifications =- Notification.where(- notification_type: Notification.types[:upcoming_change_available],- user_id: admin_1.id,- )- expect(notifications.count).to eq(2)- end- end-- context "when the same change is already in an unread notification" do- before do- Fabricate(- :notification,- user: admin_1,- notification_type: Notification.types[:upcoming_change_available],- read: false,- data: {- upcoming_change_names: ["test_upcoming_change"],- upcoming_change_humanized_names: [SiteSetting.humanized_name(:test_upcoming_change)],- count: 1,- }.to_json,- )- end-- it "deduplicates the change names" do- result-- notifications =- Notification.where(- notification_type: Notification.types[:upcoming_change_available],- user_id: admin_1.id,- )- expect(notifications.count).to eq(1)-- data = JSON.parse(notifications.first.data)- expect(data["upcoming_change_names"]).to eq(["test_upcoming_change"])- expect(data["count"]).to eq(1)- end- end-- context "when an admin has disabled upcoming change available notifications" do- before { admin_2.user_option.update!(enable_upcoming_change_available_notifications: false) }-- it "only creates a notification for admins who have the preference enabled" do- expect { result }.to change {- Notification.where(- notification_type: Notification.types[:upcoming_change_available],- ).count- }.by(1)-- expect(- Notification.exists?(- notification_type: Notification.types[:upcoming_change_available],- user_id: admin_1.id,- ),- ).to eq(true)- expect(- Notification.exists?(- notification_type: Notification.types[:upcoming_change_available],- user_id: admin_2.id,- ),- ).to eq(false)- end-- context "when no admins have the preference enabled" do- before do- admin_1.user_option.update!(enable_upcoming_change_available_notifications: false)- end-- it "does not create any notifications" do- expect { result }.not_to change {- Notification.where(- notification_type: Notification.types[:upcoming_change_available],- ).count- }- end-- it "does not create an admins_notified_available_change event" do- expect { result }.not_to change {- UpcomingChangeEvent.where(- event_type: :admins_notified_available_change,- upcoming_change_name: :test_upcoming_change,- ).count- }- end-- it "does not log a staff action" do- expect { result }.not_to change {- UserHistory.where(- action: UserHistory.actions[:upcoming_change_available],- subject: "test_upcoming_change",- ).count- }- end-- it "returns nil" do- expect(result).to be_nil- end- end- end-- context "when there is an existing notification with the old data format" do- before do- Fabricate(- :notification,- user: admin_1,- notification_type: Notification.types[:upcoming_change_available],- read: false,- data: {- upcoming_change_name: "test_upcoming_change_b",- upcoming_change_humanized_name: SiteSetting.humanized_name(:test_upcoming_change_b),- }.to_json,- )- end-- it "merges old format into the new array format" do- result-- notifications =- Notification.where(- notification_type: Notification.types[:upcoming_change_available],- user_id: admin_1.id,- )- expect(notifications.count).to eq(1)-- data = JSON.parse(notifications.first.data)- expect(data["upcoming_change_names"]).to contain_exactly(- "test_upcoming_change_b",- "test_upcoming_change",- )- expect(data["count"]).to eq(2)- end- 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..41a763feaa2--- /dev/null+++ b/spec/services/upcoming_changes/action/track_added_changes_spec.rb@@ -0,0 +1,68 @@+# frozen_string_literal: true++RSpec.describe UpcomingChanges::Action::TrackAddedChanges 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],+ )+ 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).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).to include(:show_user_menu_avatars)+ expect(result).not_to include(:enable_upload_debug_mode)+ end+ end+ end+enddiff --git a/spec/services/upcoming_changes/action/track_notify_added_changes_spec.rb b/spec/services/upcoming_changes/action/track_notify_added_changes_spec.rbdeleted file mode 100644index 6410b6355a8..00000000000--- a/spec/services/upcoming_changes/action/track_notify_added_changes_spec.rb+++ /dev/null@@ -1,172 +0,0 @@-# frozen_string_literal: true--RSpec.describe UpcomingChanges::Action::TrackNotifyAddedChanges do- let(:enable_upload_debug_mode_status) { :experimental }- let(:show_user_menu_avatars_status) { :beta }-- before do- # No upcoming change notifications are sent for new sites- UpcomingChanges.stubs(:should_notify_admins?).returns(true)- 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-- context "when the site is new (< 1 hour old)" do- before { UpcomingChanges.stubs(:should_notify_admins?).returns(false) }-- it "does not notify admins that a change is available" do- expect { result }.not_to change { Notification.count }- end-- it "does still make the upcoming change event" do- expect { result }.to change {- scoped_events.where(- event_type: :added,- upcoming_change_name: :show_user_menu_avatars,- ).count- }.by(1)- end- 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- .where(notification_type: Notification.types[:upcoming_change_available])- .where(- "data::text LIKE '%enable_upload_debug_mode%' OR data::text LIKE '%show_user_menu_avatars%'",- )- .count- }- end-- it "does not include the scoped changes in notified_changes" do- expect(result[:notified_changes]).not_to include(- :enable_upload_debug_mode,- :show_user_menu_avatars,- )- 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_notify_status_changes_spec.rb b/spec/services/upcoming_changes/action/track_status_changes_spec.rbsimilarity index 60%rename from spec/services/upcoming_changes/action/track_notify_status_changes_spec.rbrename to spec/services/upcoming_changes/action/track_status_changes_spec.rbindex d8b0e5629a1..9131644cb6f 100644--- a/spec/services/upcoming_changes/action/track_notify_status_changes_spec.rb+++ b/spec/services/upcoming_changes/action/track_status_changes_spec.rb@@ -1,12 +1,10 @@# frozen_string_literal: true-RSpec.describe UpcomingChanges::Action::TrackNotifyStatusChanges do+RSpec.describe UpcomingChanges::Action::TrackStatusChanges dolet(:enable_upload_debug_mode_status) { :experimental }let(:show_user_menu_avatars_status) { :beta }before do- # No upcoming change notifications are sent for new sites- UpcomingChanges.stubs(:should_notify_admins?).returns(true)mock_upcoming_change_metadata({enable_upload_debug_mode: {@@ -77,7 +75,7 @@ RSpec.describe UpcomingChanges::Action::TrackNotifyStatusChanges doendit "returns N/A as previous_value in the result" do- expect(result[:status_changes][:enable_upload_debug_mode]).to eq(+ expect(result[:enable_upload_debug_mode]).to eq({ previous_value: "N/A", new_value: :experimental },)end@@ -183,10 +181,6 @@ RSpec.describe UpcomingChanges::Action::TrackNotifyStatusChanges do"new_value" => "experimental",},)- UpcomingChangeEvent.create!(- event_type: :admins_notified_available_change,- upcoming_change_name: :show_user_menu_avatars,- )endit "creates a status_changed event with correct data" do@@ -199,7 +193,6 @@ RSpec.describe UpcomingChanges::Action::TrackNotifyStatusChanges doendit "records the previous and new status values" do- resultresultexpect(scoped_events@@ -210,7 +203,7 @@ RSpec.describe UpcomingChanges::Action::TrackNotifyStatusChanges doendit "returns the status change in the result" do- expect(result[:status_changes][:show_user_menu_avatars]).to eq(+ expect(result[:show_user_menu_avatars]).to eq({ previous_value: "beta", new_value: :stable },)end@@ -242,135 +235,5 @@ RSpec.describe UpcomingChanges::Action::TrackNotifyStatusChanges doexpect { result }.not_to change { scoped_events.where(event_type: :status_changed).count }endend-- 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 the site is new (< 1 hour old)" do- before { UpcomingChanges.stubs(:should_notify_admins?).returns(false) }-- it "does not notify admins" 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- 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-- context "when a change jumps directly to the promotion status" do- let(:show_user_menu_avatars_status) { :stable }-- 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" => "experimental",- },- )- 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 send an upcoming_change_available notification" 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- endendenddiff --git a/spec/services/upcoming_changes/track_spec.rb b/spec/services/upcoming_changes/track_spec.rbindex 73951a963e3..cced820ca76 100644--- a/spec/services/upcoming_changes/track_spec.rb+++ b/spec/services/upcoming_changes/track_spec.rb@@ -7,24 +7,20 @@ RSpec.describe UpcomingChanges::Track dodescribe ".call" dosubject(:result) { described_class.call }- let(:added_changes_result) do- { added_changes: [:added_change], notified_changes: [:notified_added] }- end+ let(:added_changes_result) { [:added_change] }let(:removed_changes_result) { [:removed_change] }- let(:status_changes_result) do- { status_changes: { status_change: :data }, notified_changes: [:notified_status] }- end+ let(:status_changes_result) { { status_change: :data } }before do- allow(UpcomingChanges::Action::TrackNotifyAddedChanges).to receive(:call).and_return(+ 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::TrackNotifyStatusChanges).to receive(:call).and_return(+ allow(UpcomingChanges::Action::TrackStatusChanges).to receive(:call).and_return(status_changes_result,)end@@ -33,9 +29,9 @@ RSpec.describe UpcomingChanges::Track doexpect(result).to run_successfullyend- it "calls TrackNotifyAddedChanges with correct arguments" do+ it "calls TrackAddedChanges with correct arguments" doresult- expect(UpcomingChanges::Action::TrackNotifyAddedChanges).to have_received(:call) do |args|+ expect(UpcomingChanges::Action::TrackAddedChanges).to have_received(:call) do |args|expect(args[:all_admins]).to contain_exactly(admin_1, admin_2)endend@@ -45,9 +41,9 @@ RSpec.describe UpcomingChanges::Track doexpect(UpcomingChanges::Action::TrackRemovedChanges).to have_received(:call)end- it "calls TrackNotifyStatusChanges with correct arguments" do+ it "calls TrackStatusChanges with correct arguments" doresult- expect(UpcomingChanges::Action::TrackNotifyStatusChanges).to have_received(:call) do |args|+ expect(UpcomingChanges::Action::TrackStatusChanges).to have_received(:call) do |args|expect(args[:all_admins]).to contain_exactly(admin_1, admin_2)expect(args[:added_changes]).to eq([:added_change])expect(args[:removed_changes]).to eq([:removed_change])@@ -61,7 +57,6 @@ RSpec.describe UpcomingChanges::Track dostatus_changes: {status_change: :data,},- notified_admins_for_added_changes: %i[notified_added notified_status],)endend