A platform for community discussion. Free, open, simple.
UX: Show bulk action errors in modal instead of generic toast (#37807)
Régis Hanol01c17ee5e753
diff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rbindex 4e1dafcab2e..55693f840a7 100644--- a/app/controllers/topics_controller.rb+++ b/app/controllers/topics_controller.rb@@ -1102,7 +1102,9 @@ class TopicsController < ApplicationControlleroperator = TopicsBulkAction.new(current_user, topic_ids, operation, group: operation[:group])hijack(info: "topics bulk action #{operation[:type]}") dochanged_topic_ids = operator.perform!- render_json_dump topic_ids: changed_topic_ids+ result = { topic_ids: changed_topic_ids }+ result[:errors] = operator.errors if operator.errors.present?+ render_json_dump resultendenddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 0b06f2ef132..dbed072c220 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -3682,9 +3682,18 @@ en:notify: "Notify users of this change."performing: "Performing bulk operations, please wait…"completed: "Bulk operations completed successfully!"+ completed_count:+ one: "<b>%{count}</b> topic was updated."+ other: "<b>%{count}</b> topics were updated."not_completed:- one: "Bulk operation could not be completed for <strong>%{count}</strong> topic"- other: "Bulk operation could not be completed for <strong>%{count}</strong> topics"+ one: "<b>%{count}</b> topic could not be updated:"+ other: "<b>%{count}</b> topics could not be updated:"+ skipped_count:+ one: "<b>%{count}</b> topic was already up to date."+ other: "<b>%{count}</b> topics were already up to date."+ error_topic_count:+ one: "%{count} topic"+ other: "%{count} topics"none:unread: "You have no unread topics."diff --git a/frontend/discourse/app/components/modal/bulk-topic-actions.gjs b/frontend/discourse/app/components/modal/bulk-topic-actions.gjsindex 02e7f5af065..1a15d56102d 100644--- a/frontend/discourse/app/components/modal/bulk-topic-actions.gjs+++ b/frontend/discourse/app/components/modal/bulk-topic-actions.gjs@@ -37,7 +37,9 @@ export default class BulkTopicActions extends Component {@tracked errors;@tracked notifyUsers = false;@tracked closeNote = null;- @tracked failedTopicCount = 0;+ @tracked failureMessages = null;+ @tracked successTopicCount = 0;+ @tracked skippedTopicCount = 0;@tracked notificationLevelId = null;@@ -94,6 +96,7 @@ export default class BulkTopicActions extends Component {const allTopics = this.model.bulkSelectHelper.selected;const topicChunks = this._generateTopicChunks(allTopics);const topicIds = [];+ const mergedErrors = {};const options = {};if (this.model.allowSilent && !this.notifyUsers) {@@ -116,7 +119,8 @@ export default class BulkTopicActions extends Component {const topics = topicIds.map((id) =>allTopics.find((value) => value.id === id));- return resolve(topics);+ const errors = Object.keys(mergedErrors).length ? mergedErrors : null;+ return resolve({ topics, errors });}const task = tasks.shift();@@ -126,6 +130,11 @@ export default class BulkTopicActions extends Component {if (result?.topic_ids) {topicIds.push(...result.topic_ids);}+ if (result?.errors) {+ for (const [msg, count] of Object.entries(result.errors)) {+ mergedErrors[msg] = (mergedErrors[msg] || 0) + count;+ }+ }resolveNextTask();} catch {reject();@@ -248,15 +257,6 @@ export default class BulkTopicActions extends Component {duration: "short",data: { message: i18n("generic_error") },});- } else if (this.failedTopicCount > 0) {- this.toasts.warning({- duration: "short",- data: {- message: htmlSafe(- i18n("topics.bulk.not_completed", { count: this.failedTopicCount })- ),- },- });} else {this.toasts.success({duration: "short",@@ -265,32 +265,67 @@ export default class BulkTopicActions extends Component {}}+ get failedTopicCount() {+ if (!this.failureMessages) {+ return 0;+ }+ return this.failureMessages.reduce((sum, e) => sum + e.count, 0);+ }++ _showErrors(errors, successCount, totalCount) {+ this.failureMessages = Object.entries(errors).map(([message, count]) => ({+ message,+ count,+ }));+ this.successTopicCount = successCount;+ this.skippedTopicCount = totalCount - successCount - this.failedTopicCount;+ this.loading = false;+ }++ @action+ closeWithRefresh() {+ this.model.refreshClosure?.();+ this.model.bulkSelectHelper.toggleBulkSelect();+ this.args.closeModal();+ }+@actionasync forEachPerformed(operation, cb) {- const selectedCount = this.model.bulkSelectHelper.selected.length;- const topics = await this.perform(operation);+ const totalCount = this.model.bulkSelectHelper.selected.length;+ const result = await this.perform(operation);- if (topics) {+ if (result) {+ const { topics, errors } = result;topics.forEach(cb);- this.failedTopicCount = selectedCount - topics.length;- this.model.refreshClosure?.();- this.args.closeModal();- this.model.bulkSelectHelper.toggleBulkSelect();- this.showToast();++ if (errors) {+ this._showErrors(errors, topics.length, totalCount);+ } else {+ this.model.refreshClosure?.();+ this.args.closeModal();+ this.model.bulkSelectHelper.toggleBulkSelect();+ this.showToast();+ }}}@actionasync performAndRefresh(operation) {- const selectedCount = this.model.bulkSelectHelper.selected.length;- const topics = await this.perform(operation);-- this.failedTopicCount = topics ? selectedCount - topics.length : 0;- this.model.refreshClosure?.().then(() => {- this.args.closeModal();- this.model.bulkSelectHelper.toggleBulkSelect();- this.showToast();- });+ const totalCount = this.model.bulkSelectHelper.selected.length;+ const result = await this.perform(operation);++ if (result) {+ const { topics, errors } = result;+ if (errors) {+ this._showErrors(errors, topics.length, totalCount);+ } else {+ this.model.refreshClosure?.().then(() => {+ this.args.closeModal();+ this.model.bulkSelectHelper.toggleBulkSelect();+ this.showToast();+ });+ }+ }}get isTagAction() {@@ -381,119 +416,161 @@ export default class BulkTopicActions extends Component {@isLoading={{this.loading}}@title={{i18n "topics.bulk.performing"}}>- <div class="topic-bulk-actions-modal__selection-info">-- {{#if this.showSoleCategoryTip}}- {{htmlSafe- (i18n- "topics.bulk.selected_sole_category"- )- }}- {{htmlSafe this.soleCategoryBadgeHTML}}- {{else}}- {{htmlSafe- (i18n- "topics.bulk.selected"- )- }}+ {{#if this.failureMessages}}+ <div class="topic-bulk-actions-modal__errors">+ {{#if this.successTopicCount}}+ <p>{{htmlSafe+ (i18n+ "topics.bulk.completed_count" count=this.successTopicCount+ )+ }}</p>+ {{/if}}+ {{#if this.skippedTopicCount}}+ <p>{{htmlSafe+ (i18n+ "topics.bulk.skipped_count" count=this.skippedTopicCount+ )+ }}</p>+ {{/if}}+ <p>{{htmlSafe+ (i18n "topics.bulk.not_completed" count=this.failedTopicCount)+ }}</p>+ <ul>+ {{#each this.failureMessages as |error|}}+ <li>{{error.message}}+ ({{i18n+ "topics.bulk.error_topic_count"+ count=error.count+ }})</li>+ {{/each}}+ </ul>+ </div>+ {{else}}+ <div class="topic-bulk-actions-modal__selection-info">++ {{#if this.showSoleCategoryTip}}+ {{htmlSafe+ (i18n+ "topics.bulk.selected_sole_category"+ )+ }}+ {{htmlSafe this.soleCategoryBadgeHTML}}+ {{else}}+ {{htmlSafe+ (i18n+ "topics.bulk.selected"+ )+ }}++ {{/if}}+ </div>+ {{#if this.isCategoryAction}}+ <p>+ <CategoryChooser+ @value={{this.categoryId}}+ @onChange={{this.onCategoryChange}}+ />+ </p>{{/if}}- </div>-- {{#if this.isCategoryAction}}- <p>- <CategoryChooser- @value={{this.categoryId}}- @onChange={{this.onCategoryChange}}- />- </p>- {{/if}}- {{#if this.isNotificationAction}}- <div class="bulk-notification-list">- {{#each this.notificationLevels as |level|}}- <div class="controls">- <label class="radio notification-level-radio checkbox-label">- <RadioButton- @value={{level.id}}- @name="notification_level"- @selection={{this.notificationLevelId}}- />- <strong>{{level.name}}</strong>- <div class="description">{{htmlSafe- level.description- }}</div>- </label>- </div>- {{/each}}- </div>- {{/if}}+ {{#if this.isNotificationAction}}+ <div class="bulk-notification-list">+ {{#each this.notificationLevels as |level|}}+ <div class="controls">+ <label+ class="radio notification-level-radio checkbox-label"+ >+ <RadioButton+ @value={{level.id}}+ @name="notification_level"+ @selection={{this.notificationLevelId}}+ />+ <strong>{{level.name}}</strong>+ <div class="description">{{htmlSafe+ level.description+ }}</div>+ </label>+ </div>+ {{/each}}+ </div>+ {{/if}}- {{#if this.isTagAction}}- <p><TagChooser- @tags={{this.tags}}- @categoryId={{this.soleCategoryId}}- /></p>- {{/if}}+ {{#if this.isTagAction}}+ <p><TagChooser+ @tags={{this.tags}}+ @categoryId={{this.soleCategoryId}}+ /></p>+ {{/if}}- {{#if this.activeComponent}}- {{component- this.activeComponent- onRegisterAction=this.registerCustomAction- topics=this.activeComponentProps.topics- afterBulkAction=this.activeComponentProps.afterBulkAction- }}- {{/if}}+ {{#if this.activeComponent}}+ {{component+ this.activeComponent+ onRegisterAction=this.registerCustomAction+ topics=this.activeComponentProps.topics+ afterBulkAction=this.activeComponentProps.afterBulkAction+ }}+ {{/if}}- {{#if this.isCloseAction}}- <div class="bulk-close-note-section">- <label>- {{i18n "topic_bulk_actions.close_topics.note"}} <span- class="label-optional"- >{{i18n "topic_bulk_actions.close_topics.optional"}}</span>- </label>-- <textarea- id="bulk-close-note"- {{on "input" this.updateCloseNote}}- {{autoFocus}}- >{{this.closeNote}}</textarea>- </div>+ {{#if this.isCloseAction}}+ <div class="bulk-close-note-section">+ <label>+ {{i18n "topic_bulk_actions.close_topics.note"}} <span+ class="label-optional"+ >{{i18n "topic_bulk_actions.close_topics.optional"}}</span>+ </label>++ <textarea+ id="bulk-close-note"+ {{on "input" this.updateCloseNote}}+ {{autoFocus}}+ >{{this.closeNote}}</textarea>+ </div>+ {{/if}}{{/if}}</ConditionalLoadingSection></:body><:footer>- {{#if @model.allowSilent}}- <div class="topic-bulk-actions-options">- <label- for="topic-bulk-action-options__notify"- class="checkbox-label"- >- <Input- id="topic-bulk-action-options__notify"- @type="checkbox"- @checked={{this.notifyUsers}}- />{{i18n "topics.bulk.notify"}}</label>- </div>- {{/if}}+ {{#if this.failureMessages}}+ <DButton+ @action={{this.closeWithRefresh}}+ @label="close"+ class="btn-primary"+ id="bulk-topics-close"+ />+ {{else}}+ {{#if @model.allowSilent}}+ <div class="topic-bulk-actions-options">+ <label+ for="topic-bulk-action-options__notify"+ class="checkbox-label"+ >+ <Input+ id="topic-bulk-action-options__notify"+ @type="checkbox"+ @checked={{this.notifyUsers}}+ />{{i18n "topics.bulk.notify"}}</label>+ </div>+ {{/if}}- <DButton- @action={{@closeModal}}- @label="cancel"- class="btn-transparent d-modal-cancel"- id="bulk-topics-cancel"- />- <DButton- @action={{this.performAction}}- @disabled={{this.disabledSubmit}}- @icon="check"- @label="topics.bulk.confirm"- id="bulk-topics-confirm"- class="btn-primary"- />+ <DButton+ @action={{@closeModal}}+ @label="cancel"+ class="btn-transparent d-modal-cancel"+ id="bulk-topics-cancel"+ />+ <DButton+ @action={{this.performAction}}+ @disabled={{this.disabledSubmit}}+ @icon="check"+ @label="topics.bulk.confirm"+ id="bulk-topics-confirm"+ class="btn-primary"+ />+ {{/if}}</:footer></DModal>diff --git a/lib/topics_bulk_action.rb b/lib/topics_bulk_action.rbindex 1168dee3f67..fdc050a6dbf 100644--- a/lib/topics_bulk_action.rb+++ b/lib/topics_bulk_action.rb@@ -1,11 +1,14 @@# frozen_string_literal: trueclass TopicsBulkAction+ attr_reader :errors+def initialize(user, topic_ids, operation, options = {})@user = user@topic_ids = topic_ids@operation = operation@changed_ids = []+ @errors = Hash.new(0)@options = optionsend@@ -39,8 +42,17 @@ class TopicsBulkActionif TopicsBulkAction.operations.exclude?(@operation[:type])raise Discourse::InvalidParameters.new(:operation)end+# careful these are private methods, we need sendsend(@operation[:type])++ if @errors.present?+ error_details = @errors.map { |msg, count| "- #{msg} (#{count} topics)" }.join("\n")+ Rails.logger.warn(+ "Bulk '#{@operation[:type]}' by @#{@user.username} (id=#{@user.id}) failed for #{@errors.values.sum} topics:\n#{error_details}",+ )+ end+@changed_ids.sortend@@ -147,7 +159,11 @@ class TopicsBulkActionupdatable_topics.each do |t|if guardian.can_edit?(t)changes = { category_id: @operation[:category_id] }- @changed_ids << t.id if t.first_post.revise(@user, changes, opts)+ if t.first_post.revise(@user, changes, opts)+ @changed_ids << t.id+ else+ t.errors.full_messages.each { |msg| @errors[msg] += 1 }+ endendendend@@ -239,14 +255,21 @@ class TopicsBulkActiontopics.each do |t|if guardian.can_edit?(t)- if tag_ids.present?- DiscourseTagging.tag_topic_by_ids(t, guardian, tag_ids)- elsif tag_names.present?- DiscourseTagging.tag_topic_by_names(t, guardian, tag_names)+ success =+ if tag_ids.present?+ DiscourseTagging.tag_topic_by_ids(t, guardian, tag_ids)+ elsif tag_names.present?+ DiscourseTagging.tag_topic_by_names(t, guardian, tag_names)+ else+ t.tags = []+ true+ end++ if success+ @changed_ids << t.idelse- t.tags = []+ t.errors.full_messages.each { |msg| @errors[msg] += 1 }end- @changed_ids << t.idendendend@@ -256,12 +279,20 @@ class TopicsBulkActiontopics.each do |t|if guardian.can_edit?(t)- if tag_ids.present?- DiscourseTagging.tag_topic_by_ids(t, guardian, tag_ids, append: true)- elsif tag_names.present?- DiscourseTagging.tag_topic_by_names(t, guardian, tag_names, append: true)+ success =+ if tag_ids.present?+ DiscourseTagging.tag_topic_by_ids(t, guardian, tag_ids, append: true)+ elsif tag_names.present?+ DiscourseTagging.tag_topic_by_names(t, guardian, tag_names, append: true)+ else+ true+ end++ if success+ @changed_ids << t.id+ else+ t.errors.full_messages.each { |msg| @errors[msg] += 1 }end- @changed_ids << t.idendendenddiff --git a/spec/lib/topics_bulk_action_spec.rb b/spec/lib/topics_bulk_action_spec.rbindex f529d1270f3..9787eef2dc8 100644--- a/spec/lib/topics_bulk_action_spec.rb+++ b/spec/lib/topics_bulk_action_spec.rb@@ -338,6 +338,31 @@ RSpec.describe TopicsBulkAction doexpect(topic_ids).to eq([])expect(topic_with_tag.reload.category).to eq(original_category)end++ it "logs a warning with error details" do+ Rails.logger.expects(:warn).with(includes("restricted-tag"))++ TopicsBulkAction.new(+ admin,+ [topic_with_tag.id],+ type: "change_category",+ category_id: destination_category.id,+ ).perform!+ end++ it "exposes errors via attr_reader" do+ operator =+ TopicsBulkAction.new(+ admin,+ [topic_with_tag.id],+ type: "change_category",+ category_id: destination_category.id,+ )+ operator.perform!++ expect(operator.errors).to be_present+ expect(operator.errors.values.sum).to eq(1)+ endendcontext "when destination category has the same tag group as source" do@@ -552,6 +577,27 @@ RSpec.describe TopicsBulkAction doendend+ context "when tagging fails due to tag restrictions" do+ fab!(:restricted_tag) { Fabricate(:tag, name: "restricted-tag") }+ fab!(:tag_group) do+ Fabricate(:tag_group, tags: [restricted_tag], permissions: { staff: :full })+ end++ it "does not include the topic in changed_ids and logs a warning" do+ Rails.logger.expects(:warn).with(includes("restricted-tag"))++ topic_ids =+ TopicsBulkAction.new(+ topic.user,+ [topic.id],+ type: "change_tags",+ tag_ids: [restricted_tag.id],+ ).perform!++ expect(topic_ids).to eq([])+ end+ end+context "when the user can't edit the topic" dofab!(:tag3, :tag)@@ -606,6 +652,28 @@ RSpec.describe TopicsBulkAction doendend+ context "when tagging fails due to tag restrictions" do+ fab!(:restricted_tag) { Fabricate(:tag, name: "restricted-tag") }+ fab!(:tag_group) do+ Fabricate(:tag_group, tags: [restricted_tag], permissions: { staff: :full })+ end++ it "does not include the topic in changed_ids and logs a warning" do+ Rails.logger.expects(:warn).with(includes("restricted-tag"))++ topic_ids =+ TopicsBulkAction.new(+ topic.user,+ [topic.id],+ type: "append_tags",+ tag_ids: [restricted_tag.id],+ ).perform!++ expect(topic_ids).to eq([])+ expect(topic.reload.tags).to contain_exactly(tag1, tag2)+ end+ end+context "when the user can't edit the topic" doit "doesn't change the tags" doGuardian.any_instance.expects(:can_edit?).returns(false)diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rbindex 1d27bc05ba3..fa08f13e36c 100644--- a/spec/requests/topics_controller_spec.rb+++ b/spec/requests/topics_controller_spec.rb@@ -4220,6 +4220,31 @@ RSpec.describe TopicsController doexpect(topic.reload.tags).to include(tag1)end+ it "includes errors in the response when operations partially fail" do+ sign_in(Fabricate(:admin))++ restricted_tag = Fabricate(:tag, name: "restricted-tag")+ source_category = Fabricate(:category, tags: [restricted_tag])+ destination_category = Fabricate(:category, tags: [Fabricate(:tag, name: "other-tag")])+ topic_with_tag = Fabricate(:topic, category: source_category, tags: [restricted_tag])+ Fabricate(:post, topic: topic_with_tag)++ put "/topics/bulk.json",+ params: {+ topic_ids: [topic_with_tag.id],+ operation: {+ type: "change_category",+ category_id: destination_category.id,+ },+ }++ expect(response.status).to eq(200)+ json = response.parsed_body+ expect(json["topic_ids"]).to eq([])+ expect(json["errors"]).to be_present+ expect(json["errors"].values.sum).to eq(1)+ end+context "with private message" dofab!(:group) doFabricate(:group, messageable_level: Group::ALIAS_LEVELS[:everyone]).tap do |g|diff --git a/spec/system/page_objects/modals/topic_bulk_actions.rb b/spec/system/page_objects/modals/topic_bulk_actions.rbindex 96861182117..5cc7132251c 100644--- a/spec/system/page_objects/modals/topic_bulk_actions.rb+++ b/spec/system/page_objects/modals/topic_bulk_actions.rb@@ -43,6 +43,14 @@ module PageObjectshas_no_css?(PageObjects::Components::CategoryBadge.new.category_selector(category))endend++ def has_errors?(text = nil)+ if text+ has_css?("#{MODAL_SELECTOR}__errors", text: text)+ else+ has_css?("#{MODAL_SELECTOR}__errors")+ end+ endendendenddiff --git a/spec/system/topic_bulk_select_spec.rb b/spec/system/topic_bulk_select_spec.rbindex c4a0e5ec912..d256022587a 100644--- a/spec/system/topic_bulk_select_spec.rb+++ b/spec/system/topic_bulk_select_spec.rb@@ -453,15 +453,13 @@ describe "Topic bulk select", type: :system dofab!(:destination_category, :category)fab!(:restricted_tag, :tag)- let(:toasts) { PageObjects::Components::Toasts.new }-before doSiteSetting.tagging_enabled = truetopics.first.update!(tags: [restricted_tag])topics.first.category.update!(tags: [restricted_tag])end- it "shows a warning when some topics cannot be moved due to tag restrictions" do+ it "shows errors in the modal when some topics cannot be moved due to tag restrictions" dooriginal_category = topics.first.categorysign_in(admin)visit("/latest")@@ -472,7 +470,7 @@ describe "Topic bulk select", type: :system dotopic_bulk_actions_modal.category_selector.select_row_by_value(destination_category.id)topic_bulk_actions_modal.click_bulk_topics_confirm- expect(toasts).to have_warning("could not be completed")+ expect(topic_bulk_actions_modal).to have_errors("could not be updated")expect(topics.first.reload.category).to eq(original_category)end