Skip to content

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

FEATURE: Introduce tag localizations with API, without UI yet (#36754)

Natalie Tay5322295b8cac
diff --git a/app/controllers/tag_localizations_controller.rb b/app/controllers/tag_localizations_controller.rb
new file mode 100644
index 00000000000..5569c5b5f99
--- /dev/null
+++ b/app/controllers/tag_localizations_controller.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+class TagLocalizationsController < ApplicationController
+ before_action :ensure_logged_in
+
+ def show
+ tag = Tag.find_by(id: params[:id])
+ raise Discourse::NotFound unless tag
+
+ guardian.ensure_can_localize_tag!(tag)
+
+ tag_localizations = TagLocalization.where(tag_id: tag.id)
+
+ render json: {
+ tag_localizations:
+ ActiveModel::ArraySerializer.new(
+ tag_localizations,
+ each_serializer: TagLocalizationSerializer,
+ root: false,
+ ).as_json,
+ },
+ status: :ok
+ end
+
+ def create_or_update
+ tag_id, locale, name = params.require(%i[tag_id locale name])
+ description = params[:description]
+
+ tag = Tag.find_by(id: tag_id)
+ raise Discourse::NotFound unless tag
+
+ guardian.ensure_can_localize_tag!(tag)
+
+ localization = TagLocalization.find_by(tag_id:, locale:)
+ if localization
+ TagLocalizationUpdater.update(tag:, locale:, name:, description:, user: current_user)
+ render json: success_json, status: :ok
+ else
+ TagLocalizationCreator.create(tag:, locale:, name:, description:, user: current_user)
+ render json: success_json, status: :created
+ end
+ end
+
+ def destroy
+ tag_id, locale = params.require(%i[tag_id locale])
+
+ tag = Tag.find_by(id: tag_id)
+ raise Discourse::NotFound unless tag
+
+ guardian.ensure_can_localize_tag!(tag)
+
+ TagLocalizationDestroyer.destroy(tag:, locale:, acting_user: current_user)
+ head :no_content
+ end
+end
diff --git a/app/serializers/tag_localization_serializer.rb b/app/serializers/tag_localization_serializer.rb
new file mode 100644
index 00000000000..3282586621f
--- /dev/null
+++ b/app/serializers/tag_localization_serializer.rb
@@ -0,0 +1,5 @@
+# frozen_string_literal: true
+
+class TagLocalizationSerializer < ApplicationSerializer
+ attributes :id, :tag_id, :locale, :name, :description
+end
diff --git a/app/serializers/tag_serializer.rb b/app/serializers/tag_serializer.rb
index 81e55156965..1f2b828dda9 100644
--- a/app/serializers/tag_serializer.rb
+++ b/app/serializers/tag_serializer.rb
@@ -3,6 +3,8 @@
class TagSerializer < ApplicationSerializer
attributes :id, :name, :topic_count, :staff, :description
+ has_many :localizations, serializer: TagLocalizationSerializer, embed: :objects
+
def topic_count
object.public_send(Tag.topic_count_column(scope))
end
@@ -10,4 +12,8 @@ class TagSerializer < ApplicationSerializer
def staff
DiscourseTagging.staff_tag_names.include?(name)
end
+
+ def include_localizations?
+ SiteSetting.content_localization_enabled && object.localizations.loaded?
+ end
end
diff --git a/config/routes.rb b/config/routes.rb
index b4c2478e268..41e92912f2f 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1277,6 +1277,10 @@ Discourse::Application.routes.draw do
post "topic_localizations/create_or_update", to: "topic_localizations#create_or_update"
delete "topic_localizations/destroy", to: "topic_localizations#destroy"
+ get "/tag_localizations/:id" => "tag_localizations#show"
+ post "tag_localizations/create_or_update", to: "tag_localizations#create_or_update"
+ delete "tag_localizations/destroy", to: "tag_localizations#destroy"
+
resources :bookmarks, only: %i[create destroy update] do
put "toggle_pin"
end
diff --git a/lib/guardian/localization_guardian.rb b/lib/guardian/localization_guardian.rb
index e95a6a518f5..84387d58d18 100644
--- a/lib/guardian/localization_guardian.rb
+++ b/lib/guardian/localization_guardian.rb
@@ -35,4 +35,13 @@ module LocalizationGuardian
topic.user_id == @user.id
end
+
+ def can_localize_tag?(tag_or_tag_id)
+ return false if !SiteSetting.content_localization_enabled
+ return false if anonymous?
+ return false if [email protected]_any_groups?(SiteSetting.content_localization_allowed_groups_map)
+
+ tag = tag_or_tag_id.is_a?(Tag) ? tag_or_tag_id : Tag.find_by(id: tag_or_tag_id)
+ !hidden_tag_names.include?(tag.name)
+ end
end
diff --git a/lib/tag_localization_creator.rb b/lib/tag_localization_creator.rb
new file mode 100644
index 00000000000..6a663f5e962
--- /dev/null
+++ b/lib/tag_localization_creator.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+class TagLocalizationCreator
+ def self.create(tag:, locale:, name:, description: nil, user:)
+ raise Discourse::NotFound unless tag
+
+ Guardian.new(user).ensure_can_localize_tag!(tag)
+
+ TagLocalization.create!(tag: tag, locale: locale, name: name, description: description)
+ end
+end
diff --git a/lib/tag_localization_destroyer.rb b/lib/tag_localization_destroyer.rb
new file mode 100644
index 00000000000..4a40a34a821
--- /dev/null
+++ b/lib/tag_localization_destroyer.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+class TagLocalizationDestroyer
+ def self.destroy(tag:, locale:, acting_user:)
+ raise Discourse::NotFound unless tag
+
+ Guardian.new(acting_user).ensure_can_localize_tag!(tag)
+
+ localization = TagLocalization.find_by(tag_id: tag.id, locale:)
+ raise Discourse::NotFound unless localization
+
+ localization.destroy!
+ end
+end
diff --git a/lib/tag_localization_updater.rb b/lib/tag_localization_updater.rb
new file mode 100644
index 00000000000..725702b5f57
--- /dev/null
+++ b/lib/tag_localization_updater.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+class TagLocalizationUpdater
+ def self.update(tag:, locale:, name:, description: nil, user:)
+ raise Discourse::NotFound unless tag
+
+ Guardian.new(user).ensure_can_localize_tag!(tag)
+
+ localization = TagLocalization.find_by(tag_id: tag.id, locale: locale)
+ raise Discourse::NotFound unless localization
+
+ return localization if localization.name == name && localization.description == description
+
+ localization.name = name
+ localization.description = description
+ localization.save!
+
+ localization
+ end
+end
diff --git a/plugins/discourse-ai/app/jobs/regular/localize_tags.rb b/plugins/discourse-ai/app/jobs/regular/localize_tags.rb
new file mode 100644
index 00000000000..4d6b7651c6b
--- /dev/null
+++ b/plugins/discourse-ai/app/jobs/regular/localize_tags.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+module Jobs
+ class LocalizeTags < ::Jobs::Base
+ cluster_concurrency 1
+ sidekiq_options retry: false
+
+ def execute(args)
+ return if !DiscourseAi::Translation.enabled?
+
+ unless DiscourseAi::Translation.credits_available_for_tag_localization?
+ Rails.logger.info(
+ "Translation skipped for tags: insufficient credits. Will resume when credits reset.",
+ )
+ return
+ end
+
+ limit = args[:limit]
+ raise Discourse::InvalidParameters.new(:limit) if limit.nil?
+ return if limit <= 0
+
+ short_text_llm_model =
+ find_llm_model_for_persona(SiteSetting.ai_translation_short_text_translator_persona)
+ return if short_text_llm_model.blank?
+
+ tags =
+ DiscourseAi::Translation::TagCandidates.get.where.not(locale: nil).order(:id).limit(limit)
+ return if tags.empty?
+
+ # we remove localizations in locales that match the tag's locale
+ TagLocalization
+ .joins("INNER JOIN tags ON tags.id = tag_localizations.tag_id")
+ .where(tag_id: tags)
+ .where("tag_localizations.locale = tags.locale")
+ .delete_all
+
+ remaining_limit = limit
+ locales = SiteSetting.content_localization_supported_locales.split("|")
+ tags.each do |tag|
+ break if remaining_limit <= 0
+
+ existing_locales = TagLocalization.where(tag_id: tag.id).pluck(:locale)
+ missing_locales = locales - existing_locales - [tag.locale]
+ missing_locales.each do |locale|
+ break if remaining_limit <= 0
+ next if LocaleNormalizer.is_same?(locale, tag.locale)
+
+ begin
+ DiscourseAi::Translation::TagLocalizer.localize(tag, locale, short_text_llm_model:)
+ rescue FinalDestination::SSRFDetector::LookupFailedError
+ # do nothing, there are too many sporadic lookup failures
+ rescue => e
+ DiscourseAi::Translation::VerboseLogger.log(
+ "Failed to translate tag #{tag.id} to #{locale}: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",
+ )
+ ensure
+ remaining_limit -= 1
+ end
+ end
+ end
+ end
+
+ private
+
+ def find_llm_model_for_persona(persona_id)
+ return nil if persona_id.blank?
+
+ persona_klass = AiPersona.find_by_id_from_cache(persona_id)
+ return nil if persona_klass.blank?
+
+ DiscourseAi::Translation::BaseTranslator.preferred_llm_model(persona_klass)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/jobs/scheduled/tag_localization_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/tag_localization_backfill.rb
new file mode 100644
index 00000000000..d5c734f4a14
--- /dev/null
+++ b/plugins/discourse-ai/app/jobs/scheduled/tag_localization_backfill.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module Jobs
+ class TagLocalizationBackfill < ::Jobs::Scheduled
+ every 1.hour
+ cluster_concurrency 1
+
+ def execute(args)
+ return if !DiscourseAi::Translation.backfill_enabled?
+
+ short_text_llm =
+ find_llm_model_for_persona(SiteSetting.ai_translation_short_text_translator_persona)
+
+ if short_text_llm && !LlmCreditAllocation.credits_available?(short_text_llm)
+ Rails.logger.info(
+ "Tag localization backfill skipped: insufficient credits. Will resume when credits reset.",
+ )
+ return
+ end
+
+ limit = SiteSetting.ai_translation_backfill_hourly_rate
+
+ Jobs.enqueue(:localize_tags, limit:)
+ end
+
+ private
+
+ def find_llm_model_for_persona(persona_id)
+ return nil if persona_id.blank?
+
+ persona_klass = AiPersona.find_by_id_from_cache(persona_id)
+ return nil if persona_klass.blank?
+
+ DiscourseAi::Translation::BaseTranslator.preferred_llm_model(persona_klass)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/jobs/scheduled/tags_locale_detection_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/tags_locale_detection_backfill.rb
new file mode 100644
index 00000000000..6b568ea1689
--- /dev/null
+++ b/plugins/discourse-ai/app/jobs/scheduled/tags_locale_detection_backfill.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module Jobs
+ class TagsLocaleDetectionBackfill < ::Jobs::Scheduled
+ every 1.hour
+ sidekiq_options retry: false
+ cluster_concurrency 1
+
+ def execute(args)
+ return if !DiscourseAi::Translation.backfill_enabled?
+
+ llm_model = find_llm_model
+ return if llm_model.blank?
+
+ unless LlmCreditAllocation.credits_available?(llm_model)
+ Rails.logger.info(
+ "Tags locale detection backfill skipped: insufficient credits. Will resume when credits reset.",
+ )
+ return
+ end
+
+ tags =
+ DiscourseAi::Translation::TagCandidates
+ .get
+ .where(locale: nil)
+ .limit(SiteSetting.ai_translation_backfill_hourly_rate)
+ return if tags.empty?
+
+ tags.each do |tag|
+ begin
+ DiscourseAi::Translation::TagLocaleDetector.detect_locale(tag)
+ rescue FinalDestination::SSRFDetector::LookupFailedError
+ rescue => e
+ DiscourseAi::Translation::VerboseLogger.log(
+ "Failed to detect tag #{tag.id}'s locale: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",
+ )
+ end
+ end
+
+ DiscourseAi::Translation::VerboseLogger.log("Detected #{tags.size} tag locales")
+ end
+
+ private
+
+ def find_llm_model
+ persona_klass =
+ AiPersona.find_by_id_from_cache(SiteSetting.ai_translation_locale_detector_persona)
+ return nil if persona_klass.blank?
+
+ DiscourseAi::Translation::BaseTranslator.preferred_llm_model(persona_klass)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/translation.rb b/plugins/discourse-ai/lib/translation.rb
index fb310c797b0..79a923e9351 100644
--- a/plugins/discourse-ai/lib/translation.rb
+++ b/plugins/discourse-ai/lib/translation.rb
@@ -94,5 +94,9 @@ module DiscourseAi
],
)
end
+
+ def self.credits_available_for_tag_localization?
+ credits_available_for_persona_ids?([SiteSetting.ai_translation_short_text_translator_persona])
+ end
end
end
diff --git a/plugins/discourse-ai/lib/translation/tag_candidates.rb b/plugins/discourse-ai/lib/translation/tag_candidates.rb
new file mode 100644
index 00000000000..37d387a0de0
--- /dev/null
+++ b/plugins/discourse-ai/lib/translation/tag_candidates.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Translation
+ class TagCandidates < BaseCandidates
+ private
+
+ # all tags that are eligible for translation based on site settings,
+ # including those without locale detected yet.
+ def self.get
+ tags = Tag.all
+ if SiteSetting.ai_translation_backfill_limit_to_public_content
+ tags = filter_to_public_tags(tags)
+ end
+ tags
+ end
+
+ def self.filter_to_public_tags(tags)
+ # tags visible to everyone are:
+ # 1. not in any tag group, OR
+ # 2. in a tag group that grants permission to EVERYONE
+ everyone_group_id = Group::AUTO_GROUPS[:everyone]
+ tags.where(<<~SQL, everyone_group_id)
+ tags.id NOT IN (SELECT tag_id FROM tag_group_memberships)
+ OR tags.id IN (
+ SELECT tgm.tag_id
+ FROM tag_group_memberships tgm
+ INNER JOIN tag_group_permissions tgp ON tgp.tag_group_id = tgm.tag_group_id
+ WHERE tgp.group_id = ?
+ )
+ SQL
+ end
+
+ def self.calculate_completion_per_locale(locale)
+ base_locale = "#{locale.split("_").first}%"
+ sql = <<~SQL
+ WITH eligible_tags AS (
+ #{get.where.not(tags: { locale: nil }).to_sql}
+ ),
+ total_count AS (
+ SELECT COUNT(*) AS count FROM eligible_tags
+ ),
+ done_count AS (
+ SELECT COUNT(DISTINCT t.id)
+ FROM eligible_tags t
+ LEFT JOIN tag_localizations tl ON t.id = tl.tag_id AND tl.locale LIKE :base_locale
+ WHERE t.locale LIKE :base_locale OR tl.tag_id IS NOT NULL
+ )
+ SELECT d.count AS done, t.count AS total
+ FROM total_count t, done_count d
+ SQL
+
+ done, total = DB.query_single(sql, base_locale:)
+ { done:, total: }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/translation/tag_locale_detector.rb b/plugins/discourse-ai/lib/translation/tag_locale_detector.rb
new file mode 100644
index 00000000000..facdde99645
--- /dev/null
+++ b/plugins/discourse-ai/lib/translation/tag_locale_detector.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Translation
+ class TagLocaleDetector
+ def self.detect_locale(tag)
+ return if tag.blank?
+
+ text = [tag.name, tag.description].compact.join("\n\n")
+ return if text.blank?
+
+ detected_locale = LanguageDetector.new(text).detect
+ return if detected_locale.blank?
+
+ locale = LocaleNormalizer.normalize_to_i18n(detected_locale)
+ tag.update_column(:locale, locale)
+ locale
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/translation/tag_localizer.rb b/plugins/discourse-ai/lib/translation/tag_localizer.rb
new file mode 100644
index 00000000000..ec23082c6b7
--- /dev/null
+++ b/plugins/discourse-ai/lib/translation/tag_localizer.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Translation
+ class TagLocalizer
+ def self.localize(tag, target_locale = I18n.locale, short_text_llm_model: nil)
+ return if tag.blank? || target_locale.blank?
+
+ target_locale = target_locale.to_s.sub("-", "_")
+
+ translated_name =
+ ShortTextTranslator.new(
+ text: tag.name,
+ target_locale:,
+ llm_model: short_text_llm_model,
+ ).translate
+
+ translated_description =
+ if tag.description.present?
+ ShortTextTranslator.new(
+ text: tag.description,
+ target_locale:,
+ llm_model: short_text_llm_model,
+ ).translate
+ end
+
+ localization = TagLocalization.find_or_initialize_by(tag_id: tag.id, locale: target_locale)
+
+ localization.name = translated_name
+ localization.description = translated_description
+ localization.save!
+ localization
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/jobs/regular/localize_tags_spec.rb b/plugins/discourse-ai/spec/jobs/regular/localize_tags_spec.rb
new file mode 100644
index 00000000000..a5f44034e20
--- /dev/null
+++ b/plugins/discourse-ai/spec/jobs/regular/localize_tags_spec.rb
@@ -0,0 +1,168 @@
+# frozen_string_literal: true
+
+describe Jobs::LocalizeTags do
+ subject(:job) { described_class.new }
+
+ def localize_all_tags(*locales)
+ Tag.all.each do |tag|
+ locales.each { |locale| Fabricate(:tag_localization, tag:, locale:, name: "x") }
+ end
+ end
+
+ before do
+ assign_fake_provider_to(:ai_default_llm_model)
+ enable_current_plugin
+ SiteSetting.ai_translation_enabled = true
+ SiteSetting.content_localization_supported_locales = "pt_BR|zh_CN"
+
+ Jobs.run_immediately!
+ end
+
+ it "does nothing when DiscourseAi::Translation is disabled" do
+ SiteSetting.discourse_ai_enabled = false
+
+ DiscourseAi::Translation::TagLocalizer.expects(:localize).never
+
+ job.execute({ limit: 10 })
+ end
+
+ it "does nothing when ai_translation_enabled is disabled" do
+ SiteSetting.ai_translation_enabled = false
+
+ DiscourseAi::Translation::TagLocalizer.expects(:localize).never
+
+ job.execute({ limit: 10 })
+ end
+
+ it "does nothing when no target languages are configured" do
+ SiteSetting.content_localization_supported_locales = ""
+
+ DiscourseAi::Translation::TagLocalizer.expects(:localize).never
+
+ job.execute({ limit: 10 })
+ end
+
+ it "does nothing when no tags exist" do
+ Tag.destroy_all
+
+ DiscourseAi::Translation::TagLocalizer.expects(:localize).never
+
+ job.execute({ limit: 10 })
+ end
+
+ it "skips translation when credits are unavailable" do
+ DiscourseAi::Translation.expects(:credits_available_for_tag_localization?).returns(false)
+ DiscourseAi::Translation::TagLocalizer.expects(:localize).never
+
+ job.execute({ limit: 10 })
+ end
+
+ it "does nothing when the limit is zero" do
+ DiscourseAi::Translation::TagLocalizer.expects(:localize).never
+
+ expect { job.execute({}) }.to raise_error(Discourse::InvalidParameters, /limit/)
+ job.execute({ limit: 0 })
+ end
+
+ it "translates tags to the configured locales" do
+ tag = Fabricate(:tag, locale: "en")
+
+ DiscourseAi::Translation::TagLocalizer
+ .expects(:localize)
+ .with(tag, "pt_BR", has_entries(short_text_llm_model: anything))
+ .once
+ DiscourseAi::Translation::TagLocalizer
+ .expects(:localize)
+ .with(tag, "zh_CN", has_entries(short_text_llm_model: anything))
+ .once
+
+ job.execute({ limit: 10 })
+ end
+
+ it "limits the number of localizations" do
+ SiteSetting.content_localization_supported_locales = "pt"
+
+ 6.times { Fabricate(:tag, locale: "en") }
+
+ DiscourseAi::Translation::TagLocalizer
+ .expects(:localize)
+ .with(is_a(Tag), "pt", has_entries(short_text_llm_model: anything))
+ .times(5)
+
+ job.execute({ limit: 5 })
+ end
+
+ it "skips tags that already have localizations" do
+ tag = Fabricate(:tag, locale: "en")
+ localize_all_tags("pt_BR", "zh_CN")
+
+ DiscourseAi::Translation::TagLocalizer
+ .expects(:localize)
+ .with(tag, "pt_BR", has_entries(short_text_llm_model: anything))
+ .never
+ DiscourseAi::Translation::TagLocalizer
+ .expects(:localize)
+ .with(tag, "zh_CN", has_entries(short_text_llm_model: anything))
+ .never
+
+ job.execute({ limit: 10 })
+ end
+
+ it "handles translation errors gracefully" do
+ tag1 = Fabricate(:tag, name: "first-tag", locale: "en")
+
+ DiscourseAi::Translation::TagLocalizer
+ .expects(:localize)
+ .with(tag1, "pt_BR", has_entries(short_text_llm_model: anything))
+ .once
+ .raises(StandardError.new("API error"))
+ DiscourseAi::Translation::TagLocalizer
+ .expects(:localize)
+ .with(tag1, "zh_CN", has_entries(short_text_llm_model: anything))
+ .once
+
+ expect { job.execute({ limit: 10 }) }.not_to raise_error
+ end
+
+ it "skips creating localizations in the same language as the tag's locale" do
+ tag = Fabricate(:tag, locale: "pt")
+
+ DiscourseAi::Translation::TagLocalizer
+ .expects(:localize)
+ .with(tag, "pt", has_entries(short_text_llm_model: anything))
+ .never
+ DiscourseAi::Translation::TagLocalizer
+ .expects(:localize)
+ .with(tag, "zh_CN", has_entries(short_text_llm_model: anything))
+ .once
+
+ job.execute({ limit: 10 })
+ end
+
+ it "deletes existing localizations that match each tag's locale" do
+ tag1 = Fabricate(:tag, locale: "pt")
+ tag2 = Fabricate(:tag, locale: "zh_CN")
+ Fabricate(:tag_localization, tag: tag1, locale: "pt")
+ Fabricate(:tag_localization, tag: tag1, locale: "zh_CN")
+ Fabricate(:tag_localization, tag: tag2, locale: "pt")
+ Fabricate(:tag_localization, tag: tag2, locale: "zh_CN")
+
+ DiscourseAi::Translation::TagLocalizer.stubs(:localize)
+
+ job.execute({ limit: 10 })
+
+ expect(TagLocalization.where(tag: tag1).pluck(:locale)).to eq(%w[zh_CN])
+ expect(TagLocalization.where(tag: tag2).pluck(:locale)).to eq(%w[pt])
+ end
+
+ it "doesn't process tags with nil locale" do
+ nil_locale_tag = Fabricate(:tag, name: "no-locale", locale: nil)
+
+ DiscourseAi::Translation::TagLocalizer
+ .expects(:localize)
+ .with(nil_locale_tag, any_parameters)
+ .never
+
+ job.execute({ limit: 10 })
+ end
+end
diff --git a/plugins/discourse-ai/spec/jobs/scheduled/tag_localization_backfill_spec.rb b/plugins/discourse-ai/spec/jobs/scheduled/tag_localization_backfill_spec.rb
new file mode 100644
index 00000000000..c25e63db899
--- /dev/null
+++ b/plugins/discourse-ai/spec/jobs/scheduled/tag_localization_backfill_spec.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+describe Jobs::TagLocalizationBackfill do
+ before do
+ enable_current_plugin
+ assign_fake_provider_to(:ai_default_llm_model)
+ SiteSetting.ai_translation_enabled = true
+ SiteSetting.ai_translation_backfill_hourly_rate = 100
+ SiteSetting.ai_translation_backfill_max_age_days = 30
+ SiteSetting.content_localization_supported_locales = "pt_BR|zh_CN"
+ end
+
+ it "does not enqueue when AI is disabled" do
+ SiteSetting.discourse_ai_enabled = false
+
+ described_class.new.execute({})
+
+ expect_not_enqueued_with(job: :localize_tags)
+ end
+
+ it "does not enqueue when translation is disabled" do
+ SiteSetting.ai_translation_enabled = false
+
+ described_class.new.execute({})
+
+ expect_not_enqueued_with(job: :localize_tags)
+ end
+
+ it "does not enqueue when backfill rate is 0" do
+ SiteSetting.ai_translation_backfill_hourly_rate = 0
+
+ described_class.new.execute({})
+
+ expect_not_enqueued_with(job: :localize_tags)
+ end
+
+ it "enqueues localize_tags job with the hourly rate limit" do
+ described_class.new.execute({})
+
+ expect_job_enqueued(job: :localize_tags, args: { limit: 100 })
+ end
+
+ it "does not enqueue when credits are unavailable" do
+ llm_model = Fabricate(:llm_model)
+ short_text_persona = Fabricate(:ai_persona)
+ short_text_persona.update!(default_llm_id: llm_model.id)
+ SiteSetting.ai_translation_short_text_translator_persona = short_text_persona.id
+
+ LlmCreditAllocation.stubs(:credits_available?).with(llm_model).returns(false)
+
+ described_class.new.execute({})
+
+ expect_not_enqueued_with(job: :localize_tags)
+ end
+end
diff --git a/plugins/discourse-ai/spec/jobs/scheduled/tags_locale_detection_backfill_spec.rb b/plugins/discourse-ai/spec/jobs/scheduled/tags_locale_detection_backfill_spec.rb
new file mode 100644
index 00000000000..30a4d563182
--- /dev/null
+++ b/plugins/discourse-ai/spec/jobs/scheduled/tags_locale_detection_backfill_spec.rb
@@ -0,0 +1,125 @@
+# frozen_string_literal: true
+
+describe Jobs::TagsLocaleDetectionBackfill do
+ subject(:job) { described_class.new }
+
+ fab!(:tag) { Fabricate(:tag, locale: nil) }
+
+ before do
+ assign_fake_provider_to(:ai_default_llm_model)
+ enable_current_plugin
+ SiteSetting.ai_translation_enabled = true
+ SiteSetting.ai_translation_backfill_hourly_rate = 100
+ SiteSetting.ai_translation_backfill_max_age_days = 30
+ SiteSetting.content_localization_supported_locales = "en"
+ end
+
+ it "does nothing when AI is disabled" do
+ SiteSetting.discourse_ai_enabled = false
+ DiscourseAi::Translation::TagLocaleDetector.expects(:detect_locale).never
+
+ job.execute({})
+ end
+
+ it "does nothing when content translation is disabled" do
+ SiteSetting.ai_translation_enabled = false
+ DiscourseAi::Translation::TagLocaleDetector.expects(:detect_locale).never
+
+ job.execute({})
+ end
+
+ it "does nothing when backfill rate is 0" do
+ SiteSetting.ai_translation_backfill_hourly_rate = 0
+ DiscourseAi::Translation::TagLocaleDetector.expects(:detect_locale).never
+
+ job.execute({})
+ end
+
+ it "does nothing when there are no tags to detect" do
+ Tag.update_all(locale: "en")
+ DiscourseAi::Translation::TagLocaleDetector.expects(:detect_locale).never
+
+ job.execute({})
+ end
+
+ it "detects locale for tags with nil locale" do
+ Tag.where.not(id: tag.id).update_all(locale: "en")
+ DiscourseAi::Translation::TagLocaleDetector.expects(:detect_locale).with(tag).once
+
+ job.execute({})
+ end
+
+ it "handles detection errors gracefully" do
+ Tag.where.not(id: tag.id).update_all(locale: "en")
+ DiscourseAi::Translation::TagLocaleDetector
+ .expects(:detect_locale)
+ .with(tag)
+ .raises(StandardError.new("error"))
+ .once
+
+ expect { job.execute({}) }.not_to raise_error
+ end
+
+ it "logs a summary after running" do
+ Tag.where.not(id: tag.id).update_all(locale: "en")
+ DiscourseAi::Translation::TagLocaleDetector.stubs(:detect_locale)
+ DiscourseAi::Translation::VerboseLogger.expects(:log).with(includes("Detected 1 tag locales"))
+
+ job.execute({})
+ end
+
+ describe "with public content limitation" do
+ fab!(:tag_group)
+ fab!(:restricted_group, :group)
+
+ before do
+ SiteSetting.ai_translation_backfill_limit_to_public_content = true
+ Tag.update_all(locale: "en")
+ end
+
+ it "processes tags not in any tag group" do
+ standalone_tag = Fabricate(:tag, locale: nil)
+ DiscourseAi::Translation::TagLocaleDetector.expects(:detect_locale).with(standalone_tag).once
+
+ job.execute({})
+ end
+
+ it "processes tags in tag groups visible to everyone" do
+ public_tag = Fabricate(:tag, locale: nil)
+ tag_group.tags << public_tag
+ TagGroupPermission.create!(
+ tag_group: tag_group,
+ group_id: Group::AUTO_GROUPS[:everyone],
+ permission_type: TagGroupPermission.permission_types[:full],
+ )
+
+ DiscourseAi::Translation::TagLocaleDetector.expects(:detect_locale).with(public_tag).once
+
+ job.execute({})
+ end
+
+ it "skips tags in tag groups not visible to everyone" do
+ restricted_tag = Fabricate(:tag, locale: nil)
+ tag_group.tags << restricted_tag
+ TagGroupPermission.where(tag_group: tag_group).destroy_all
+ TagGroupPermission.create!(
+ tag_group: tag_group,
+ group_id: restricted_group.id,
+ permission_type: TagGroupPermission.permission_types[:full],
+ )
+
+ DiscourseAi::Translation::TagLocaleDetector.expects(:detect_locale).never
+
+ job.execute({})
+ end
+ end
+
+ it "limits processing to the backfill rate" do
+ SiteSetting.ai_translation_backfill_hourly_rate = 1
+ Fabricate(:tag, locale: nil)
+
+ DiscourseAi::Translation::TagLocaleDetector.expects(:detect_locale).once
+
+ job.execute({})
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/translation/tag_candidates_spec.rb b/plugins/discourse-ai/spec/lib/translation/tag_candidates_spec.rb
new file mode 100644
index 00000000000..20a2d4b59a1
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/translation/tag_candidates_spec.rb
@@ -0,0 +1,131 @@
+# frozen_string_literal: true
+
+describe DiscourseAi::Translation::TagCandidates do
+ describe ".get" do
+ it "returns all tags" do
+ Fabricate(:tag)
+ expect(DiscourseAi::Translation::TagCandidates.get.count).to eq(Tag.count)
+ end
+
+ context "when ai_translation_backfill_limit_to_public_content is enabled" do
+ before { SiteSetting.ai_translation_backfill_limit_to_public_content = true }
+
+ it "includes tags not in any tag group" do
+ tag = Fabricate(:tag)
+
+ tags = DiscourseAi::Translation::TagCandidates.get
+ expect(tags).to include(tag)
+ end
+
+ it "includes tags in tag groups visible to everyone" do
+ tag = Fabricate(:tag)
+ tag_group = Fabricate(:tag_group, tags: [tag])
+ TagGroupPermission.create!(
+ tag_group: tag_group,
+ group_id: Group::AUTO_GROUPS[:everyone],
+ permission_type: TagGroupPermission.permission_types[:full],
+ )
+
+ tags = DiscourseAi::Translation::TagCandidates.get
+ expect(tags).to include(tag)
+ end
+
+ it "excludes tags in tag groups not visible to everyone" do
+ tag = Fabricate(:tag)
+ tag_group = Fabricate(:tag_group, tags: [tag])
+ # remove default everyone permission if exists
+ TagGroupPermission.where(tag_group: tag_group).destroy_all
+ # add restricted permission
+ restricted_group = Fabricate(:group)
+ TagGroupPermission.create!(
+ tag_group: tag_group,
+ group_id: restricted_group.id,
+ permission_type: TagGroupPermission.permission_types[:full],
+ )
+
+ tags = DiscourseAi::Translation::TagCandidates.get
+ expect(tags).not_to include(tag)
+ end
+ end
+ end
+
+ describe ".calculate_completion_per_locale" do
+ before { Tag.destroy_all }
+
+ context "when completion determined by tag's locale" do
+ it "returns done = total if all tags are in the locale" do
+ locale = "pt_BR"
+ Fabricate(:tag, locale:)
+ Fabricate(:tag, locale: "pt") # pt counts as pt_BR
+
+ completion = DiscourseAi::Translation::TagCandidates.calculate_completion_per_locale(locale)
+ expect(completion).to eq({ done: Tag.count, total: Tag.count })
+ end
+
+ it "returns correct done and total if some tags are in the locale" do
+ locale = "pt_BR"
+ Fabricate(:tag, locale:)
+ Fabricate(:tag, locale: "ar") # not portuguese
+
+ completion = DiscourseAi::Translation::TagCandidates.calculate_completion_per_locale(locale)
+ expect(completion).to eq({ done: 1, total: Tag.count })
+ end
+ end
+
+ context "when completion determined by tag localizations" do
+ it "returns done = total if all tags have a localization in the locale" do
+ locale = "pt_BR"
+ tag1 = Fabricate(:tag, locale: "en")
+ tag2 = Fabricate(:tag, locale: "en")
+ Fabricate(:tag_localization, tag: tag1, locale:)
+ Fabricate(:tag_localization, tag: tag2, locale: "pt") # pt counts as pt_BR
+
+ completion = DiscourseAi::Translation::TagCandidates.calculate_completion_per_locale(locale)
+ expect(completion).to eq({ done: Tag.count, total: Tag.count })
+ end
+
+ it "returns correct done and total if some tags have a localization in the locale" do
+ locale = "es"
+ tag1 = Fabricate(:tag, locale: "en")
+ tag2 = Fabricate(:tag, locale: "fr")
+ Fabricate(:tag_localization, tag: tag1, locale:)
+ Fabricate(:tag_localization, tag: tag2, locale: "ar") # not the target locale
+
+ completion = DiscourseAi::Translation::TagCandidates.calculate_completion_per_locale(locale)
+ expect(completion).to eq({ done: 1, total: Tag.count })
+ end
+ end
+
+ it "returns correct done and total based on both tag.locale and TagLocalization" do
+ locale = "pt_BR"
+
+ # translated candidates
+ Fabricate(:tag, locale:)
+ tag2 = Fabricate(:tag, locale: "en")
+ Fabricate(:tag_localization, tag: tag2, locale:)
+
+ # untranslated candidate
+ tag3 = Fabricate(:tag, locale: "fr")
+ Fabricate(:tag_localization, tag: tag3, locale: "zh_CN")
+
+ completion = DiscourseAi::Translation::TagCandidates.calculate_completion_per_locale(locale)
+ translated_candidates = 2
+ total_candidates = Tag.count
+ expect(completion).to eq({ done: translated_candidates, total: total_candidates })
+ end
+
+ it "does not allow done to exceed total when tag.locale and tag_localization both exist" do
+ locale = "pt_BR"
+ tag = Fabricate(:tag, locale:)
+ Fabricate(:tag_localization, tag:, locale:)
+
+ completion = DiscourseAi::Translation::TagCandidates.calculate_completion_per_locale(locale)
+ expect(completion).to eq({ done: Tag.count, total: Tag.count })
+ end
+
+ it "returns 0 for done and total when no tags are present" do
+ completion = DiscourseAi::Translation::TagCandidates.calculate_completion_per_locale("pt")
+ expect(completion).to eq({ done: 0, total: 0 })
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/translation/tag_locale_detector_spec.rb b/plugins/discourse-ai/spec/lib/translation/tag_locale_detector_spec.rb
new file mode 100644
index 00000000000..c7076bdb892
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/translation/tag_locale_detector_spec.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+describe DiscourseAi::Translation::TagLocaleDetector do
+ before { enable_current_plugin }
+
+ describe ".detect_locale" do
+ fab!(:tag) { Fabricate(:tag, name: "hello-world", description: "A test tag", locale: nil) }
+
+ def language_detector_stub(opts)
+ mock = instance_double(DiscourseAi::Translation::LanguageDetector)
+ allow(DiscourseAi::Translation::LanguageDetector).to receive(:new).with(
+ opts[:text],
+ ).and_return(mock)
+ allow(mock).to receive(:detect).and_return(opts[:locale])
+ end
+
+ it "returns nil if tag is blank" do
+ expect(described_class.detect_locale(nil)).to eq(nil)
+ end
+
+ it "returns nil if detected locale is blank and does not update tag" do
+ text = "#{tag.name}\n\n#{tag.description}"
+ language_detector_stub({ text: text, locale: nil })
+
+ expect(described_class.detect_locale(tag)).to eq(nil)
+ expect { described_class.detect_locale(tag) }.not_to change { tag }
+ end
+
+ it "updates the tag locale with the detected locale" do
+ text = "#{tag.name}\n\n#{tag.description}"
+ language_detector_stub({ text: text, locale: "zh_CN" })
+
+ expect { described_class.detect_locale(tag) }.to change { tag.reload.locale }.from(nil).to(
+ "zh_CN",
+ )
+ end
+
+ it "handles tag with no description" do
+ no_description_tag = Fabricate(:tag, name: "test-tag", description: nil, locale: nil)
+ language_detector_stub({ text: no_description_tag.name, locale: "fr" })
+
+ expect { described_class.detect_locale(no_description_tag) }.to change {
+ no_description_tag.reload.locale
+ }.from(nil).to("fr")
+ end
+
+ it "bypasses validations when updating locale" do
+ language_detector_stub({ text: "#{tag.name}\n\n#{tag.description}", locale: "zh_CN" })
+
+ described_class.detect_locale(tag)
+ expect(tag.reload.locale).to eq("zh_CN")
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/translation/tag_localizer_spec.rb b/plugins/discourse-ai/spec/lib/translation/tag_localizer_spec.rb
new file mode 100644
index 00000000000..d571fe78483
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/translation/tag_localizer_spec.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+describe DiscourseAi::Translation::TagLocalizer do
+ subject(:localizer) { described_class }
+
+ before do
+ enable_current_plugin
+ assign_fake_provider_to(:ai_default_llm_model)
+ end
+
+ def short_text_translator_stub(opts)
+ mock = instance_double(DiscourseAi::Translation::ShortTextTranslator)
+ allow(DiscourseAi::Translation::ShortTextTranslator).to receive(:new).with(
+ text: opts[:text],
+ target_locale: opts[:target_locale],
+ llm_model: be_nil,
+ ).and_return(mock)
+ allow(mock).to receive(:translate).and_return(opts[:translated])
+ end
+
+ fab!(:tag) { Fabricate(:tag, name: "test-tag", description: "This is a test tag description") }
+
+ describe ".localize" do
+ let(:target_locale) { "fr" }
+
+ it "translates the tag name and description" do
+ translated_tag_desc = "C'est une description de tag de test"
+ translated_tag_name = "tag-de-test"
+ short_text_translator_stub(
+ { text: tag.name, target_locale: target_locale, translated: translated_tag_name },
+ )
+ short_text_translator_stub(
+ { text: tag.description, target_locale: target_locale, translated: translated_tag_desc },
+ )
+
+ res = localizer.localize(tag, target_locale)
+
+ expect(res.name).to eq(translated_tag_name)
+ expect(res.description).to eq(translated_tag_desc)
+ end
+
+ it "handles tag without description" do
+ tag_no_desc = Fabricate(:tag, name: "no-desc-tag", description: nil)
+ translated_tag_name = "tag-sans-description"
+ short_text_translator_stub(
+ { text: tag_no_desc.name, target_locale: target_locale, translated: translated_tag_name },
+ )
+
+ res = localizer.localize(tag_no_desc, target_locale)
+
+ expect(res.name).to eq(translated_tag_name)
+ expect(res.description).to be_nil
+ end
+
+ it "returns nil if tag is blank" do
+ expect(localizer.localize(nil)).to be_nil
+ end
+
+ it "returns nil if target locale is blank" do
+ expect(localizer.localize(tag, nil)).to be_nil
+ end
+
+ it "uses I18n.locale as default when no target locale is provided" do
+ I18n.locale = :es
+ translated_tag_desc = "Esta es una descripción de tag de prueba"
+ translated_tag_name = "tag-de-prueba"
+ short_text_translator_stub(
+ { text: tag.name, target_locale: "es", translated: translated_tag_name },
+ )
+ short_text_translator_stub(
+ { text: tag.description, target_locale: "es", translated: translated_tag_desc },
+ )
+
+ res = localizer.localize(tag)
+
+ expect(res.name).to eq(translated_tag_name)
+ expect(res.description).to eq(translated_tag_desc)
+ expect(res.locale).to eq("es")
+ end
+
+ it "updates existing localization if one exists" do
+ existing = Fabricate(:tag_localization, tag: tag, locale: target_locale, name: "old-name")
+ translated_tag_name = "tag-de-test"
+ translated_tag_desc = "C'est une description"
+ short_text_translator_stub(
+ { text: tag.name, target_locale: target_locale, translated: translated_tag_name },
+ )
+ short_text_translator_stub(
+ { text: tag.description, target_locale: target_locale, translated: translated_tag_desc },
+ )
+
+ expect { localizer.localize(tag, target_locale) }.not_to change { TagLocalization.count }
+
+ existing.reload
+ expect(existing.name).to eq(translated_tag_name)
+ expect(existing.description).to eq(translated_tag_desc)
+ end
+ end
+end
diff --git a/spec/fabricators/tag_localization_fabricator.rb b/spec/fabricators/tag_localization_fabricator.rb
index cc2685cf8b7..9842c93ac73 100644
--- a/spec/fabricators/tag_localization_fabricator.rb
+++ b/spec/fabricators/tag_localization_fabricator.rb
@@ -3,6 +3,6 @@
Fabricator(:tag_localization) do
tag
locale "ja"
- name { sequence(:name) { |i| "タグ#{i + 1}" } }
- description "タグの説明"
+ name { sequence(:name) { |i| "猫タグ#{i + 1}" } }
+ description "猫についてのタグです"
end
diff --git a/spec/lib/tag_localization_creator_spec.rb b/spec/lib/tag_localization_creator_spec.rb
new file mode 100644
index 00000000000..91aa5600199
--- /dev/null
+++ b/spec/lib/tag_localization_creator_spec.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+describe TagLocalizationCreator do
+ fab!(:user)
+ fab!(:tag)
+ fab!(:group)
+
+ let(:locale) { "ja" }
+ let(:name) { "猫タグ" }
+ let(:description) { "猫についてのタグです" }
+
+ before do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_allowed_groups = group.id.to_s
+ group.add(user)
+ end
+
+ it "creates a tag localization record" do
+ localization = described_class.create(tag:, locale:, name:, description:, user:)
+
+ expect(TagLocalization.find(localization.id)).to have_attributes(
+ tag_id: tag.id,
+ locale:,
+ name:,
+ description:,
+ )
+ end
+
+ it "creates localization without description" do
+ localization = described_class.create(tag:, locale:, name:, user:)
+
+ expect(TagLocalization.find(localization.id)).to have_attributes(
+ tag_id: tag.id,
+ locale:,
+ name:,
+ description: nil,
+ )
+ end
+
+ it "raises not found if the tag is nil" do
+ expect { described_class.create(tag: nil, locale:, name:, user:) }.to raise_error(
+ Discourse::NotFound,
+ )
+ end
+
+ it "raises permission error if user is not in allowed groups" do
+ group.remove(user)
+
+ expect { described_class.create(tag:, locale:, name:, user:) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+end
diff --git a/spec/lib/tag_localization_destroyer_spec.rb b/spec/lib/tag_localization_destroyer_spec.rb
new file mode 100644
index 00000000000..bf7148c5fe3
--- /dev/null
+++ b/spec/lib/tag_localization_destroyer_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+describe TagLocalizationDestroyer do
+ fab!(:user)
+ fab!(:tag)
+ fab!(:group)
+
+ let(:locale) { "ja" }
+
+ before do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_allowed_groups = group.id.to_s
+ group.add(user)
+ end
+
+ it "destroys a tag localization record" do
+ localization = Fabricate(:tag_localization, tag: tag, locale:)
+
+ expect { described_class.destroy(tag:, locale:, acting_user: user) }.to change {
+ TagLocalization.count
+ }.by(-1)
+ end
+
+ it "raises not found if the tag is nil" do
+ expect { described_class.destroy(tag: nil, locale:, acting_user: user) }.to raise_error(
+ Discourse::NotFound,
+ )
+ end
+
+ it "raises not found if the localization is missing" do
+ expect { described_class.destroy(tag:, locale: "nope", acting_user: user) }.to raise_error(
+ Discourse::NotFound,
+ )
+ end
+
+ it "raises permission error if user is not in allowed groups" do
+ Fabricate(:tag_localization, tag: tag, locale:)
+ group.remove(user)
+
+ expect { described_class.destroy(tag:, locale:, acting_user: user) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+end
diff --git a/spec/lib/tag_localization_updater_spec.rb b/spec/lib/tag_localization_updater_spec.rb
new file mode 100644
index 00000000000..a7df1e1501e
--- /dev/null
+++ b/spec/lib/tag_localization_updater_spec.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+describe TagLocalizationUpdater do
+ fab!(:user)
+ fab!(:tag)
+ fab!(:group)
+ fab!(:localization) { Fabricate(:tag_localization, tag: tag, locale: "ja", name: "古い猫") }
+
+ let(:locale) { "ja" }
+ let(:name) { "新しい猫" }
+ let(:description) { "かわいい猫のタグ" }
+
+ before do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_allowed_groups = group.id.to_s
+ group.add(user)
+ end
+
+ it "updates a tag localization record" do
+ described_class.update(tag:, locale:, name:, description:, user:)
+
+ localization.reload
+ expect(localization).to have_attributes(name:, description:)
+ end
+
+ it "returns localization without saving if nothing changed" do
+ result =
+ described_class.update(
+ tag:,
+ locale:,
+ name: localization.name,
+ description: localization.description,
+ user:,
+ )
+
+ expect(result).to eq(localization)
+ end
+
+ it "raises not found if the tag is nil" do
+ expect { described_class.update(tag: nil, locale:, name:, user:) }.to raise_error(
+ Discourse::NotFound,
+ )
+ end
+
+ it "raises not found if the localization is missing" do
+ expect { described_class.update(tag:, locale: "nope", name:, user:) }.to raise_error(
+ Discourse::NotFound,
+ )
+ end
+
+ it "raises permission error if user is not in allowed groups" do
+ group.remove(user)
+
+ expect { described_class.update(tag:, locale:, name:, user:) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+end
diff --git a/spec/requests/tag_localizations_controller_spec.rb b/spec/requests/tag_localizations_controller_spec.rb
new file mode 100644
index 00000000000..2c9887cfbf6
--- /dev/null
+++ b/spec/requests/tag_localizations_controller_spec.rb
@@ -0,0 +1,190 @@
+# frozen_string_literal: true
+
+describe TagLocalizationsController do
+ fab!(:user)
+ fab!(:group)
+ fab!(:tag)
+
+ let(:locale) { "ja" }
+ let(:name) { "猫タグ" }
+ let(:description) { "猫についてのタグです" }
+
+ before do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_allowed_groups = group.id.to_s
+ group.add(user)
+ sign_in(user)
+ end
+
+ describe "#show" do
+ it "allows users in allowed groups to view localizations" do
+ Fabricate(:tag_localization, tag: tag, locale:)
+
+ get "/tag_localizations/#{tag.id}.json"
+
+ expect(response.status).to eq(200)
+ json = response.parsed_body
+ expect(json["tag_localizations"].length).to eq(1)
+ end
+
+ it "denies users not in allowed groups" do
+ group.remove(user)
+
+ get "/tag_localizations/#{tag.id}.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 404 for non-existent tag" do
+ get "/tag_localizations/-1.json"
+
+ expect(response.status).to eq(404)
+ end
+ end
+
+ describe "#create_or_update" do
+ context "when localization does not exist" do
+ it "creates a new localization" do
+ expect {
+ post "/tag_localizations/create_or_update.json",
+ params: {
+ tag_id: tag.id,
+ locale:,
+ name:,
+ description:,
+ }
+ }.to change { TagLocalization.count }.by(1)
+
+ expect(response.status).to eq(201)
+ localization = TagLocalization.last
+ expect(localization).to have_attributes(locale:, name:, description:, tag_id: tag.id)
+ end
+
+ it "creates localization without description" do
+ expect {
+ post "/tag_localizations/create_or_update.json",
+ params: {
+ tag_id: tag.id,
+ locale:,
+ name:,
+ }
+ }.to change { TagLocalization.count }.by(1)
+
+ expect(response.status).to eq(201)
+ localization = TagLocalization.last
+ expect(localization.description).to be_nil
+ end
+ end
+
+ context "when localization already exists" do
+ it "updates the existing localization" do
+ localization = Fabricate(:tag_localization, tag: tag, locale:, name: "古い猫")
+
+ expect {
+ post "/tag_localizations/create_or_update.json",
+ params: {
+ tag_id: tag.id,
+ locale:,
+ name:,
+ description:,
+ }
+ }.not_to change { TagLocalization.count }
+
+ expect(response.status).to eq(200)
+ localization.reload
+ expect(localization.name).to eq(name)
+ expect(localization.description).to eq(description)
+ end
+ end
+
+ it "returns forbidden if user is not in allowed group" do
+ group.remove(user)
+
+ post "/tag_localizations/create_or_update.json", params: { tag_id: tag.id, locale:, name: }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns not found if tag does not exist" do
+ post "/tag_localizations/create_or_update.json", params: { tag_id: -1, locale:, name: }
+
+ expect(response.status).to eq(404)
+ end
+ end
+
+ describe "#destroy" do
+ it "destroys the localization" do
+ Fabricate(:tag_localization, tag: tag, locale:)
+
+ expect {
+ delete "/tag_localizations/destroy.json", params: { tag_id: tag.id, locale: }
+ }.to change { TagLocalization.count }.by(-1)
+
+ expect(response.status).to eq(204)
+ end
+
+ it "returns 404 if localization is missing" do
+ delete "/tag_localizations/destroy.json", params: { tag_id: tag.id, locale: "nope" }
+
+ expect(response.status).to eq(404)
+ end
+ end
+
+ context "when content_localization_enabled is false" do
+ before { SiteSetting.content_localization_enabled = false }
+
+ it "denies access to show" do
+ get "/tag_localizations/#{tag.id}.json"
+ expect(response.status).to eq(403)
+ end
+
+ it "denies access to create_or_update" do
+ post "/tag_localizations/create_or_update.json", params: { tag_id: tag.id, locale:, name: }
+ expect(response.status).to eq(403)
+ end
+
+ it "denies access to destroy" do
+ Fabricate(:tag_localization, tag: tag, locale:)
+ delete "/tag_localizations/destroy.json", params: { tag_id: tag.id, locale: }
+ expect(response.status).to eq(403)
+ end
+ end
+
+ context "when tag is in a restricted tag group" do
+ fab!(:restricted_group, :group)
+ fab!(:tag_group) { Fabricate(:tag_group, tags: [tag]) }
+
+ before do
+ TagGroupPermission.where(tag_group: tag_group).destroy_all
+ TagGroupPermission.create!(
+ tag_group: tag_group,
+ group_id: restricted_group.id,
+ permission_type: TagGroupPermission.permission_types[:full],
+ )
+ end
+
+ it "denies access to show for users who cannot see the tag" do
+ get "/tag_localizations/#{tag.id}.json"
+ expect(response.status).to eq(403)
+ end
+
+ it "denies access to create_or_update for users who cannot see the tag" do
+ post "/tag_localizations/create_or_update.json", params: { tag_id: tag.id, locale:, name: }
+ expect(response.status).to eq(403)
+ end
+
+ it "allows access when user is in the restricted group" do
+ restricted_group.add(user)
+
+ get "/tag_localizations/#{tag.id}.json"
+ expect(response.status).to eq(200)
+ end
+
+ it "allows staff to access restricted tags" do
+ user.update!(admin: true)
+
+ get "/tag_localizations/#{tag.id}.json"
+ expect(response.status).to eq(200)
+ end
+ end
+end