A platform for community discussion. Free, open, simple.
FIX: resolve localized tag names via ID when creating or editing topics (#39026)
Natalie Tay5080cebb0a86
diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rbindex 1dfa0bdff99..4ad243481f0 100644--- a/app/controllers/posts_controller.rb+++ b/app/controllers/posts_controller.rb@@ -983,7 +983,11 @@ class PostsController < ApplicationControllerendPostRevisor.tracked_topic_fields.each_key do |f|- params.permit(f => [])+ if f == :tags+ params.permit(tags: %i[id name])+ else+ params.permit(f => [])+ endresult[f] = params[f] if params.has_key?(f)enddiff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rbindex b628fd5433d..4715deb65d2 100644--- a/app/controllers/topics_controller.rb+++ b/app/controllers/topics_controller.rb@@ -417,16 +417,17 @@ class TopicsController < ApplicationControllerreturn render_json_error(I18n.t("category.errors.not_found"))end- if category &&- topic_tags = (params[:tags] || topic.tags.pluck(:name)).reject { |c| c.empty? }- if topic_tags.present?+ if category+ topic_tag_names = resolve_tag_names(topic)++ if topic_tag_names.present?allowed_tags =DiscourseTagging.filter_allowed_tags(guardian, category: category).map(&:name)- invalid_tags = topic_tags - allowed_tags+ invalid_tags = topic_tag_names - allowed_tags# Do not raise an error on a topic's hidden tags when not modifying tags- if params[:tags].blank?+ if !params.has_key?(:tags)invalid_tags.each do |tag_name|if DiscourseTagging.hidden_tag_names.include?(tag_name)invalid_tags.delete(tag_name)@@ -476,6 +477,9 @@ class TopicsController < ApplicationControllerchanges.delete(:tags)endend++ # resolve to name strings before passing to PostRevisor+ changes[:tags] = resolve_tag_names(topic) if changes.has_key?(:tags)elsif topic.tags.empty?changes.delete(:tags)end@@ -1310,6 +1314,30 @@ class TopicsController < ApplicationControllerprivate+ def resolve_tag_names(topic)+ @resolved_tag_names ||=+ if params[:tags].present?+ incoming = params[:tags]+ if incoming.first.is_a?(String)+ Discourse.deprecate(+ "Passing tag names as strings to the tags param is deprecated, use tag objects ({id, name}) instead",+ since: "2026.01",+ drop_from: "2026.07",+ )+ incoming.reject(&:empty?)+ else+ ids = incoming.filter_map { |t| t[:id]&.to_i }+ names = incoming.filter_map { |t| t[:id].blank? && t[:name].presence }+ names += Tag.visible(guardian).where(id: ids).pluck(:name) if ids.present?+ names+ end+ elsif params.has_key?(:tags)+ []+ else+ topic.tags.pluck(:name)+ end+ end+def allow_embed_modereturn if params[:embed_mode].blank?return unless SiteSetting.embed_full_appdiff --git a/frontend/discourse/app/adapters/post.js b/frontend/discourse/app/adapters/post.jsindex 64fe85565dc..0ba377304a0 100644--- a/frontend/discourse/app/adapters/post.js+++ b/frontend/discourse/app/adapters/post.js@@ -12,10 +12,12 @@ export default class PostAdapter extends RestAdapter {createRecord(store, type, args) {const typeField = underscore(type);args.nested_post = true;- return ajax(this.pathFor(store, type), { type: "POST", data: args }).then(- function (json) {- return new Result(json[typeField], json);- }- );+ return ajax(this.pathFor(store, type), {+ type: "POST",+ data: JSON.stringify(args),+ contentType: "application/json",+ }).then(function (json) {+ return new Result(json[typeField], json);+ });}}diff --git a/frontend/discourse/app/lib/serialize-tags.js b/frontend/discourse/app/lib/serialize-tags.jsnew file mode 100644index 00000000000..4c865fa6f1b--- /dev/null+++ b/frontend/discourse/app/lib/serialize-tags.js@@ -0,0 +1,12 @@+export function serializeTags(tags) {+ return tags.map((t) => {+ if (typeof t === "string") {+ return { name: t };+ }+ const numId = Number(t.id);+ if (Number.isInteger(numId) && numId > 0) {+ return { id: numId, name: t.name };+ }+ return { name: t.name };+ });+}diff --git a/frontend/discourse/app/models/composer.js b/frontend/discourse/app/models/composer.jsindex 965f33cc384..d67252d1f74 100644--- a/frontend/discourse/app/models/composer.js+++ b/frontend/discourse/app/models/composer.js@@ -13,6 +13,7 @@ import { extractError, throwAjaxError } from "discourse/lib/ajax-error";import { tinyAvatar } from "discourse/lib/avatar-utils";import deprecated from "discourse/lib/deprecated";import { QUOTE_REGEXP } from "discourse/lib/quote";+import { serializeTags } from "discourse/lib/serialize-tags";import { prioritizeNameFallback } from "discourse/lib/settings";import { applyValueTransformer } from "discourse/lib/transformer";import { emailValid, escapeExpression } from "discourse/lib/utilities";@@ -1147,10 +1148,7 @@ export default class Composer extends RestModel {let val = this.get(serializer[f]);if (typeof val !== "undefined") {if (f === "tags" && Array.isArray(val)) {- // extract tag names from objects for backend compatibility- if (val.some((t) => typeof t === "object" && t !== null)) {- val = val.map((t) => (typeof t === "object" ? t.name : t));- }+ val = serializeTags(val);}set(dest, f, val);}diff --git a/frontend/discourse/app/models/topic.js b/frontend/discourse/app/models/topic.jsindex bb83e43ea09..94444979e9e 100644--- a/frontend/discourse/app/models/topic.js+++ b/frontend/discourse/app/models/topic.js@@ -16,6 +16,7 @@ import getURL from "discourse/lib/get-url";import { applyModelTransformations } from "discourse/lib/model-transformers";import { deepMerge } from "discourse/lib/object";import PreloadStore from "discourse/lib/preload-store";+import { serializeTags } from "discourse/lib/serialize-tags";import { emojiUnescape } from "discourse/lib/text";import { fancyTitle } from "discourse/lib/topic-fancy-title";import {@@ -108,9 +109,8 @@ export default class Topic extends RestModel {const data = { ...props };- // SHOULD NOT normalize tags to names - backend expects string arrayif (Array.isArray(data.tags)) {- data.tags = data.tags.map((t) => (typeof t === "string" ? t : t.name));+ data.tags = serializeTags(data.tags);}if (opts.fastEdit) {diff --git a/frontend/discourse/tests/helpers/create-pretender.js b/frontend/discourse/tests/helpers/create-pretender.jsindex 32e236b04d2..76e0f2adf6c 100644--- a/frontend/discourse/tests/helpers/create-pretender.js+++ b/frontend/discourse/tests/helpers/create-pretender.js@@ -5,27 +5,33 @@ import { cloneJSON } from "discourse/lib/object";import User from "discourse/models/user";export function parsePostData(query) {- const result = {};- if (query) {- query.split("&").forEach(function (part) {- const item = part.split("=");- const firstSeg = decodeURIComponent(item[0]);- const m = /^([^\[]+)\[(.+)\]/.exec(firstSeg);- const val = decodeURIComponent(item[1]).replace(/\+/g, " ");- const isArray = firstSeg.endsWith("[]");-- if (m) {- let key = m[1];- result[key] = result[key] || {};- result[key][m[2].replace("][", ".")] = val;- } else if (isArray) {- result[firstSeg] ||= [];- result[firstSeg].push(val);- } else {- result[firstSeg] = val;- }- });+ if (!query) {+ return {};+ }++ if (query.startsWith("{") || query.startsWith("[")) {+ return JSON.parse(query);}++ const result = {};+ query.split("&").forEach(function (part) {+ const item = part.split("=");+ const firstSeg = decodeURIComponent(item[0]);+ const m = /^([^\[]+)\[(.+)\]/.exec(firstSeg);+ const val = decodeURIComponent(item[1]).replace(/\+/g, " ");+ const isArray = firstSeg.endsWith("[]");++ if (m) {+ let key = m[1];+ result[key] = result[key] || {};+ result[key][m[2].replace("][", ".")] = val;+ } else if (isArray) {+ result[firstSeg] ||= [];+ result[firstSeg].push(val);+ } else {+ result[firstSeg] = val;+ }+ });return result;}diff --git a/frontend/discourse/tests/unit/models/composer-test.js b/frontend/discourse/tests/unit/models/composer-test.jsindex da6634c442f..3f0cb2a9d6a 100644--- a/frontend/discourse/tests/unit/models/composer-test.js+++ b/frontend/discourse/tests/unit/models/composer-test.js@@ -512,7 +512,7 @@ module("Unit | Model | composer", function (hooks) {assert.strictEqual(composer.composerVersion, 1);});- test("serialize normalizes tags to names and keeps original_tags as objects", function (assert) {+ test("serialize normalizes tags to {id, name} objects", function (assert) {const composer = createComposer.call(this, {tags: [{ id: 1, name: "bug", slug: "bug" },@@ -531,8 +531,11 @@ module("Unit | Model | composer", function (hooks) {assert.deepEqual(serialized.tags,- ["bug", "feature"],- "tags are normalized to string names"+ [+ { id: 1, name: "bug" },+ { id: 2, name: "feature" },+ ],+ "tags are sent as objects with IDs for backend to resolve original names");assert.deepEqual(serialized.original_tags,diff --git a/lib/post_revisor.rb b/lib/post_revisor.rbindex 0e197d171a1..74d898b075f 100644--- a/lib/post_revisor.rb+++ b/lib/post_revisor.rb@@ -135,7 +135,22 @@ class PostRevisortc.record_change("category_id", current_category.id, nil)tc.topic.category_id = nilelsif new_category.nil? || tc.guardian.can_move_topic_to_category?(new_category_id)- tags = fields[:tags] || tc.topic.tags.map(&:name)+ tags =+ if fields[:tags].present?+ input = fields[:tags]+ if input.first.is_a?(String)+ input+ else+ ids = input.filter_map { |t| t[:id]&.to_i }+ names = input.filter_map { |t| t[:id].blank? && t[:name].presence }+ names += Tag.visible(tc.guardian).where(id: ids).pluck(:name) if ids.present?+ names+ end+ elsif fields.has_key?(:tags)+ []+ else+ tc.topic.tags.map(&:name)+ endif new_category &&!DiscourseTagging.validate_category_tags(tc.guardian, tc.topic, new_category, tags)tc.check_result(false)diff --git a/plugins/discourse-post-voting/test/javascripts/acceptance/composer-test.js b/plugins/discourse-post-voting/test/javascripts/acceptance/composer-test.jsindex d356efd6af2..f2c01aafc2c 100644--- a/plugins/discourse-post-voting/test/javascripts/acceptance/composer-test.js+++ b/plugins/discourse-post-voting/test/javascripts/acceptance/composer-test.js@@ -18,10 +18,10 @@ acceptance("Discourse Post Voting - composer", function (needs) {needs.pretender((server, helper) => {server.post("/posts", (request) => {+ const data = parsePostData(request.requestBody);if (- parsePostData(request.requestBody).create_as_post_voting === "true" ||- parsePostData(request.requestBody).only_post_voting_in_this_category ===- "true"+ String(data.create_as_post_voting) === "true" ||+ String(data.only_post_voting_in_this_category) === "true") {createAsPostVotingSetInRequest = true;}diff --git a/spec/lib/post_revisor_spec.rb b/spec/lib/post_revisor_spec.rbindex 4918e0bc7a1..06d4a623588 100644--- a/spec/lib/post_revisor_spec.rb+++ b/spec/lib/post_revisor_spec.rb@@ -119,6 +119,37 @@ describe PostRevisor doexpect(post.reload.topic.category_id).to eq(new_category.id)end+ it "allows category change with localized tags" do+ SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]+ SiteSetting.tag_topic_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]++ tag = Fabricate(:tag)+ tag_group = Fabricate(:tag_group, tags: [tag])+ old_category = Fabricate(:category)+ new_category = Fabricate(:category, tag_groups: [tag_group])++ post = create_post(category: old_category)++ post.revise(post.user, category_id: new_category.id, tags: [{ id: tag.id, name: tag.name }])+ expect(post.reload.topic.category_id).to eq(new_category.id)+ end++ it "allows category change when clearing all tags with an empty array" do+ SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]+ SiteSetting.tag_topic_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]++ tag = Fabricate(:tag)+ old_category = Fabricate(:category)+ new_category = Fabricate(:category)++ post = create_post(category: old_category, tags: [tag.name])+ expect(post.topic.tags).to contain_exactly(tag)++ post.revise(post.user, category_id: new_category.id, tags: [])+ expect(post.reload.topic.category_id).to eq(new_category.id)+ expect(post.topic.tags).to be_empty+ end+it "returns an error if the topic does not have minimum amount of tags that the new category requires" doSiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]SiteSetting.tag_topic_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]diff --git a/spec/requests/posts_controller_spec.rb b/spec/requests/posts_controller_spec.rbindex 942bdbb7897..9cffbb32e16 100644--- a/spec/requests/posts_controller_spec.rb+++ b/spec/requests/posts_controller_spec.rb@@ -1714,6 +1714,45 @@ RSpec.describe PostsController doexpect(Post.last.topic.tags).to contain_exactly(tag)end+ context "with content localization enabled" do+ fab!(:japanese_user) { Fabricate(:user, locale: "ja", refresh_auto_groups: true) }+ fab!(:localized_tag) { Fabricate(:tag, name: "strategy", locale: "en") }+ fab!(:tag_localization) do+ Fabricate(:tag_localization, tag: localized_tag, locale: "ja", name: "戦略")+ end++ before do+ SiteSetting.tagging_enabled = true+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|ja"+ sign_in(japanese_user)+ end++ it "creates a topic with localized tags" do+ post "/posts.json",+ params: {+ raw: "this is the test content",+ title: "this is the test title for the topic",+ tags: [{ id: localized_tag.id, name: "戦略" }],+ }++ expect(response.status).to eq(200)+ expect(Post.last.topic.tags).to contain_exactly(localized_tag)+ end++ it "creates a topic with tags sent as strings" do+ post "/posts.json",+ params: {+ raw: "this is the test content",+ title: "this is the test title for the topic",+ tags: ["strategy"],+ }++ expect(response.status).to eq(200)+ expect(Post.last.topic.tags).to contain_exactly(localized_tag)+ end+ end+it "creates the topic and post with the right attributes" dopost "/posts.json",params: {diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rbindex 66072d87ddb..b51724d6046 100644--- a/spec/requests/topics_controller_spec.rb+++ b/spec/requests/topics_controller_spec.rb@@ -2620,6 +2620,20 @@ RSpec.describe TopicsController doexpect(result["errors"][0]).not_to include(tag3.name)end+ it "does not resolve hidden tags sent by ID" do+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [tag3.name])+ restricted_category.allowed_tags = [tag2.name]++ put "/t/#{topic.slug}/#{topic.id}.json",+ params: {+ tags: [{ id: tag2.id, name: tag2.name }, { id: tag3.id, name: "anything" }],+ category_id: restricted_category.id,+ }++ expect(response.status).to eq(200)+ expect(topic.reload.tags.map(&:name)).not_to include(tag3.name)+ end+it "will clean tag params" dorestricted_category.allowed_tags = [tag2.name]@@ -2631,6 +2645,53 @@ RSpec.describe TopicsController doexpect(response.status).to eq(200)end++ context "with content localization enabled" do+ before do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|ja"+ tag1.update!(locale: "en")+ Fabricate(:tag_localization, tag: tag1, locale: "ja", name: "タグ1")+ user.update!(locale: "ja")+ end++ it "can change category with localized tags" do+ restricted_category.allowed_tags = [tag1.name]++ put "/t/#{topic.slug}/#{topic.id}.json",+ params: {+ tags: [{ id: tag1.id, name: "タグ1" }],+ category_id: restricted_category.id,+ }++ expect(response.status).to eq(200)+ end++ it "can change category when tags are sent as strings" do+ restricted_category.allowed_tags = [tag1.name]++ put "/t/#{topic.slug}/#{topic.id}.json",+ params: {+ tags: [tag1.name],+ category_id: restricted_category.id,+ }++ expect(response.status).to eq(200)+ end++ it "can edit tags with localized tag names" do+ tag2 = Fabricate(:tag, name: "planning", locale: "en")+ Fabricate(:tag_localization, tag: tag2, locale: "ja", name: "計画")++ put "/t/#{topic.slug}/#{topic.id}.json",+ params: {+ tags: [{ id: tag1.id, name: "タグ1" }, { id: tag2.id, name: "計画" }],+ }++ expect(response.status).to eq(200)+ expect(topic.reload.tags).to contain_exactly(tag1, tag2)+ end+ endendcontext "when allow_uncategorized_topics is false" dodiff --git a/spec/system/content_localization_spec.rb b/spec/system/content_localization_spec.rbindex 5b8a0978bc8..7ecf4559d77 100644--- a/spec/system/content_localization_spec.rb+++ b/spec/system/content_localization_spec.rb@@ -550,6 +550,66 @@ describe "Content Localization" domini_tag_chooser.search("戦")expect(mini_tag_chooser).to have_option_name("戦略")end++ it "can create a topic with a localized tag" do+ SiteSetting.tag_topic_allowed_groups = Group::AUTO_GROUPS[:everyone]+ SiteSetting.create_topic_allowed_groups = Group::AUTO_GROUPS[:everyone]+ mini_tag_chooser = PageObjects::Components::SelectKit.new(".mini-tag-chooser")++ sign_in(admin)+ admin.update!(locale: "ja")+ visit("/new-topic")+ expect(composer).to be_opened++ composer.fill_title("テストトピック with localized tags")+ composer.fill_content("このトピックにはローカライズされたタグが含まれています")++ mini_tag_chooser.expand+ mini_tag_chooser.search("戦")+ mini_tag_chooser.select_row_by_name("戦略")++ composer.create++ topic = Topic.where("title LIKE ?", "%テストトピック%").last+ expect(topic).to be_present+ expect(topic.tags).to include(tag)+ end++ it "can change category and tags on an existing topic with localized tags" do+ SiteSetting.tag_topic_allowed_groups = Group::AUTO_GROUPS[:everyone]+ tag2 = Fabricate(:tag, name: "planning", locale: "en")+ Fabricate(:tag_localization, tag: tag2, locale: "ja", name: "計画")+ new_category = Fabricate(:category)+ topic_page = PageObjects::Pages::Topic.new+ edit_dialog = PageObjects::Components::Dialog.new+ mini_tag_chooser = PageObjects::Components::SelectKit.new(".mini-tag-chooser")++ # Topic already has the "strategy" tag via topic_tag fab+ sign_in(admin)+ admin.update!(locale: "ja")+ visit(topic.url)++ topic_page.click_topic_edit_title+ edit_dialog.click_yes # edit original++ # Change category+ category_chooser =+ PageObjects::Components::SelectKit.new(".edit-category__wrapper .category-chooser")+ category_chooser.expand+ category_chooser.select_row_by_value(new_category.id)++ # Add another localized tag+ mini_tag_chooser.expand+ mini_tag_chooser.search("plan")+ mini_tag_chooser.select_row_by_name("計画")++ topic_page.click_topic_title_submit_edit++ expect(topic_page).to have_no_css("#topic-title .submit-edit")+ topic.reload+ expect(topic.category).to eq(new_category)+ expect(topic.tags).to include(tag, tag2)+ endendend