A platform for community discussion. Free, open, simple.
DEV: Setup backend for dedicated tag settings page (#37804)
Natalie Tay7691be669a6a
diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rbindex e98ec7e69f0..3c499f8a7e0 100644--- a/app/controllers/tags_controller.rb+++ b/app/controllers/tags_controller.rb@@ -28,6 +28,8 @@ class TagsController < ::ApplicationControllerpersonal_messagesinfolist+ settings+ update_settings]before_action :fetch_tag,@@ -233,6 +235,43 @@ class TagsController < ::ApplicationControllerrender_serialized(@tag, DetailedTagSerializer, rest_serializer: true, root: :tag_info)end+ def settings+ includes = %i[tag_groups synonyms]+ includes << :localizations if SiteSetting.content_localization_enabled+ tag = Tag.includes(includes).find_by(id: params[:tag_id])+ raise Discourse::NotFound unless tag && guardian.can_edit_tag?(tag)++ render_serialized(tag, TagSettingsSerializer, rest_serializer: true, root: :tag_settings)+ end++ def update_settings+ tag = Tag.find_by(id: params[:tag_id])+ raise Discourse::NotFound unless tag && guardian.can_edit_tag?(tag)++ updater_params =+ params.require(:tag_settings).permit(+ :name,+ :slug,+ :description,+ removed_synonym_ids: [],+ new_synonyms: [:id],+ localizations: %i[locale name description],+ )++ updater = TagSettingsUpdater.new(tag, current_user)++ if updater.update(updater_params)+ render_serialized(+ updater.updated_tag,+ TagSettingsSerializer,+ rest_serializer: true,+ root: :tag_settings,+ )+ else+ render_json_error updater.errors+ end+ end+def updateif params[:tag][:id]warning =diff --git a/app/models/tag.rb b/app/models/tag.rbindex 9621d54a603..365bf128743 100644--- a/app/models/tag.rb+++ b/app/models/tag.rb@@ -300,7 +300,7 @@ class Tag < ActiveRecord::Baseself.slug ||= ""return if name.blank?- if self.slug.blank? || will_save_change_to_name?+ if self.slug.blank? || (will_save_change_to_name? && !will_save_change_to_slug?)self.slug = Slug.for(name, "")self.slug = "" if self.slug.blank? || duplicate_slug?enddiff --git a/app/serializers/tag_settings_serializer.rb b/app/serializers/tag_settings_serializer.rbnew file mode 100644index 00000000000..fe4c6aecf0e--- /dev/null+++ b/app/serializers/tag_settings_serializer.rb@@ -0,0 +1,65 @@+# frozen_string_literal: true++class TagSettingsSerializer < ApplicationSerializer+ attributes :id,+ :name,+ :slug,+ :description,+ :synonyms,+ :tag_group_names,+ :tag_groups,+ :category_restricted,+ :can_edit,+ :can_admin++ has_many :categories, serializer: BasicCategorySerializer+ has_many :localizations, serializer: TagLocalizationSerializer, embed: :objects++ def name+ object.name+ end++ def description+ object.description+ end++ def synonyms+ object.synonyms.map { |t| { id: t.id, name: t.name } }+ end++ def categories+ object.all_categories(scope)+ end++ def category_restricted+ object.all_category_ids.present?+ end++ def tag_group_names+ object.tag_groups.map(&:name)+ end++ def tag_groups+ object.tag_groups.map { |tg| { id: tg.id, name: tg.name } }+ end++ def can_edit+ scope.can_edit_tag?(object)+ end++ def can_admin+ scope.can_admin_tags?+ end++ def include_tag_group_names?+ scope.is_admin? || SiteSetting.tags_listed_by_group == true+ end++ def include_tag_groups?+ scope.is_admin? || SiteSetting.tags_listed_by_group == true+ end++ def include_localizations?+ SiteSetting.content_localization_enabled+ end+enddiff --git a/app/services/tag_settings_updater.rb b/app/services/tag_settings_updater.rbnew file mode 100644index 00000000000..d38392c42ec--- /dev/null+++ b/app/services/tag_settings_updater.rb@@ -0,0 +1,95 @@+# frozen_string_literal: true++class TagSettingsUpdater+ attr_reader :tag, :errors++ def initialize(tag, actor)+ @tag = tag+ @actor = actor+ @errors = []+ end++ def self.update(tag, actor, params)+ new(tag, actor).update(params)+ end++ def update(params)+ old_tag_name = @tag.name++ Tag.transaction do+ update_basic_attributes(params)++ unless @tag.save+ @errors = @tag.errors.full_messages+ raise ActiveRecord::Rollback+ end++ log_rename(old_tag_name) if @tag.name != old_tag_name+ remove_synonyms(params[:removed_synonym_ids])+ add_synonyms(params[:new_synonyms])+ update_localizations(params[:localizations])+ end++ @errors.empty?+ end++ def updated_tag+ Tag.includes(:synonyms, :localizations, :tag_groups).find(@tag.id)+ end++ private++ def update_basic_attributes(params)+ @tag.name = DiscourseTagging.clean_tag(params[:name]) if params[:name].present?+ @tag.slug = params[:slug] if params[:slug].present?+ @tag.description = params[:description] if params.key?(:description)+ end++ def log_rename(old_name)+ StaffActionLogger.new(@actor).log_custom(+ "renamed_tag",+ previous_value: old_name,+ new_value: @tag.name,+ )+ end++ def remove_synonyms(removed_ids)+ return if removed_ids.blank?++ Tag.where(id: removed_ids, target_tag_id: @tag.id).update_all(target_tag_id: nil)+ end++ def add_synonyms(new_synonyms)+ return if new_synonyms.blank?++ synonym_tag_ids = new_synonyms.filter_map { |t| t[:id]&.to_i }+ DiscourseTagging.add_or_create_synonyms(@tag, synonym_tag_ids:) if synonym_tag_ids.present?+ end++ def update_localizations(localizations)+ return if localizations.blank?++ submitted_locales = []++ localizations.each do |loc|+ locale = loc[:locale]+ next if locale.blank?++ submitted_locales << locale++ existing = TagLocalization.find_by(tag_id: @tag.id, locale: locale)+ if existing+ existing.update!(name: loc[:name], description: loc[:description])+ else+ TagLocalization.create!(+ tag_id: @tag.id,+ locale: locale,+ name: loc[:name],+ description: loc[:description],+ )+ end+ end++ TagLocalization.where(tag_id: @tag.id).where.not(locale: submitted_locales).delete_all+ end+enddiff --git a/config/routes.rb b/config/routes.rbindex a0db18d2648..86168050ab3 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -1673,6 +1673,8 @@ Discourse::Application.routes.draw doget "/info" => "tags#info", :as => "tag_info"get "/notifications" => "tags#notifications", :as => "tag_notifications"put "/notifications" => "tags#update_notifications"+ get "/settings" => "tags#settings"+ put "/settings" => "tags#update_settings"put "/" => "tags#update", :as => "tag_update"delete "/" => "tags#destroy", :as => "tag_destroy"post "/synonyms" => "tags#create_synonyms", :as => "tag_synonyms"@@ -1685,6 +1687,8 @@ Discourse::Application.routes.draw doscope "/tag/:tag_slug/:tag_id", constraints: { tag_id: /\d+/, format: :json } doget "/" => "tags#show", :as => "tag_show_with_slug"+ get "/edit" => "tags#show"+ get "/edit/:tab" => "tags#show"Discourse.filters.each do |filter|get "/l/#{filter}" => "tags#show_#{filter}", :as => "tag_show_#{filter}_with_slug"diff --git a/lib/discourse_tagging.rb b/lib/discourse_tagging.rbindex fa76da43f8f..21a24d40fb5 100644--- a/lib/discourse_tagging.rb+++ b/lib/discourse_tagging.rb@@ -912,7 +912,13 @@ module DiscourseTaggingnow = Time.currentrows =names_to_create.map do |n|- { name: n, target_tag_id: target_tag.id, created_at: now, updated_at: now }+ {+ name: n,+ slug: Slug.for(n, ""),+ target_tag_id: target_tag.id,+ created_at: now,+ updated_at: now,+ }endvalid_ids += Tag.insert_all(rows, returning: :id).pluck("id")enddiff --git a/spec/lib/discourse_tagging_spec.rb b/spec/lib/discourse_tagging_spec.rbindex 4f4c5f2af0f..3de908d0a8b 100644--- a/spec/lib/discourse_tagging_spec.rb+++ b/spec/lib/discourse_tagging_spec.rb@@ -2049,6 +2049,12 @@ RSpec.describe DiscourseTagging doexpect(s.target_tag).to eq(tag1)end+ it "generates slug for new tags" do+ DiscourseTagging.add_or_create_synonyms(tag1, new_synonym_names: ["synonym1"])+ s = Tag.where_name("synonym1").first+ expect(s.slug).to eq("synonym1")+ end+it "can add existing and new tags" doexpect {expect(diff --git a/spec/requests/tags_controller_spec.rb b/spec/requests/tags_controller_spec.rbindex bfddb390869..e6d8a60aa94 100644--- a/spec/requests/tags_controller_spec.rb+++ b/spec/requests/tags_controller_spec.rb@@ -686,6 +686,236 @@ RSpec.describe TagsController doendend+ describe "#settings" do+ fab!(:tag) { Fabricate(:tag, name: "test-tag", description: "test description") }+ fab!(:synonym) { Fabricate(:tag, name: "test-synonym", target_tag: tag) }++ it "returns 404 if tag not found" do+ sign_in(admin)+ get "/tag/9999999/settings.json"+ expect(response.status).to eq(404)+ end++ it "returns 404 if user cannot edit tags" do+ sign_in(user)+ get "/tag/#{tag.id}/settings.json"+ expect(response.status).to eq(404)+ end++ it "returns tag settings for admin" do+ sign_in(admin)+ get "/tag/#{tag.id}/settings.json"+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["id"]).to eq(tag.id)+ expect(settings["name"]).to eq(tag.name)+ expect(settings["slug"]).to eq(tag.slug)+ expect(settings["description"]).to eq(tag.description)+ expect(settings["can_edit"]).to eq(true)+ expect(settings["can_admin"]).to eq(true)+ end++ it "includes synonyms in the response" do+ sign_in(admin)+ get "/tag/#{tag.id}/settings.json"+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["synonyms"].map { |s| s["name"] }).to contain_exactly(synonym.name)+ end++ it "includes category restrictions when present" do+ category.update!(tags: [tag])+ sign_in(admin)+ get "/tag/#{tag.id}/settings.json"+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["category_restricted"]).to eq(true)+ # categories are at top level, not nested inside tag_settings+ expect(response.parsed_body["categories"].map { |c| c["id"] }).to contain_exactly(category.id)+ end++ it "includes tag group names for admin" do+ SiteSetting.tags_listed_by_group = true+ tag_group = Fabricate(:tag_group, tags: [tag])+ sign_in(admin)+ get "/tag/#{tag.id}/settings.json"+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["tag_group_names"]).to contain_exactly(tag_group.name)+ end++ it "includes tag groups with id and name for admin" do+ SiteSetting.tags_listed_by_group = true+ tag_group = Fabricate(:tag_group, tags: [tag])+ sign_in(admin)+ get "/tag/#{tag.id}/settings.json"+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["tag_groups"]).to be_present+ expect(settings["tag_groups"].length).to eq(1)+ expect(settings["tag_groups"][0]["id"]).to eq(tag_group.id)+ expect(settings["tag_groups"][0]["name"]).to eq(tag_group.name)+ end++ context "with content localization enabled" do+ before { SiteSetting.content_localization_enabled = true }++ it "includes localizations in the response" do+ Fabricate(:tag_localization, tag: tag, locale: "zh_CN", name: "测试标签")+ sign_in(admin)+ get "/tag/#{tag.id}/settings.json"+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["localizations"]).to be_present+ expect(settings["localizations"].first["locale"]).to eq("zh_CN")+ expect(settings["localizations"].first["name"]).to eq("测试标签")+ end+ end++ context "when user in edit_tags_allowed_groups" do+ before { SiteSetting.edit_tags_allowed_groups = "1|2|13" }++ it "allows access for users in allowed groups" do+ sign_in(regular_user)+ get "/tag/#{tag.id}/settings.json"+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["can_edit"]).to eq(true)+ expect(settings["can_admin"]).to eq(false)+ end+ end+ end++ describe "#update_settings" do+ fab!(:tag) { Fabricate(:tag, name: "original-name", description: "original description") }++ it "returns 404 if tag not found" do+ sign_in(admin)+ put "/tag/9999999/settings.json", params: { tag_settings: { name: "new-name" } }+ expect(response.status).to eq(404)+ end++ it "returns 404 if user cannot edit tags" do+ sign_in(user)+ put "/tag/#{tag.id}/settings.json", params: { tag_settings: { name: "new-name" } }+ expect(response.status).to eq(404)+ end++ context "when signed in as admin" do+ before { sign_in(admin) }++ it "updates the tag name" do+ put "/tag/#{tag.id}/settings.json", params: { tag_settings: { name: "updated-name" } }+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["name"]).to eq("updated-name")+ expect(tag.reload.name).to eq("updated-name")+ end++ it "updates the tag slug" do+ put "/tag/#{tag.id}/settings.json", params: { tag_settings: { slug: "custom-slug" } }+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["slug"]).to eq("custom-slug")+ expect(tag.reload.slug).to eq("custom-slug")+ end++ it "updates the tag description" do+ put "/tag/#{tag.id}/settings.json",+ params: {+ tag_settings: {+ description: "new description",+ },+ }+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["description"]).to eq("new description")+ expect(tag.reload.description).to eq("new description")+ end++ it "can clear the description" do+ put "/tag/#{tag.id}/settings.json", params: { tag_settings: { description: "" } }+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["description"]).to be_blank+ expect(tag.reload.description).to be_blank+ end++ it "logs staff action when renaming a tag" do+ expect {+ put "/tag/#{tag.id}/settings.json", params: { tag_settings: { name: "renamed-tag" } }+ }.to change { UserHistory.where(action: UserHistory.actions[:custom_staff]).count }.by(1)++ log = UserHistory.last+ expect(log.custom_type).to eq("renamed_tag")+ expect(log.previous_value).to eq("original-name")+ expect(log.new_value).to eq("renamed-tag")+ end++ it "does not log staff action when not changing name" do+ expect {+ put "/tag/#{tag.id}/settings.json",+ params: {+ tag_settings: {+ description: "just updating description",+ },+ }+ }.not_to change { UserHistory.where(action: UserHistory.actions[:custom_staff]).count }+ end++ it "cleans the tag name" do+ put "/tag/#{tag.id}/settings.json", params: { tag_settings: { name: "New Tag Name" } }+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["name"]).to eq("new-tag-name")+ end++ it "ignores empty name param" do+ original_name = tag.name+ put "/tag/#{tag.id}/settings.json", params: { tag_settings: { name: "" } }+ expect(response.status).to eq(200)+ expect(tag.reload.name).to eq(original_name)+ end++ it "returns errors for duplicate tag name" do+ other_tag = Fabricate(:tag, name: "existing-tag")+ put "/tag/#{tag.id}/settings.json", params: { tag_settings: { name: other_tag.name } }+ expect(response.status).to eq(422)+ end++ it "supports unicode tag names" do+ put "/tag/#{tag.id}/settings.json", params: { tag_settings: { name: "日本語タグ" } }+ expect(response.status).to eq(200)++ settings = response.parsed_body["tag_settings"]+ expect(settings["name"]).to eq("日本語タグ")+ end+ end++ context "when user in edit_tags_allowed_groups" do+ before { SiteSetting.edit_tags_allowed_groups = "1|2|13" }++ it "allows updating for users in allowed groups" do+ sign_in(regular_user)+ put "/tag/#{tag.id}/settings.json", params: { tag_settings: { name: "user-updated" } }+ expect(response.status).to eq(200)+ expect(tag.reload.name).to eq("user-updated")+ end+ end+ end+describe "#update" dofab!(:tag)diff --git a/spec/services/tag_settings_updater_spec.rb b/spec/services/tag_settings_updater_spec.rbnew file mode 100644index 00000000000..462cceef8a2--- /dev/null+++ b/spec/services/tag_settings_updater_spec.rb@@ -0,0 +1,172 @@+# frozen_string_literal: true++describe TagSettingsUpdater do+ fab!(:admin)+ fab!(:tag)++ describe "#update" do+ it "updates basic tag attributes" do+ result = TagSettingsUpdater.update(tag, admin, { name: "new-name", description: "new desc" })++ expect(result).to eq(true)+ tag.reload+ expect(tag.name).to eq("new-name")+ expect(tag.description).to eq("new desc")+ end++ it "updates slug when provided" do+ result = TagSettingsUpdater.update(tag, admin, { slug: "custom-slug" })++ expect(result).to eq(true)+ expect(tag.reload.slug).to eq("custom-slug")+ end++ it "cleans tag name using DiscourseTagging" do+ result = TagSettingsUpdater.update(tag, admin, { name: " New Name " })++ expect(result).to eq(true)+ expect(tag.reload.name).to eq("new-name")+ end++ it "returns false and populates errors when save fails" do+ existing_tag = Fabricate(:tag)+ updater = TagSettingsUpdater.new(tag, admin)+ result = updater.update({ name: existing_tag.name })++ expect(result).to eq(false)+ expect(updater.errors).to be_present+ end++ it "logs staff action when name changes" do+ old_name = tag.name++ expect { TagSettingsUpdater.update(tag, admin, { name: "renamed-tag" }) }.to change {+ UserHistory.where(+ acting_user_id: admin.id,+ custom_type: "renamed_tag",+ previous_value: old_name,+ new_value: "renamed-tag",+ ).count+ }.by(1)+ end++ it "does not log staff action when name stays the same" do+ expect { TagSettingsUpdater.update(tag, admin, { description: "new desc" }) }.not_to change {+ UserHistory.where(acting_user_id: admin.id, custom_type: "renamed_tag").count+ }+ end++ context "with synonyms" do+ fab!(:synonym1) { Fabricate(:tag, target_tag: tag) }+ fab!(:synonym2) { Fabricate(:tag, target_tag: tag) }+ fab!(:other_tag, :tag)++ it "removes synonyms when removed_synonym_ids provided" do+ TagSettingsUpdater.update(tag, admin, { removed_synonym_ids: [synonym1.id] })++ expect(synonym1.reload.target_tag_id).to be_nil+ expect(synonym2.reload.target_tag_id).to eq(tag.id)+ end++ it "adds existing tags as synonyms" do+ TagSettingsUpdater.update(+ tag,+ admin,+ { new_synonyms: [{ id: other_tag.id, name: other_tag.name }] },+ )++ expect(other_tag.reload.target_tag_id).to eq(tag.id)+ end++ it "only removes synonyms that belong to this tag" do+ unrelated_synonym = Fabricate(:tag, target_tag: other_tag)++ TagSettingsUpdater.update(tag, admin, { removed_synonym_ids: [unrelated_synonym.id] })++ expect(unrelated_synonym.reload.target_tag_id).to eq(other_tag.id)+ end+ end++ context "with transaction rollback" do+ it "rolls back all changes if tag save fails" do+ synonym = Fabricate(:tag, target_tag: tag)+ other_tag = Fabricate(:tag)++ tag.stubs(:save).returns(false)+ tag.errors.add(:name, "is invalid")++ updater = TagSettingsUpdater.new(tag, admin)+ result =+ updater.update(+ {+ name: "new-name",+ removed_synonym_ids: [synonym.id],+ new_synonyms: [{ id: other_tag.id, name: other_tag.name }],+ },+ )++ expect(result).to eq(false)+ expect(synonym.reload.target_tag_id).to eq(tag.id)+ expect(other_tag.reload.target_tag_id).to be_nil+ end+ end++ context "with localizations" do+ it "creates new localizations" do+ TagSettingsUpdater.update(+ tag,+ admin,+ { localizations: [{ locale: "de", name: "German Name", description: "German Desc" }] },+ )++ loc = TagLocalization.find_by(tag_id: tag.id, locale: "de")+ expect(loc).to be_present+ expect(loc.name).to eq("German Name")+ expect(loc.description).to eq("German Desc")+ end++ it "updates existing localizations" do+ TagLocalization.create!(tag_id: tag.id, locale: "fr", name: "Old", description: "Old Desc")++ TagSettingsUpdater.update(+ tag,+ admin,+ { localizations: [{ locale: "fr", name: "New", description: "New Desc" }] },+ )++ loc = TagLocalization.find_by(tag_id: tag.id, locale: "fr")+ expect(loc.name).to eq("New")+ expect(loc.description).to eq("New Desc")+ end++ it "removes localizations not in the submitted list" do+ TagLocalization.create!(tag_id: tag.id, locale: "es", name: "Spanish", description: "")+ TagLocalization.create!(tag_id: tag.id, locale: "it", name: "Italian", description: "")++ TagSettingsUpdater.update(+ tag,+ admin,+ { localizations: [{ locale: "es", name: "Spanish Updated", description: "" }] },+ )++ expect(TagLocalization.find_by(tag_id: tag.id, locale: "es")).to be_present+ expect(TagLocalization.find_by(tag_id: tag.id, locale: "it")).to be_nil+ end+ end+ end++ describe "#updated_tag" do+ it "returns tag with associations preloaded" do+ synonym = Fabricate(:tag, target_tag: tag)+ updater = TagSettingsUpdater.new(tag, admin)+ updater.update({ name: "updated" })++ updated = updater.updated_tag++ expect(updated.name).to eq("updated")+ expect(updated.association(:synonyms).loaded?).to eq(true)+ expect(updated.association(:localizations).loaded?).to eq(true)+ expect(updated.association(:tag_groups).loaded?).to eq(true)+ end+ end+end