A platform for community discussion. Free, open, simple.
FEATURE: Add topic admin button to schedule translations for untranslated posts (#36172)
Rafael dos Santos Silvab5d1130e0938
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rbindex eb109c71217..a651d1961d5 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rb@@ -32,6 +32,40 @@ module DiscourseAirender json: success_jsonend+ def schedule_topic+ topic = Topic.find_by(id: params[:topic_id])+ raise ActiveRecord::RecordNotFound unless topic++ unless DiscourseAi::Translation.enabled?+ return(+ render json:+ failed_json.merge(error: I18n.t("discourse_ai.translation.errors.disabled")),+ status: :bad_request+ )+ end++ guardian.ensure_can_see!(topic)++ untranslated_posts = find_untranslated_posts(topic)++ if untranslated_posts.empty?+ return(+ render_json_error(+ I18n.t("discourse_ai.translation.errors.all_posts_translated"),+ status: :unprocessable_entity,+ )+ )+ end++ Jobs.enqueue(:detect_translate_topic, topic_id: topic.id, force: true)++ untranslated_posts.each do |post|+ Jobs.enqueue(:detect_translate_post, post_id: post.id, force: true)+ end++ render json: success_json.merge(scheduled_posts: untranslated_posts.count)+ end+privatedef check_permissions@@ -47,6 +81,35 @@ module DiscourseAirender_json_error(I18n.t("rate_limiter.slow_down"))endend++ def find_untranslated_posts(topic)+ supported_locales = SiteSetting.content_localization_supported_locales.split("|")+ base_locales = supported_locales.map { |locale| locale.split("_").first }++ # Find posts that:+ # 1. Have a detected locale+ # 2. Need translation to other supported locales (excluding their own locale)+ # 3. Don't have PostLocalization records for those target locales yet+ # 4. Are not deleted and have content+ topic+ .posts+ .where("user_id > 0")+ .where.not(raw: "")+ .where(deleted_at: nil)+ .where.not(locale: nil)+ .where(+ "EXISTS (+ SELECT 1 FROM unnest(ARRAY[?]) AS target_locale+ WHERE split_part(posts.locale, '_', 1) != target_locale+ AND NOT EXISTS (+ SELECT 1 FROM post_localizations pl+ WHERE pl.post_id = posts.id+ AND split_part(pl.locale, '_', 1) = target_locale+ )+ )",+ base_locales,+ )+ endendendenddiff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-translation-topic-admin.gjs b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-translation-topic-admin.gjsnew file mode 100644index 00000000000..10d6ff41969--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-translation-topic-admin.gjs@@ -0,0 +1,76 @@+import { ajax } from "discourse/lib/ajax";+import { apiInitializer } from "discourse/lib/api";+import { i18n } from "discourse-i18n";++/**+ * Initializer that adds a topic admin menu button for scheduling translations+ * of untranslated posts in a topic.+ *+ * @module ai-translation-topic-admin+ */+export default apiInitializer((api) => {+ const settings = api.container.lookup("service:site-settings");++ if (!settings.discourse_ai_enabled || !settings.ai_translation_enabled) {+ return;+ }++ api.addTopicAdminMenuButton((topic) => {+ const currentUser = api.getCurrentUser();++ if (!currentUser) {+ return;+ }++ const allowedGroups = settings.content_localization_allowed_groups+ .split("|")+ .map((id) => parseInt(id, 10));++ const userGroupIds = currentUser.groups.map((g) => g.id);+ const hasPermission = allowedGroups.some((groupId) =>+ userGroupIds.includes(groupId)+ );++ if (!hasPermission) {+ return;+ }++ return {+ action: async () => {+ const toasts = api.container.lookup("service:toasts");++ try {+ const result = await ajax(+ `/discourse-ai/translate/topics/${topic.id}`,+ {+ type: "POST",+ }+ );++ toasts.success({+ duration: 5000,+ data: {+ message: i18n("discourse_ai.translation.schedule_topic_success", {+ count: result.scheduled_posts,+ }),+ },+ });+ } catch (error) {+ const errorMessage =+ error.jqXHR?.responseJSON?.errors?.[0] ||+ i18n("discourse_ai.translation.schedule_topic_error");++ toasts.error({+ duration: 5000,+ data: {+ message: errorMessage,+ },+ });+ }+ },+ icon: "language",+ className: "schedule-topic-translations-button",+ label: "discourse_ai.ai_features.translation.schedule_untranslated",+ };+ });+});diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 08279e55d9c..4ed61386222 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -307,6 +307,11 @@ en:post_raw_translator: "Post raw translator"topic_title_translator: "Topic title translator"short_text_translator: "Short text translator"+ schedule_untranslated: "Schedule translations"+ schedule_topic_success:+ one: "Scheduled translation for %{count} untranslated post."+ other: "Scheduled translation for %{count} untranslated posts."+ schedule_topic_error: "Failed to schedule translations. Please try again."spam:name: "Spam"diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex ea5f6da3f20..59eac872fb5 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -664,6 +664,7 @@ en:translation:errors:disabled: "The AI translation feature is not fully configured."+ all_posts_translated: "All posts in this topic are already translated."llm_credit_allocation:limit_exceeded: "You have reached your AI credit limit. Please try again in %{reset_time}."diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rbindex a985d51540f..4bd21b70edf 100644--- a/plugins/discourse-ai/config/routes.rb+++ b/plugins/discourse-ai/config/routes.rb@@ -67,6 +67,7 @@ DiscourseAi::Engine.routes.draw doscope module: :translation, path: "/translate", defaults: { format: :json } dopost "/posts/:post_id" => "translation#translate"+ post "/topics/:topic_id" => "translation#schedule_topic"endenddiff --git a/plugins/discourse-ai/spec/requests/translation/translation_controller_spec.rb b/plugins/discourse-ai/spec/requests/translation/translation_controller_spec.rbindex 870ea370321..724248a12fa 100644--- a/plugins/discourse-ai/spec/requests/translation/translation_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/translation/translation_controller_spec.rb@@ -81,4 +81,146 @@ describe DiscourseAi::Translation::TranslationController doendendend++ describe "#schedule_topic" do+ fab!(:topic)+ fab!(:post1) { Fabricate(:post, topic: topic, user: user) }+ fab!(:post2) { Fabricate(:post, topic: topic, user: user) }++ context "when not logged in" do+ it "returns a 403 response" do+ post "/discourse-ai/translate/topics/#{topic.id}"+ expect(response.status).to eq(403)+ end+ end++ context "when logged in but not in allowed groups" do+ it "returns a 403 response" do+ sign_in(user)+ post "/discourse-ai/translate/topics/#{topic.id}"+ expect(response.status).to eq(403)+ end+ end++ context "when logged in and in allowed groups" do+ before do+ group.add(user)+ SiteSetting.content_localization_allowed_groups = group.id.to_s+ sign_in(user)+ end++ it "returns a 404 for non-existent topic" do+ post "/discourse-ai/translate/topics/999999"+ expect(response.status).to eq(404)+ end++ it "successfully enqueues translation jobs for untranslated posts" do+ post1.update!(locale: "en")+ post2.update!(locale: "en")+ SiteSetting.content_localization_supported_locales = "en|es"++ expect_enqueued_with(+ job: Jobs::DetectTranslateTopic,+ args: {+ topic_id: topic.id,+ force: true,+ },+ ) do+ expect_enqueued_with(+ job: Jobs::DetectTranslatePost,+ args: {+ post_id: post1.id,+ force: true,+ },+ ) do+ expect_enqueued_with(+ job: Jobs::DetectTranslatePost,+ args: {+ post_id: post2.id,+ force: true,+ },+ ) { post "/discourse-ai/translate/topics/#{topic.id}" }+ end+ end++ expect(response.status).to eq(200)+ expect(response.parsed_body["scheduled_posts"]).to eq(2)+ end++ it "returns error when all posts are already translated" do+ post1.update!(locale: "en")+ post2.update!(locale: "en")+ SiteSetting.content_localization_supported_locales = "en"++ post "/discourse-ai/translate/topics/#{topic.id}"+ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to include(+ I18n.t("discourse_ai.translation.errors.all_posts_translated"),+ )+ end++ it "ignores posts without detected locale" do+ post1.update!(locale: "en")+ post2.update!(locale: nil)+ SiteSetting.content_localization_supported_locales = "en|es"++ expect_enqueued_with(+ job: Jobs::DetectTranslatePost,+ args: {+ post_id: post1.id,+ force: true,+ },+ ) { post "/discourse-ai/translate/topics/#{topic.id}" }++ expect(response.status).to eq(200)+ expect(response.parsed_body["scheduled_posts"]).to eq(1)+ end++ it "ignores deleted posts" do+ post1.update!(locale: "en", deleted_at: Time.now)+ post2.update!(locale: "en")+ SiteSetting.content_localization_supported_locales = "en|es"++ expect_enqueued_with(+ job: Jobs::DetectTranslatePost,+ args: {+ post_id: post2.id,+ force: true,+ },+ ) { post "/discourse-ai/translate/topics/#{topic.id}" }++ expect(response.status).to eq(200)+ expect(response.parsed_body["scheduled_posts"]).to eq(1)+ end++ it "ignores posts that already have translations" do+ post1.update!(locale: "en")+ post2.update!(locale: "en")+ SiteSetting.content_localization_supported_locales = "en|es"++ Fabricate(:post_localization, post: post1, locale: "es")++ expect_enqueued_with(+ job: Jobs::DetectTranslatePost,+ args: {+ post_id: post2.id,+ force: true,+ },+ ) { post "/discourse-ai/translate/topics/#{topic.id}" }++ expect(response.status).to eq(200)+ expect(response.parsed_body["scheduled_posts"]).to eq(1)+ end+ end++ context "when required settings are unconfigured" do+ it "returns a 400 response" do+ sign_in(admin)+ SiteSetting.ai_translation_enabled = false++ post "/discourse-ai/translate/topics/#{topic.id}"+ expect(response.status).to eq(400)+ end+ end+ endend