A platform for community discussion. Free, open, simple.
FIX: Allow managing restricted tags in bulk actions (#40681)
Régis Hanolba25445dd0eb
diff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rbindex f6a4dbbca0d..5dc26230e2e 100644--- a/app/controllers/topics_controller.rb+++ b/app/controllers/topics_controller.rb@@ -1178,6 +1178,9 @@ class TopicsController < ApplicationControllerchanged_topic_ids = operator.perform!result = { topic_ids: changed_topic_ids }result[:errors] = operator.errors if operator.errors.present?+ if operator.tag_category_errors.present?+ result[:tag_category_errors] = operator.tag_category_errors+ endrender_json_dump resultrescue Discourse::InvalidParameters => exrender_json_error(ex, status: 400)diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 21b07a067a3..6f3a924e149 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -4074,6 +4074,9 @@ en:error_topic_count:one: "%{count} topic"other: "%{count} topics"+ tag_not_allowed_in_category:+ one: "%{tags} isn't allowed in the %{category} category."+ other: "These tags aren't allowed in the %{category} category: %{tags}."none:unread: "You have no unread topics."@@ -5848,7 +5851,6 @@ en:category_restrictions:one: "It can only be used in the %{categories} category."other: "It can only be used in these categories: %{categories}."- restricted_to: "Restricted to"no_synonyms: "This tag has no synonyms."edit_synonyms: "Edit Synonyms"add_synonyms_label: "Add synonyms:"diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 189e35ecd23..d439a666c46 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -5825,6 +5825,9 @@ en:invalid:one: "The tag you selected cannot be used"other: "None of the tags you selected can be used"+ tag_not_allowed_in_category:+ one: 'The "%{tags}" tag isn''t allowed in the "%{category}" category.'+ other: 'The following tags aren''t allowed in the "%{category}" category: %{tags}.'in_this_category: "Can't be used in this category"not_allowed: "Can't be used"restricted_to:diff --git a/frontend/discourse/app/components/modal/bulk-topic-actions.gjs b/frontend/discourse/app/components/modal/bulk-topic-actions.gjsindex 8b8a6487aba..ee5dc7738ec 100644--- a/frontend/discourse/app/components/modal/bulk-topic-actions.gjs+++ b/frontend/discourse/app/components/modal/bulk-topic-actions.gjs@@ -10,6 +10,8 @@ import { Promise } from "rsvp";import ManageTagsForm from "discourse/components/modal/bulk-topic-actions/manage-tags-form";import BulkPinOptions from "discourse/components/modal/feature-topic/bulk-pin-options";import { topicLevels } from "discourse/lib/notification-levels";+import renderTag from "discourse/lib/render-tag";+import { escapeExpression } from "discourse/lib/utilities";import Category from "discourse/models/category";import Topic from "discourse/models/topic";import CategoryChooser from "discourse/select-kit/components/category-chooser";@@ -17,6 +19,7 @@ import DButton from "discourse/ui-kit/d-button";import DConditionalLoadingSection from "discourse/ui-kit/d-conditional-loading-section";import DModal from "discourse/ui-kit/d-modal";import DRadioButton from "discourse/ui-kit/d-radio-button";+import { categoryBadgeHTML } from "discourse/ui-kit/helpers/d-category-link";import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";import { i18n } from "discourse-i18n";@@ -102,6 +105,7 @@ export default class BulkTopicActions extends Component {const topicChunks = this._generateTopicChunks(allTopics);const topicIds = [];const mergedErrors = {};+ const mergedTagCategoryErrors = {};const options = {};if (this.model.allowSilent && !this.notifyUsers) {@@ -129,7 +133,14 @@ export default class BulkTopicActions extends Component {allTopics.find((value) => value.id === id));const errors = Object.keys(mergedErrors).length ? mergedErrors : null;- return resolve({ topics, errors });+ const tagCategoryErrors = Object.values(mergedTagCategoryErrors);+ return resolve({+ topics,+ errors,+ tagCategoryErrors: tagCategoryErrors.length+ ? tagCategoryErrors+ : null,+ });}const task = tasks.shift();@@ -144,6 +155,16 @@ export default class BulkTopicActions extends Component {mergedErrors[msg] = (mergedErrors[msg] || 0) + count;}}+ if (result?.tag_category_errors) {+ for (const error of result.tag_category_errors) {+ const key = `${error.category_id}:${error.tag_names.join(",")}`;+ if (mergedTagCategoryErrors[key]) {+ mergedTagCategoryErrors[key].count += error.count;+ } else {+ mergedTagCategoryErrors[key] = { ...error };+ }+ }+ }resolveNextTask();} catch {reject();@@ -281,17 +302,36 @@ export default class BulkTopicActions extends Component {}get failedTopicCount() {- if (!this.failureMessages) {- return 0;- }- return this.failureMessages.reduce((sum, e) => sum + e.count, 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,- }));+ get hasFailures() {+ return this.failedTopicCount > 0;+ }++ _buildTagCategoryError(error) {+ const category = Category.findById(error.category_id);+ return i18n("topics.bulk.tag_not_allowed_in_category", {+ count: error.tag_names.length,+ tags: error.tag_names.map((name) => renderTag(name)).join(" "),+ category: category+ ? categoryBadgeHTML(category)+ : escapeExpression(error.category_name),+ });+ }++ _showErrors(errors, tagCategoryErrors, successCount, totalCount) {+ this.failureMessages = [+ ...(tagCategoryErrors || []).map((error) => ({+ message: this._buildTagCategoryError(error),+ count: error.count,+ trustHtml: true,+ })),+ ...Object.entries(errors || {}).map(([message, count]) => ({+ message,+ count,+ })),+ ];this.successTopicCount = successCount;this.skippedTopicCount = totalCount - successCount - this.failedTopicCount;this.loading = false;@@ -311,11 +351,11 @@ export default class BulkTopicActions extends Component {const result = await this.perform(operation);if (result) {- const { topics, errors } = result;+ const { topics, errors, tagCategoryErrors } = result;topics.forEach(cb);- if (errors) {- this._showErrors(errors, topics.length, totalCount);+ if (errors || tagCategoryErrors) {+ this._showErrors(errors, tagCategoryErrors, topics.length, totalCount);} else {this.model.refreshClosure?.();this.args.closeModal();@@ -332,9 +372,9 @@ export default class BulkTopicActions extends Component {const result = await this.perform(operation);if (result) {- const { topics, errors } = result;- if (errors) {- this._showErrors(errors, topics.length, totalCount);+ const { topics, errors, tagCategoryErrors } = result;+ if (errors || tagCategoryErrors) {+ this._showErrors(errors, tagCategoryErrors, topics.length, totalCount);} else {this.model.refreshClosure?.().then(() => {this.args.closeModal();@@ -436,7 +476,7 @@ export default class BulkTopicActions extends Component {@isLoading={{this.loading}}@title={{i18n "topics.bulk.performing"}}>- {{#if this.failureMessages}}+ {{#if this.hasFailures}}<div class="topic-bulk-actions-modal__errors">{{#if this.successTopicCount}}<p>{{trustHTML@@ -457,7 +497,12 @@ export default class BulkTopicActions extends Component {}}</p><ul>{{#each this.failureMessages as |error|}}- <li>{{error.message}}+ <li>+ {{#if error.trustHtml}}+ {{trustHTML error.message}}+ {{else}}+ {{error.message}}+ {{/if}}({{i18n"topics.bulk.error_topic_count"count=error.count@@ -542,7 +587,7 @@ export default class BulkTopicActions extends Component {</:body><:footer>- {{#if this.failureMessages}}+ {{#if this.hasFailures}}<DButton@action={{this.closeWithRefresh}}@label="close"diff --git a/frontend/discourse/app/components/modal/bulk-topic-actions/manage-tags-form.gjs b/frontend/discourse/app/components/modal/bulk-topic-actions/manage-tags-form.gjsindex 1d3ff84a6e8..450ca6b9503 100644--- a/frontend/discourse/app/components/modal/bulk-topic-actions/manage-tags-form.gjs+++ b/frontend/discourse/app/components/modal/bulk-topic-actions/manage-tags-form.gjs@@ -4,6 +4,7 @@ import { action } from "@ember/object";import { trustHTML } from "@ember/template";import Form from "discourse/components/form";import { bind } from "discourse/lib/decorators";+import { not } from "discourse/truth-helpers";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";@@ -181,7 +182,7 @@ export default class ManageTagsForm extends Component {@onSet={{this.afterFieldSet}}as |field|>- <field.Control />+ <field.Control @showAllTags={{true}} /></form.Field>{{/if}}@@ -207,7 +208,10 @@ export default class ManageTagsForm extends Component {@onSet={{this.afterFieldSet}}as |field|>- <field.Control @categoryId={{@categoryId}} />+ <field.Control+ @categoryId={{@categoryId}}+ @showAllTags={{not @categoryId}}+ /></form.Field><form.Container@@ -231,6 +235,7 @@ export default class ManageTagsForm extends Component {as |field|><field.Control+ @showAllTags={{true}}@maximum={{1}}@placeholder="topic_bulk_actions.manage_tags.replace.from_placeholder"@blockedTags={{this.blockedTagsFor@@ -264,6 +269,7 @@ export default class ManageTagsForm extends Component {><field.Control@categoryId={{@categoryId}}+ @showAllTags={{not @categoryId}}@maximum={{1}}@placeholder="topic_bulk_actions.manage_tags.replace.to_placeholder"@blockedTags={{this.blockedTagsFordiff --git a/frontend/discourse/app/components/tag-settings.gjs b/frontend/discourse/app/components/tag-settings.gjsindex d7ec96ffb0c..9a38ae67cd4 100644--- a/frontend/discourse/app/components/tag-settings.gjs+++ b/frontend/discourse/app/components/tag-settings.gjs@@ -16,6 +16,7 @@ import { eq } from "discourse/truth-helpers";import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";import DHorizontalOverflowNav from "discourse/ui-kit/d-horizontal-overflow-nav";import DPageHeader from "discourse/ui-kit/d-page-header";+import { categoryBadgeHTML } from "discourse/ui-kit/helpers/d-category-link";import { i18n } from "discourse-i18n";export default class TagSettings extends Component {@@ -105,13 +106,14 @@ export default class TagSettings extends Component {}if (this.hasCategories) {- const categoriesHtml = this.args.tag.categories- .map(- (cat) =>- `<a href="/c/${cat.slug}/${cat.id}" class="badge-category">${cat.name}</a>`- )- .join(" ");- parts.push(`${i18n("tagging.restricted_to")} ${categoriesHtml}.`);+ parts.push(+ i18n("tagging.category_restrictions", {+ count: this.args.tag.categories.length,+ categories: this.args.tag.categories+ .map((cat) => categoryBadgeHTML(cat))+ .join(" "),+ })+ );} else if (this.isCategoryRestricted) {parts.push(i18n("tagging.category_restricted"));}diff --git a/lib/discourse_tagging.rb b/lib/discourse_tagging.rbindex 1abf3c57647..4551ad32666 100644--- a/lib/discourse_tagging.rb+++ b/lib/discourse_tagging.rb@@ -243,7 +243,20 @@ module DiscourseTaggingreturn false unless validate_required_tags_from_group(guardian, topic, category, tags)if tags.size == 0- topic.errors.add(:base, I18n.t("tags.forbidden.invalid", count: new_tag_names.size))+ not_allowed = tag_names_not_allowed_in_category(category, new_tag_names)+ if not_allowed.present?+ topic.errors.add(+ :base,+ I18n.t(+ "tags.forbidden.tag_not_allowed_in_category",+ count: not_allowed.size,+ tags: not_allowed.sort.join(", "),+ category: category.name,+ ),+ )+ else+ topic.errors.add(:base, I18n.t("tags.forbidden.invalid", count: new_tag_names.size))+ endreturn falseend@@ -326,23 +339,36 @@ module DiscourseTaggingsuccessend- def self.validate_category_restricted_tags(guardian, model, category, tags = [])- return true if tags.blank? || category.blank?-- tags = tags.map(&:name) if Tag === tags[0]- tags_restricted_to_categories = Hash.new { |h, k| h[k] = Set.new }-- query = Tag.where(name: tags)+ def self.restricted_category_ids_by_tag_name(tag_names)+ restricted_to = Hash.new { |h, k| h[k] = Set.new }+ return restricted_to if tag_names.blank?+ query = Tag.where(name: tag_names)query.joins(tag_groups: :categories).pluck(:name, "categories.id")- .each { |(tag, cat_id)| tags_restricted_to_categories[tag] << cat_id }-+ .each { |(name, category_id)| restricted_to[name] << category_id }query.joins(:categories).pluck(:name, "categories.id")- .each { |(tag, cat_id)| tags_restricted_to_categories[tag] << cat_id }+ .each { |(name, category_id)| restricted_to[name] << category_id }+ restricted_to+ end++ def self.tag_names_not_allowed_in_category(category, tag_names, restricted_to: nil)+ return [] if category.blank? || tag_names.blank?++ restricted_to ||= restricted_category_ids_by_tag_name(tag_names)+ tag_names.select do |name|+ restricted_to.key?(name) && !restricted_to[name].include?(category.id)+ end+ end++ def self.validate_category_restricted_tags(guardian, model, category, tags = [])+ return true if tags.blank? || category.blank?++ tags = tags.map(&:name) if Tag === tags[0]+ tags_restricted_to_categories = restricted_category_ids_by_tag_name(tags)unallowed_tags =tags_restricted_to_categories.keys.select do |tag|diff --git a/lib/topics_bulk_action.rb b/lib/topics_bulk_action.rbindex 13b9b694958..6d774e762cb 100644--- a/lib/topics_bulk_action.rb+++ b/lib/topics_bulk_action.rb@@ -9,9 +9,26 @@ class TopicsBulkAction@operation = operation@changed_ids = []@errors = Hash.new(0)+ @restricted_tag_errors = Hash.new(0)@options = optionsend+ def tag_category_errors+ return [] if @restricted_tag_errors.empty?++ category_names =+ Category.where(id: @restricted_tag_errors.keys.map(&:first).uniq).pluck(:id, :name).to_h++ @restricted_tag_errors.map do |(category_id, tag_names), count|+ {+ category_id: category_id,+ category_name: category_names[category_id],+ tag_names: tag_names,+ count: count,+ }+ end+ end+def self.operations@operations ||= %w[change_category@@ -374,11 +391,31 @@ class TopicsBulkAction@changed_ids << topic.idtrueelse- topic.errors.full_messages.each { |msg| @errors[msg] += 1 }+ not_allowed =+ DiscourseTagging.tag_names_not_allowed_in_category(+ topic.category,+ tag_names,+ restricted_to: restricted_category_ids_for(tag_names),+ )+ if topic.category && not_allowed.present?+ @restricted_tag_errors[[topic.category_id, not_allowed.sort]] += 1+ else+ topic.errors.full_messages.each { |msg| @errors[msg] += 1 }+ endfalseendend+ def restricted_category_ids_for(tag_names)+ @restricted_tag_cache ||= {}+ uncached = tag_names - @restricted_tag_cache.keys+ if uncached.present?+ found = DiscourseTagging.restricted_category_ids_by_tag_name(uncached)+ uncached.each { |name| @restricted_tag_cache[name] = found.key?(name) ? found[name] : nil }+ end+ @restricted_tag_cache.slice(*tag_names).compact+ end+def resolve_tag_namesif @operation[:tag_ids].present?Tag.where(id: @operation[:tag_ids]).pluck(:name)@@ -411,7 +448,7 @@ class TopicsBulkActionenddef topics_with_tags- @topics_with_tags ||= topics.includes(:first_post, :tags)+ @topics_with_tags ||= topics.includes(:first_post, :tags, :category)enddef dismiss_topics_since_datediff --git a/spec/lib/discourse_tagging_spec.rb b/spec/lib/discourse_tagging_spec.rbindex a3fb4444317..1bb471d6fd3 100644--- a/spec/lib/discourse_tagging_spec.rb+++ b/spec/lib/discourse_tagging_spec.rb@@ -1066,6 +1066,36 @@ RSpec.describe DiscourseTagging doenddescribe "tag_topic_by_names" do+ context "with a tag restricted to other categories" do+ fab!(:allowed_category, :category)+ fab!(:other_category, :category)+ fab!(:restricted_tag_group) { Fabricate(:tag_group, tag_names: ["events"]) }+ fab!(:topic_in_other_category) { Fabricate(:topic, category: other_category) }++ before do+ CategoryTagGroup.create!(category: allowed_category, tag_group: restricted_tag_group)+ end++ it "names the offending category instead of a generic error, even for admins" do+ valid =+ DiscourseTagging.tag_topic_by_names(+ topic_in_other_category,+ Guardian.new(admin),+ ["events"],+ )++ expect(valid).to eq(false)+ expect(topic_in_other_category.errors[:base]&.first).to eq(+ I18n.t(+ "tags.forbidden.tag_not_allowed_in_category",+ count: 1,+ tags: "events",+ category: other_category.name,+ ),+ )+ end+ end+context "with visible but restricted tags" dofab!(:topic)diff --git a/spec/system/topic_bulk_select_spec.rb b/spec/system/topic_bulk_select_spec.rbindex a42a0dafb8c..8af2c170c73 100644--- a/spec/system/topic_bulk_select_spec.rb+++ b/spec/system/topic_bulk_select_spec.rb@@ -240,6 +240,75 @@ describe "Topic bulk select" doexpect(topic_list).to have_topic_tags(topic, tags: [restricted_tag, tag1])expect(topic_list).to have_topic_tags(topic_2, tags: [restricted_tag, tag1])end++ it "can remove and replace-away a restricted tag" do+ restricted_tag_group = Fabricate(:tag_group)+ restricted_to_remove = Fabricate(:tag)+ restricted_to_replace = Fabricate(:tag)+ [restricted_to_remove, restricted_to_replace].each do |t|+ TagGroupMembership.create!(tag: t, tag_group: restricted_tag_group)+ end+ CategoryTagGroup.create!(category: category, tag_group: restricted_tag_group)+ category.update!(allow_global_tags: true)+ topic.update!(tags: [restricted_to_remove, restricted_to_replace])++ modal = open_manage_tags_modal([topic, topic_2])++ modal.remove_tags(restricted_to_remove.name)+ modal.select_replace_from(restricted_to_replace.name)+ modal.select_replace_to(tag1.name)++ modal.click_confirm++ expect(topic_list).to have_topic_tags(topic, tags: [tag1])+ end+ end++ context "when selecting topics across multiple categories" do+ fab!(:category_a, :category)+ fab!(:category_b, :category)+ fab!(:restricted_tag_group, :tag_group)+ fab!(:restricted_tag, :tag)++ before do+ topic.update!(category_id: category_a.id)+ topic_2.update!(category_id: category_b.id)+ TagGroupMembership.create!(tag: restricted_tag, tag_group: restricted_tag_group)+ end++ it "lets a restricted tag be added when every selected category allows it" do+ CategoryTagGroup.create!(category: category_a, tag_group: restricted_tag_group)+ CategoryTagGroup.create!(category: category_b, tag_group: restricted_tag_group)++ modal = open_manage_tags_modal([topic, topic_2])+ modal.add_tags(restricted_tag.name)+ modal.click_confirm++ expect(topic_list).to have_topic_tags(topic, tags: [restricted_tag])+ expect(topic_list).to have_topic_tags(topic_2, tags: [restricted_tag])+ end++ it "reports an error for topics whose category forbids the tag" do+ CategoryTagGroup.create!(category: category_a, tag_group: restricted_tag_group)++ modal = open_manage_tags_modal([topic, topic_2])+ modal.add_tags(restricted_tag.name)+ modal.click_confirm++ expect(topic_bulk_actions_modal).to have_errors+ expect(page).to have_css(+ ".topic-bulk-actions-modal__errors .badge-category",+ text: category_b.name,+ )+ expect(page).to have_css(+ ".topic-bulk-actions-modal__errors .discourse-tag",+ text: restricted_tag.name,+ )+ expect(page).to have_css("#bulk-topics-close")+ expect(page).to have_no_css("#bulk-topics-confirm")+ expect(topic.reload.tags).to include(restricted_tag)+ expect(topic_2.reload.tags).not_to include(restricted_tag)+ endendend