Skip to content

A platform for community discussion. Free, open, simple.

FIX: Timeout issue when updating a large collection of users when changing the default_categories_* and default_tags_* SiteSettings (#33665)

Juan David Martínez Cubillos0d721b47dd4f
diff --git a/app/assets/javascripts/admin/addon/components/site-setting.gjs b/app/assets/javascripts/admin/addon/components/site-setting.gjs
index c033e44e3de..1ee36865cc0 100644
--- a/app/assets/javascripts/admin/addon/components/site-setting.gjs
+++ b/app/assets/javascripts/admin/addon/components/site-setting.gjs
@@ -9,14 +9,17 @@ import { LinkTo } from "@ember/routing";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import { isNone } from "@ember/utils";
+import { and } from "truth-helpers";
import DButton from "discourse/components/d-button";
import JsonSchemaEditorModal from "discourse/components/modal/json-schema-editor";
import icon from "discourse/helpers/d-icon";
+import { bind } from "discourse/lib/decorators";
import { deepEqual } from "discourse/lib/object";
import { splitString } from "discourse/lib/utilities";
import { i18n } from "discourse-i18n";
import SettingValidationMessage from "admin/components/setting-validation-message";
import Description from "admin/components/site-settings/description";
+import JobStatus from "admin/components/site-settings/job-status";
import SiteSetting from "admin/models/site-setting";
const CUSTOM_TYPES = [
@@ -51,13 +54,48 @@ export default class SiteSettingComponent extends Component {
@service modal;
@service router;
@service siteSettingChangeTracker;
+ @service messageBus;
@tracked isSecret = null;
+ @tracked status = null;
+ @tracked progress = null;
updateExistingUsers = null;
constructor() {
super(...arguments);
this.isSecret = this.setting?.secret;
+
+ if (this.canSubscribeToSettingsJobs) {
+ this.messageBus.subscribe(
+ `/site_setting/${this.setting.setting}/process`,
+ this.onMessage
+ );
+ }
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+
+ if (this.canSubscribeToSettingsJobs) {
+ this.messageBus.unsubscribe(
+ `/site_setting/${this.setting.setting}/process`,
+ this.onMessage
+ );
+ }
+ }
+
+ canSubscribeToSettingsJobs() {
+ const settingName = this.setting.setting;
+ return (
+ settingName.includes("default_categories") ||
+ settingName.includes("default_tags")
+ );
+ }
+
+ @bind
+ async onMessage(membership) {
+ this.status = membership.status;
+ this.progress = membership.progress;
}
@action
@@ -227,6 +265,14 @@ export default class SiteSettingComponent extends Component {
return this.setting.staffLogFilter;
}
+ get canUpdate() {
+ if (!this.status || this.status === "completed") {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
@action
async update() {
if (this.setting.requiresConfirmation) {
@@ -367,6 +413,7 @@ export default class SiteSettingComponent extends Component {
/>
<Description @description={{this.setting.description}} />
+ <JobStatus @status={{this.status}} @progress={{this.progress}} />
{{else}}
<this.resolvedComponent
{{on "keydown" this._handleKeydown}}
@@ -383,11 +430,12 @@ export default class SiteSettingComponent extends Component {
/>
{{#if this.displayDescription}}
<Description @description={{this.setting.description}} />
+ <JobStatus @status={{this.status}} @progress={{this.progress}} />
{{/if}}
{{/if}}
</div>
- {{#if this.dirty}}
+ {{#if (and this.dirty this.canUpdate)}}
<div class="setting-controls">
<DButton
@action={{this.update}}
@@ -404,7 +452,7 @@ export default class SiteSettingComponent extends Component {
class="cancel setting-controls__cancel"
/>
</div>
- {{else if this.overridden}}
+ {{else if (and this.overridden this.canUpdate)}}
{{#if this.setting.secret}}
<DButton
@action={{this.toggleSecret}}
diff --git a/app/assets/javascripts/admin/addon/components/site-settings/job-status.gjs b/app/assets/javascripts/admin/addon/components/site-settings/job-status.gjs
new file mode 100644
index 00000000000..e2bb14bc6f2
--- /dev/null
+++ b/app/assets/javascripts/admin/addon/components/site-settings/job-status.gjs
@@ -0,0 +1,20 @@
+import { eq } from "truth-helpers";
+import { i18n } from "discourse-i18n";
+
+<template>
+ asdasd
+ {{#if @status}}
+ <div class="job desc site-setting">
+ {{#if (eq @status "enqueued")}}
+ <p class="alert">{{i18n "admin.site_settings.job_status.enqueued"}}</p>
+ {{else if (eq @status "completed")}}
+ <p class="success">{{i18n
+ "admin.site_settings.job_status.completed"
+ }}</p>
+ {{/if}}
+ {{#if @progress}}
+ <p class="progress">{{@progress}}</p>
+ {{/if}}
+ </div>
+ {{/if}}
+</template>
diff --git a/app/assets/javascripts/discourse/tests/integration/components/site-setting-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/site-setting-test.gjs
index 3416180d494..10914da98ed 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/site-setting-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/site-setting-test.gjs
@@ -8,6 +8,7 @@ import {
import { module, skip, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { publishToMessageBus } from "discourse/tests/helpers/qunit-helpers";
import selectKit from "discourse/tests/helpers/select-kit-helper";
import { i18n } from "discourse-i18n";
import SiteSettingComponent from "admin/components/site-setting";
@@ -214,6 +215,104 @@ module("Integration | Component | SiteSetting", function (hooks) {
`/admin/logs/staff_action_logs?filters=${encodeURIComponent(JSON.stringify({ subject: "enable_badges", action_name: "change_site_setting" }))}&force_refresh=true`
);
});
+
+ test("Shows update status for default_categories_ sitesettings", async function (assert) {
+ const self = this;
+
+ this.set(
+ "setting",
+ SiteSetting.create({
+ setting: "default_categories_test",
+ value: "",
+ type: "category_list",
+ })
+ );
+
+ await render(
+ <template><SiteSettingComponent @setting={{self.setting}} /></template>
+ );
+
+ await publishToMessageBus("/site_setting/default_categories_test/process", {
+ status: "enqueued",
+ });
+
+ assert.dom(".desc.site-setting").hasTextContaining("Update in progress");
+
+ await publishToMessageBus("/site_setting/default_categories_test/process", {
+ status: "enqueued",
+ progress: "10/100",
+ });
+
+ assert.dom(".desc.site-setting").hasTextContaining("Update in progress");
+ assert.dom(".desc.site-setting").hasTextContaining("10/100");
+
+ await publishToMessageBus("/site_setting/default_categories_test/process", {
+ status: "completed",
+ });
+ assert.dom(".desc.site-setting").hasTextContaining("Update completed");
+ });
+
+ test("Shows update status for default_tags_ sitesettings", async function (assert) {
+ const self = this;
+
+ this.set(
+ "setting",
+ SiteSetting.create({
+ setting: "default_tags_test",
+ value: "",
+ type: "tag_list",
+ })
+ );
+
+ await render(
+ <template><SiteSettingComponent @setting={{self.setting}} /></template>
+ );
+
+ await publishToMessageBus("/site_setting/default_tags_test/process", {
+ status: "enqueued",
+ });
+ assert.dom(".desc.site-setting").hasTextContaining("Update in progress");
+
+ await publishToMessageBus("/site_setting/default_tags_test/process", {
+ status: "enqueued",
+ progress: "10/100",
+ });
+
+ assert.dom(".desc.site-setting").hasTextContaining("Update in progress");
+ assert.dom(".desc.site-setting").hasTextContaining("10/100");
+
+ await publishToMessageBus("/site_setting/default_tags_test/process", {
+ status: "completed",
+ });
+ assert.dom(".desc.site-setting").hasTextContaining("Update completed");
+ });
+
+ test("Doesn't shows update status for other site settings besides default_tags_test or default_categories_test", async function (assert) {
+ const self = this;
+
+ this.set(
+ "setting",
+ SiteSetting.create({
+ setting: "default_test",
+ value: "",
+ type: "tag_list",
+ })
+ );
+
+ await render(
+ <template><SiteSettingComponent @setting={{self.setting}} /></template>
+ );
+
+ await publishToMessageBus("/site_setting/default_tags_test/process", {
+ status: "enqueued",
+ });
+ assert.dom(".desc.site-setting").doesNotExist();
+
+ await publishToMessageBus("/site_setting/default_tags_test/process", {
+ status: "completed",
+ });
+ assert.dom(".desc.site-setting").doesNotExist();
+ });
});
module(
diff --git a/app/assets/stylesheets/admin/settings.scss b/app/assets/stylesheets/admin/settings.scss
index 4aa152fe47d..5fdc7cd79d0 100644
--- a/app/assets/stylesheets/admin/settings.scss
+++ b/app/assets/stylesheets/admin/settings.scss
@@ -133,6 +133,29 @@
color: var(--danger);
}
+ .job.site-setting {
+ display: flex;
+ flex-direction: row;
+
+ p {
+ margin: 0;
+ }
+
+ .alert {
+ color: var(--danger);
+ background-color: transparent;
+ padding: 0;
+ }
+
+ .success {
+ color: var(--success);
+ }
+
+ .progress {
+ margin-left: 0.5rem;
+ }
+ }
+
.desc {
color: var(--primary-medium);
}
diff --git a/app/jobs/regular/site_setting_update_default_categories.rb b/app/jobs/regular/site_setting_update_default_categories.rb
new file mode 100644
index 00000000000..8d405aa0062
--- /dev/null
+++ b/app/jobs/regular/site_setting_update_default_categories.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+module Jobs
+ class SiteSettingUpdateDefaultCategories < ::Jobs::Base
+ # There should only be one of these jobs running at a time
+ cluster_concurrency 1
+
+ def execute(args)
+ id = args[:id]
+ value = args[:value]
+ previous_value = args[:previous_value]
+
+ SiteSettingUpdateExistingUsers.default_categories(id, value, previous_value)
+ end
+ end
+end
diff --git a/app/jobs/regular/site_setting_update_default_tags.rb b/app/jobs/regular/site_setting_update_default_tags.rb
new file mode 100644
index 00000000000..bd23874e3b5
--- /dev/null
+++ b/app/jobs/regular/site_setting_update_default_tags.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+module Jobs
+ class SiteSettingUpdateDefaultTags < ::Jobs::Base
+ # There should only be one of these jobs running at a time
+ cluster_concurrency 1
+
+ def execute(args)
+ id = args[:id]
+ value = args[:value]
+ previous_value = args[:previous_value]
+
+ SiteSettingUpdateExistingUsers.default_tags(id, value, previous_value)
+ end
+ end
+end
diff --git a/app/services/site_setting_update_existing_users.rb b/app/services/site_setting_update_existing_users.rb
index 9d6f4838274..701dabaaafa 100644
--- a/app/services/site_setting_update_existing_users.rb
+++ b/app/services/site_setting_update_existing_users.rb
@@ -18,81 +18,25 @@ class SiteSettingUpdateExistingUsers
UserOption.human_users.where(user_option => previous_value).update_all(attrs)
elsif id.start_with?("default_categories_")
- previous_category_ids = previous_value.split("|")
- new_category_ids = new_value.split("|")
-
- notification_level = self.category_notification_level(id)
-
- categories_to_unwatch = previous_category_ids - new_category_ids
- CategoryUser.where(
- category_id: categories_to_unwatch,
- notification_level: notification_level,
- ).delete_all
- TopicUser
- .joins(:topic)
- .where(
- notification_level: TopicUser.notification_levels[:watching],
- notifications_reason_id: TopicUser.notification_reasons[:auto_watch_category],
- topics: {
- category_id: categories_to_unwatch,
- },
- )
- .update_all(notification_level: TopicUser.notification_levels[:regular])
-
- (new_category_ids - previous_category_ids).each do |category_id|
- skip_user_ids = CategoryUser.where(category_id: category_id).pluck(:user_id)
-
- User
- .real
- .where(staged: false)
- .where.not(id: skip_user_ids)
- .select(:id)
- .find_in_batches do |users|
- category_users = []
- users.each do |user|
- category_users << {
- category_id: category_id,
- user_id: user.id,
- notification_level: notification_level,
- }
- end
- CategoryUser.insert_all!(category_users)
- end
- end
+ Jobs.enqueue(
+ :site_setting_update_default_categories,
+ { id: id, value: value, previous_value: previous_value },
+ )
+ MessageBus.publish(
+ "/site_setting/#{id}/process",
+ status: "enqueued",
+ group_ids: [Group::AUTO_GROUPS[:admins]],
+ )
elsif id.start_with?("default_tags_")
- previous_tag_ids = Tag.where(name: previous_value.split("|")).pluck(:id)
- new_tag_ids = Tag.where(name: new_value.split("|")).pluck(:id)
- now = Time.zone.now
-
- notification_level = self.tag_notification_level(id)
-
- TagUser.where(
- tag_id: (previous_tag_ids - new_tag_ids),
- notification_level: notification_level,
- ).delete_all
-
- (new_tag_ids - previous_tag_ids).each do |tag_id|
- skip_user_ids = TagUser.where(tag_id: tag_id).pluck(:user_id)
-
- User
- .real
- .where(staged: false)
- .where.not(id: skip_user_ids)
- .select(:id)
- .find_in_batches do |users|
- tag_users = []
- users.each do |user|
- tag_users << {
- tag_id: tag_id,
- user_id: user.id,
- notification_level: notification_level,
- created_at: now,
- updated_at: now,
- }
- end
- TagUser.insert_all!(tag_users)
- end
- end
+ Jobs.enqueue(
+ :site_setting_update_default_tags,
+ { id: id, value: value, previous_value: previous_value },
+ )
+ MessageBus.publish(
+ "/site_setting/#{id}/process",
+ status: "enqueued",
+ group_ids: [Group::AUTO_GROUPS[:admins]],
+ )
elsif self.is_sidebar_default_setting?(id)
Jobs.enqueue(
:backfill_sidebar_site_settings,
@@ -166,4 +110,146 @@ class SiteSettingUpdateExistingUsers
def self.is_sidebar_default_setting?(setting_name)
%w[default_navigation_menu_categories default_navigation_menu_tags].include?(setting_name.to_s)
end
+
+ def self.default_categories(id, value, previous_value)
+ new_value = value.nil? ? "" : value
+
+ batch_size = 50_000
+ previous_category_ids = previous_value.split("|")
+ new_category_ids = new_value.split("|")
+
+ notification_level = category_notification_level(id)
+
+ categories_to_unwatch = previous_category_ids - new_category_ids
+
+ CategoryUser
+ .where(category_id: categories_to_unwatch, notification_level: notification_level)
+ .in_batches(of: batch_size) { |batch| batch.delete_all }
+
+ TopicUser
+ .joins(:topic)
+ .where(
+ notification_level: TopicUser.notification_levels[:watching],
+ notifications_reason_id: TopicUser.notification_reasons[:auto_watch_category],
+ topics: {
+ category_id: categories_to_unwatch,
+ },
+ )
+ .select("topic_users.id")
+ .in_batches(of: batch_size) do |batch|
+ batch.update_all(notification_level: TopicUser.notification_levels[:regular])
+ end
+
+ modified_categories = new_category_ids - previous_category_ids
+
+ skip_user_ids = {}
+ users_scope = {}
+
+ modified_categories.each do |category_id|
+ skip_user_ids[category_id] = CategoryUser.where(category_id: category_id).pluck(:user_id)
+ users_scope[category_id] = User
+ .real
+ .where(staged: false)
+ .where.not(id: skip_user_ids[category_id])
+ end
+
+ total_users_to_process = users_scope.values.map(&:count).sum
+ processed_total = 0
+
+ modified_categories.each do |category_id|
+ users_scope[category_id]
+ .select(:id)
+ .find_in_batches(batch_size: batch_size) do |users|
+ category_users =
+ users.map do |user|
+ { category_id: category_id, user_id: user.id, notification_level: notification_level }
+ end
+
+ CategoryUser.insert_all!(category_users)
+
+ processed_total += users.size
+ publish_progress(id, processed_total, total_users_to_process, modified_categories)
+ end
+ end
+
+ publish_progress(id, processed_total, total_users_to_process, modified_categories)
+ end
+
+ def self.default_tags(id, value, previous_value)
+ new_value = value.nil? ? "" : value
+
+ batch_size = 50_000
+
+ previous_tag_ids = Tag.where(name: previous_value.split("|")).pluck(:id)
+ new_tag_ids = Tag.where(name: new_value.split("|")).pluck(:id)
+ now = Time.zone.now
+
+ notification_level = tag_notification_level(id)
+
+ TagUser
+ .where(tag_id: (previous_tag_ids - new_tag_ids), notification_level: notification_level)
+ .in_batches(of: batch_size) { |batch| batch.delete_all }
+
+ modified_tags = new_tag_ids - previous_tag_ids
+
+ skip_user_ids = {}
+ users_scope = {}
+
+ modified_tags.each do |tag_id|
+ skip_user_ids[:tag_id] = TagUser.where(tag_id: tag_id).pluck(:user_id)
+ users_scope[:tag_id] = User.real.where(staged: false).where.not(id: skip_user_ids[:tag_id])
+ end
+
+ total_users_to_process = users_scope.values.map(&:count).sum
+ processed_total = 0
+
+ modified_tags.each do |tag_id|
+ skip_user_ids[:tag_id] = TagUser.where(tag_id: tag_id).pluck(:user_id)
+ users_scope[:tag_id] = User.real.where(staged: false).where.not(id: skip_user_ids[:tag_id])
+
+ users_scope[:tag_id]
+ .select(:id)
+ .find_in_batches(batch_size: batch_size) do |users|
+ tag_users =
+ users.map do |user|
+ {
+ tag_id: tag_id,
+ user_id: user.id,
+ notification_level: notification_level,
+ created_at: now,
+ updated_at: now,
+ }
+ end
+
+ TagUser.insert_all!(tag_users)
+
+ processed_total += users.size
+ publish_progress(id, processed_total, total_users_to_process, modified_tags)
+ end
+ end
+
+ publish_progress(id, processed_total, total_users_to_process, modified_tags)
+ end
+
+ def self.publish_progress(
+ site_setting_name,
+ processed_total = 0,
+ total_users_to_process = 0,
+ modified = nil
+ )
+ status =
+ if modified.empty? || processed_total >= total_users_to_process
+ "completed"
+ else
+ "enqueued"
+ end
+
+ progress = modified.empty? ? nil : "#{processed_total}/#{total_users_to_process}"
+ MessageBus.publish(
+ "/site_setting/#{site_setting_name}/process",
+ status: status,
+ progress: progress,
+ group_ids: [Group::AUTO_GROUPS[:admins]],
+ )
+ end
end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 1ef7c904529..e4ee6e79e7c 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -8223,7 +8223,9 @@ en:
block_common_passwords:
prompt: "You’re about to change your password policy. This will affect all users changing their passwords from now on. Are you sure you want to proceed?"
confirm: "Yes, update password policy"
-
+ job_status:
+ completed: "Update completed"
+ enqueued: "Update in progress"
badges:
status: Status
title: Badges
diff --git a/spec/jobs/regular/site_setting_update_default_categories_spec.rb b/spec/jobs/regular/site_setting_update_default_categories_spec.rb
new file mode 100644
index 00000000000..fc43a5423b9
--- /dev/null
+++ b/spec/jobs/regular/site_setting_update_default_categories_spec.rb
@@ -0,0 +1,91 @@
+# frozen_string_literal: true
+
+describe Jobs::SiteSettingUpdateDefaultCategories do
+ subject(:job) { described_class.new }
+
+ context "when logged in as an admin" do
+ context "with default categories" do
+ fab!(:user1, :user)
+ fab!(:user2, :user)
+ fab!(:staged_user, :staged)
+ let(:watching) { NotificationLevels.all[:watching] }
+ let(:tracking) { NotificationLevels.all[:tracking] }
+
+ let(:category_ids) { 3.times.collect { Fabricate(:category).id } }
+
+ before do
+ SiteSetting.default_categories_watching = category_ids.first(2).join("|")
+
+ CategoryUser.create!(
+ category_id: category_ids.last,
+ notification_level: tracking,
+ user: user2,
+ )
+ end
+
+ it "should update existing users user preference" do
+ job.execute(
+ id: "default_categories_watching",
+ value: category_ids.last(2).join("|"),
+ previous_value: category_ids.first(2).join("|"),
+ )
+
+ expect(
+ CategoryUser.where(category_id: category_ids.first, notification_level: watching).count,
+ ).to eq(0)
+
+ expect(
+ CategoryUser.where(category_id: category_ids.last, notification_level: watching).count,
+ ).to eq(User.real.where(staged: false).count - 1)
+
+ # Set default_categories_watching to the new value otherwise
+ # new CategoryUser records will be created with the wrong value
+ SiteSetting.default_categories_watching = category_ids.last(2).join("|")
+
+ topic = Fabricate(:topic, category_id: category_ids.last)
+ topic_user1 =
+ Fabricate(
+ :topic_user,
+ topic: topic,
+ notification_level: TopicUser.notification_levels[:watching],
+ notifications_reason_id: TopicUser.notification_reasons[:auto_watch_category],
+ )
+ topic_user2 =
+ Fabricate(
+ :topic_user,
+ topic: topic,
+ notification_level: TopicUser.notification_levels[:watching],
+ notifications_reason_id: TopicUser.notification_reasons[:user_changed],
+ )
+
+ job.execute(
+ id: "default_categories_watching",
+ value: "",
+ previous_value: category_ids.last(2).join("|"),
+ )
+
+ expect(
+ CategoryUser.where(category_id: category_ids, notification_level: watching).count,
+ ).to eq(0)
+ expect(topic_user1.reload.notification_level).to eq(TopicUser.notification_levels[:regular])
+ expect(topic_user2.reload.notification_level).to eq(
+ TopicUser.notification_levels[:watching],
+ )
+ end
+
+ it "should publish a MessageBus informing the correct groups" do
+ messages =
+ MessageBus.track_publish("/site_setting/default_categories_watching/process") do
+ job.execute(
+ id: "default_categories_watching",
+ value: category_ids.last(2).join("|"),
+ previous_value: category_ids.first(2).join("|"),
+ )
+ end
+
+ expect(messages[0][:data][:group_ids]).to eq([Group::AUTO_GROUPS[:admins]])
+ expect(messages[0][:data][:status]).to eq("completed")
+ end
+ end
+ end
+end
diff --git a/spec/jobs/regular/site_setting_update_default_tags_spec.rb b/spec/jobs/regular/site_setting_update_default_tags_spec.rb
new file mode 100644
index 00000000000..c593cc7ee91
--- /dev/null
+++ b/spec/jobs/regular/site_setting_update_default_tags_spec.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+describe Jobs::SiteSettingUpdateDefaultTags do
+ subject(:job) { described_class.new }
+
+ context "when logged in as an admin" do
+ context "with default tags" do
+ fab!(:user1, :user)
+ fab!(:user2, :user)
+ fab!(:staged_user, :staged)
+ let(:watching) { NotificationLevels.all[:watching] }
+ let(:tracking) { NotificationLevels.all[:tracking] }
+
+ let(:tags) { 3.times.collect { Fabricate(:tag) } }
+ before do
+ SiteSetting.default_tags_watching = tags.first(2).pluck(:name).join("|")
+ TagUser.create!(tag_id: tags.last.id, notification_level: tracking, user: user2)
+ end
+
+ it "should update existing users user preference" do
+ job.execute(
+ id: "default_tags_watching",
+ value: tags.last(2).pluck(:name).join("|"),
+ previous_value: tags.first(2).pluck(:name).join("|"),
+ )
+
+ expect(TagUser.where(tag_id: tags.first.id, notification_level: watching).count).to eq(0)
+ expect(TagUser.where(tag_id: tags.last.id, notification_level: watching).count).to eq(
+ User.real.where(staged: false).count - 1,
+ )
+ end
+
+ it "should publish a MessageBus informing the correct groups" do
+ messages =
+ MessageBus.track_publish("/site_setting/default_tags_watching/process") do
+ job.execute(
+ id: "default_tags_watching",
+ value: tags.last(2).pluck(:name).join("|"),
+ previous_value: tags.first(2).pluck(:name).join("|"),
+ )
+ end
+
+ expect(messages[0][:data][:group_ids]).to eq([Group::AUTO_GROUPS[:admins]])
+ expect(messages[0][:data][:status]).to eq("completed")
+ end
+ end
+ end
+end
diff --git a/spec/requests/admin/site_settings_controller_spec.rb b/spec/requests/admin/site_settings_controller_spec.rb
index 5e7be257101..f84697b206b 100644
--- a/spec/requests/admin/site_settings_controller_spec.rb
+++ b/spec/requests/admin/site_settings_controller_spec.rb
@@ -1,5 +1,4 @@
# frozen_string_literal: true
-
RSpec.describe Admin::SiteSettingsController do
fab!(:admin)
fab!(:moderator)
@@ -465,46 +464,33 @@ RSpec.describe Admin::SiteSettingsController do
default_categories_watching: category_ids.last(2).join("|"),
update_existing_user: true,
}
+ expect_job_enqueued(
+ job: Jobs::SiteSettingUpdateDefaultCategories,
+ args: {
+ id: "default_categories_watching",
+ value: category_ids.last(2).join("|"),
+ previous_value: category_ids.first(2).join("|"),
+ },
+ )
expect(response.status).to eq(200)
- expect(
- CategoryUser.where(category_id: category_ids.first, notification_level: watching).count,
- ).to eq(0)
- expect(
- CategoryUser.where(category_id: category_ids.last, notification_level: watching).count,
- ).to eq(User.real.where(staged: false).count - 1)
-
- topic = Fabricate(:topic, category_id: category_ids.last)
- topic_user1 =
- Fabricate(
- :topic_user,
- topic: topic,
- notification_level: TopicUser.notification_levels[:watching],
- notifications_reason_id: TopicUser.notification_reasons[:auto_watch_category],
- )
- topic_user2 =
- Fabricate(
- :topic_user,
- topic: topic,
- notification_level: TopicUser.notification_levels[:watching],
- notifications_reason_id: TopicUser.notification_reasons[:user_changed],
- )
put "/admin/site_settings/default_categories_watching.json",
params: {
default_categories_watching: "",
update_existing_user: true,
}
- expect(response.status).to eq(200)
- expect(
- CategoryUser.where(category_id: category_ids, notification_level: watching).count,
- ).to eq(0)
- expect(topic_user1.reload.notification_level).to eq(
- TopicUser.notification_levels[:regular],
- )
- expect(topic_user2.reload.notification_level).to eq(
- TopicUser.notification_levels[:watching],
+
+ expect_job_enqueued(
+ job: Jobs::SiteSettingUpdateDefaultCategories,
+ args: {
+ id: "default_categories_watching",
+ value: "",
+ previous_value: category_ids.last(2).join("|"),
+ },
)
+
+ expect(response.status).to eq(200)
end
it "should not update existing users user preference" do
@@ -517,40 +503,46 @@ RSpec.describe Admin::SiteSettingsController do
CategoryUser.where(category_id: category_ids.first, notification_level: watching).count
}
+ expect_not_enqueued_with(
+ job: Jobs::SiteSettingUpdateDefaultCategories,
+ args: {
+ id: "default_categories_watching",
+ value: category_ids.last(2).join("|"),
+ previous_value: category_ids.first(2).join("|"),
+ },
+ )
+
expect(response.status).to eq(200)
- expect(
- CategoryUser.where(category_id: category_ids.last, notification_level: watching).count,
- ).to eq(0)
- topic = Fabricate(:topic, category_id: category_ids.last)
- topic_user1 =
- Fabricate(
- :topic_user,
- topic: topic,
- notification_level: TopicUser.notification_levels[:watching],
- notifications_reason_id: TopicUser.notification_reasons[:auto_watch_category],
- )
- topic_user2 =
- Fabricate(
- :topic_user,
- topic: topic,
- notification_level: TopicUser.notification_levels[:watching],
- notifications_reason_id: TopicUser.notification_reasons[:user_changed],
- )
put "/admin/site_settings/default_categories_watching.json",
params: {
default_categories_watching: "",
}
- expect(response.status).to eq(200)
- expect(
- CategoryUser.where(category_id: category_ids.first, notification_level: watching).count,
- ).to eq(0)
- expect(topic_user1.reload.notification_level).to eq(
- TopicUser.notification_levels[:watching],
- )
- expect(topic_user2.reload.notification_level).to eq(
- TopicUser.notification_levels[:watching],
+
+ expect_not_enqueued_with(
+ job: Jobs::SiteSettingUpdateDefaultCategories,
+ args: {
+ id: "default_categories_watching",
+ value: "",
+ previous_value: category_ids.last(2).join("|"),
+ },
)
+
+ expect(response.status).to eq(200)
+ end
+
+ it "should publish a MessageBus informing the correct groups" do
+ messages =
+ MessageBus.track_publish("/site_setting/default_categories_watching/process") do
+ put "/admin/site_settings/default_categories_watching.json",
+ params: {
+ default_categories_watching: category_ids.last(2).join("|"),
+ update_existing_user: true,
+ }
+ end
+
+ expect(messages[0][:data][:group_ids]).to eq([Group::AUTO_GROUPS[:admins]])
+ expect(messages[0][:data][:status]).to eq("enqueued")
end
end
@@ -575,10 +567,16 @@ RSpec.describe Admin::SiteSettingsController do
update_existing_user: true,
}
- expect(TagUser.where(tag_id: tags.first.id, notification_level: watching).count).to eq(0)
- expect(TagUser.where(tag_id: tags.last.id, notification_level: watching).count).to eq(
- User.real.where(staged: false).count - 1,
+ expect_job_enqueued(
+ job: Jobs::SiteSettingUpdateDefaultTags,
+ args: {
+ id: "default_tags_watching",
+ value: tags.last(2).pluck(:name).join("|"),
+ previous_value: tags.first(2).pluck(:name).join("|"),
+ },
)
+
+ expect(response.status).to eq(200)
end
it "should not update existing users user preference" do
@@ -591,7 +589,29 @@ RSpec.describe Admin::SiteSettingsController do
TagUser.where(tag_id: tags.first.id, notification_level: watching).count
}
- expect(TagUser.where(tag_id: tags.last.id, notification_level: watching).count).to eq(0)
+ expect_not_enqueued_with(
+ job: Jobs::SiteSettingUpdateDefaultTags,
+ args: {
+ id: "default_tags_watching",
+ value: tags.last(2).pluck(:name).join("|"),
+ previous_value: tags.first(2).pluck(:name).join("|"),
+ },
+ )
+
+ expect(response.status).to eq(200)
+ end
+
+ it "should publish a MessageBus informing the correct groups" do
+ messages =
+ MessageBus.track_publish("/site_setting/default_tags_watching/process") do
+ put "/admin/site_settings/default_tags_watching.json",
+ params: {
+ default_tags_watching: tags.last(2).pluck(:name).join("|"),
+ update_existing_user: true,
+ }
+ end
+ expect(messages[0][:data][:group_ids]).to eq([Group::AUTO_GROUPS[:admins]])
+ expect(messages[0][:data][:status]).to eq("enqueued")
end
end
@@ -727,8 +747,70 @@ RSpec.describe Admin::SiteSettingsController do
end
context "when logged in as a non-staff user" do
+ fab!(:user1, :user)
+ fab!(:user2, :user)
+
+ let(:tracking) { NotificationLevels.all[:tracking] }
+ let(:watching) { NotificationLevels.all[:watching] }
+
before { sign_in(user) }
+ context "with default categories" do
+ let(:category_ids) { 3.times.collect { Fabricate(:category).id } }
+
+ before do
+ SiteSetting.default_categories_watching = category_ids.first(2).join("|")
+
+ CategoryUser.create!(
+ category_id: category_ids.last,
+ notification_level: tracking,
+ user: user2,
+ )
+ end
+
+ it "doesn't update default categories" do
+ put "/admin/site_settings/default_categories_watching.json",
+ params: {
+ default_categories_watching: category_ids.last(2).join("|"),
+ update_existing_user: true,
+ }
+
+ expect(response.status).to eq(404)
+
+ expect_not_enqueued_with(job: Jobs::SiteSettingUpdateDefaultCategories)
+
+ expect(
+ CategoryUser.where(category_id: category_ids.last, notification_level: watching).count,
+ ).to eq(0)
+ end
+ end
+
+ context "with default tags" do
+ fab!(:tag_1, :tag)
+ fab!(:tag_2, :tag)
+ fab!(:tag_3, :tag)
+ let(:tags) { [tag_1, tag_2, tag_3] }
+
+ before do
+ SiteSetting.default_tags_watching = tags.first(2).pluck(:name).join("|")
+ TagUser.create!(tag_id: tags.last.id, notification_level: tracking, user: user2)
+ end
+
+ it "doesn't update default categories" do
+ put "/admin/site_settings/default_tags_watching.json",
+ params: {
+ default_tags_watching: tags.last(2).pluck(:name).join("|"),
+ update_existing_user: true,
+ }
+
+ expect(response.status).to eq(404)
+
+ expect_not_enqueued_with(job: Jobs::SiteSettingUpdateDefaultTags)
+
+ expect(TagUser.where(tag_id: tags.last.id, notification_level: watching).count).to eq(0)
+ end
+ end
+
include_examples "site setting update not allowed"
end
end