Skip to content

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

UX: Show a bit more information on translation progress chart (#34643)

Natalie Tay86fcf3708227
diff --git a/app/assets/javascripts/admin/addon/components/chart.gjs b/app/assets/javascripts/admin/addon/components/chart.gjs
index c2e91a4ce0f..3ab13494800 100644
--- a/app/assets/javascripts/admin/addon/components/chart.gjs
+++ b/app/assets/javascripts/admin/addon/components/chart.gjs
@@ -6,11 +6,20 @@ import loadScript from "discourse/lib/load-script";
// chartConfig - object
export default class Chart extends Component {
renderChart = modifier((element) => {
- const { chartConfig } = this.args;
+ const { chartConfig, loadChartDataLabelsPlugin } = this.args;
- loadScript("/javascripts/Chart.min.js").then(() => {
- this.chart = new window.Chart(element.getContext("2d"), chartConfig);
- });
+ loadScript("/javascripts/Chart.min.js")
+ .then(
+ () =>
+ loadChartDataLabelsPlugin &&
+ loadScript("/javascripts/chartjs-plugin-datalabels.min.js")
+ )
+ .then(() => {
+ if (loadChartDataLabelsPlugin) {
+ (chartConfig.plugins ??= []).push(window.ChartDataLabels);
+ }
+ this.chart = new window.Chart(element.getContext("2d"), chartConfig);
+ });
return () => this.chart?.destroy();
});
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_translations_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_translations_controller.rb
index 3a617aa84fc..8869ab9b7a6 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_translations_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_translations_controller.rb
@@ -9,29 +9,34 @@ module DiscourseAi
supported_locales =
SiteSetting.content_localization_supported_locales.presence&.split("|") || []
+ if supported_locales.empty?
+ return(
+ render json: {
+ translation_progress: [],
+ translation_id: DiscourseAi::Configuration::Module::TRANSLATION_ID,
+ enabled: DiscourseAi::Translation.backfill_enabled?,
+ total: 0,
+ posts_with_detected_locale: 0,
+ }
+ )
+ end
+
+ candidates = DiscourseAi::Translation::PostCandidates
+
result =
supported_locales.map do |locale|
- completion_data =
- DiscourseAi::Translation::PostCandidates.get_completion_per_locale(locale)
-
- total = completion_data[:total].to_f
- done = completion_data[:done].to_f
- remaining = total - done
-
- completion_percentage = safe_percentage(done, total)
- remaining_percentage = safe_percentage(remaining, total)
-
- {
- locale: locale,
- completion_percentage: completion_percentage,
- remaining_percentage: remaining_percentage,
- }
+ candidates.get_completion_per_locale(locale) in { total:, done: }
+ { locale:, total:, done: }
end
+ candidates.get_total_and_with_locale_count in { total:, posts_with_detected_locale: }
+
render json: {
translation_progress: result,
translation_id: DiscourseAi::Configuration::Module::TRANSLATION_ID,
enabled: DiscourseAi::Translation.backfill_enabled?,
+ total:,
+ posts_with_detected_locale:,
}
end
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-translations.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-translations.gjs
index 69cd185be99..1dc2a2ca383 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-translations.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-translations.gjs
@@ -2,25 +2,27 @@ import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { service } from "@ember/service";
import DPageSubheader from "discourse/components/d-page-subheader";
+import DTooltip from "discourse/components/d-tooltip";
+import InterpolatedTranslation from "discourse/components/interpolated-translation";
+import icon from "discourse/helpers/d-icon";
import { i18n } from "discourse-i18n";
import AdminConfigAreaCard from "admin/components/admin-config-area-card";
import AdminConfigAreaEmptyList from "admin/components/admin-config-area-empty-list";
import Chart from "admin/components/chart";
export default class AiTranslations extends Component {
- @service siteSettings;
@service store;
+ @service languageNameLookup;
+ @service site;
@tracked data = this.args.model?.translation_progress;
+ @tracked done = this.args.model?.posts_with_detected_locale;
+ @tracked total = this.args.model?.total;
- getLanguageName(locale) {
- try {
- const availableLocales = this.siteSettings.available_locales;
- const localeObj = availableLocales.find((l) => l.value === locale);
- return localeObj ? localeObj.name : locale;
- } catch {
- return locale; // Fallback to the locale code if not found
- }
+ get descriptionKey() {
+ return this.done === this.total
+ ? "discourse_ai.translations.stats.complete_language_detection_description"
+ : "discourse_ai.translations.stats.incomplete_language_detection_description";
}
get chartConfig() {
@@ -29,62 +31,103 @@ export default class AiTranslations extends Component {
}
const chartEl = document.querySelector(".ai-translations");
- const computedStyle = getComputedStyle(chartEl);
- const colors = {
- progress: computedStyle.getPropertyValue("--chart-progress-color").trim(),
- remaining: computedStyle
- .getPropertyValue("--chart-remaining-color")
- .trim(),
- };
+ const backgroundColor = getComputedStyle(chartEl)
+ .getPropertyValue("--chart-progress-color")
+ .trim();
- const processedData = this.data.map((item) => {
+ const processedData = this.data.map(({ locale, total, done }) => {
+ const donePercentage = (total > 0 ? (done / total) * 100 : 0).toFixed(0);
return {
- locale: this.getLanguageName(item.locale),
- completionPercentage: item.completion_percentage,
- remainingPercentage: item.remaining_percentage,
+ locale: this.languageNameLookup.getLanguageName(locale),
+ done,
+ donePercentage,
+ tooltip: [
+ i18n("discourse_ai.translations.progress_chart.tooltip_translated", {
+ done,
+ total,
+ }),
+ ],
};
});
+ const chartData = {
+ labels: processedData.map(({ locale }) => locale),
+ datasets: [
+ {
+ tooltip: processedData.map(({ tooltip }) => tooltip),
+ data: processedData.map(({ donePercentage }) => donePercentage),
+ totalItems: processedData.map(({ done }) => done),
+ backgroundColor,
+ barThickness: 30,
+ borderRadius: 4,
+ },
+ ],
+ };
return {
type: "bar",
- data: {
- labels: processedData.map((item) => item.locale),
- datasets: [
- {
- label: i18n("discourse_ai.translations.progress_chart.completed"),
- data: processedData.map((item) => item.completionPercentage),
- backgroundColor: colors.progress,
- },
- {
- label: i18n("discourse_ai.translations.progress_chart.remaining"),
- data: processedData.map((item) => item.remainingPercentage),
- backgroundColor: colors.remaining,
+ data: chartData,
+ plugins: [
+ {
+ id: "barTotalText",
+ afterDraw: ({ ctx, data, scales }) => {
+ ctx.save();
+ ctx.textBaseline = "middle";
+ const items = data.datasets[0].totalItems;
+ items.forEach((done, i) => {
+ ctx.fillText(
+ i18n("discourse_ai.translations.progress_chart.bar_done", {
+ done,
+ }),
+ scales.x.getPixelForValue(100) + 10,
+ scales.y.getPixelForValue(i)
+ );
+ });
+ ctx.canvas.parentElement.style.height = `${items.length * 50 + 40}px`;
+ ctx.restore();
},
- ],
- },
+ },
+ ],
options: {
indexAxis: "y",
responsive: true,
+ maintainAspectRatio: false,
+ layout: { padding: { right: 70 } },
scales: {
x: {
- stacked: true,
beginAtZero: true,
max: 100,
+ grid: {
+ display: false,
+ },
ticks: {
- callback: (value) => `${value}%`,
+ callback: (percentage) =>
+ i18n("discourse_ai.translations.progress_chart.data_label", {
+ percentage,
+ }),
},
},
y: {
- stacked: true,
+ grid: {
+ display: false,
+ },
},
},
plugins: {
+ legend: { display: false },
tooltip: {
+ displayColors: false,
callbacks: {
- label: (context) =>
- `${context.dataset.label}: ${context.raw.toFixed(1)}%`,
+ label: ({ dataset: { tooltip }, dataIndex }) =>
+ tooltip[dataIndex],
},
},
+ datalabels: {
+ formatter: (percentage) =>
+ i18n("discourse_ai.translations.progress_chart.data_label", {
+ percentage,
+ }),
+ color: "white",
+ },
},
},
};
@@ -120,9 +163,35 @@ export default class AiTranslations extends Component {
@heading="discourse_ai.translations.progress_chart.title"
>
<:content>
+ <div class="ai-translation__stats-container">
+ <div class="ai-translation__stat-item">
+ <span class="ai-translation__stat-label">
+ <InterpolatedTranslation
+ @key={{this.descriptionKey}}
+ as |Placeholder|
+ >
+ <Placeholder @name="tooltip">
+ <DTooltip>
+ <:trigger>
+ {{icon "circle-question"}}
+ </:trigger>
+ <:content>
+ {{i18n
+ "discourse_ai.translations.stats.description_tooltip"
+ }}
+ </:content>
+ </DTooltip>
+ </Placeholder>
+ <Placeholder @name="done">{{this.done}}</Placeholder>
+ <Placeholder @name="total">{{this.total}}</Placeholder>
+ </InterpolatedTranslation>
+ </span>
+ </div>
+ </div>
<div class="ai-translation__chart-container">
<Chart
@chartConfig={{this.chartConfig}}
+ @loadChartDataLabelsPlugin={{true}}
class="ai-translation__chart"
/>
</div>
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 93fbe951c4e..4f62716a98f 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -324,10 +324,16 @@ en:
disabled_state:
configure: "Configure translations"
empty_label: "Automatic translations are disabled, click below to configure"
+ stats:
+ title: "Translation statistics"
+ complete_language_detection_description: "All %{total} eligible posts have their language detected %{tooltip}"
+ incomplete_language_detection_description: "%{done} of %{total} eligible posts have their language detected %{tooltip}"
+ description_tooltip: "Eligible posts are determined by AI translation settings"
progress_chart:
- title: "Translation progress"
- completed: "Completed"
- remaining: "Remaining"
+ title: "Translation Progress"
+ data_label: "%{percentage}%"
+ tooltip_translated: "%{done} out of %{total} posts translated"
+ bar_done: "%{done} posts"
spam:
diff --git a/plugins/discourse-ai/lib/translation/base_candidates.rb b/plugins/discourse-ai/lib/translation/base_candidates.rb
index 363fa429d3e..e6461c14c47 100644
--- a/plugins/discourse-ai/lib/translation/base_candidates.rb
+++ b/plugins/discourse-ai/lib/translation/base_candidates.rb
@@ -3,21 +3,29 @@
module DiscourseAi
module Translation
class BaseCandidates
- COMPLETION_CACHE_TTL = 1.hour
+ CACHE_TTL = 1.hour
- # ModelType that are eligible for translation based on site settings
- # @return [ActiveRecord::Relation] the ActiveRecord relation of the candidates
- def self.get
- raise NotImplementedError
+ # Returns the total number of candidates and the number of candidates that have a detected locale.
+ # The values are cached and provides an overview of how many posts are eligible for translation and how many have been detected with a locale.
+ # @return [Hash] a hash with keys :total and :posts_with_detected_locale
+ def self.get_total_and_with_locale_count
+ Discourse
+ .cache
+ .fetch(get_total_cache_key, expires_in: CACHE_TTL) do
+ total, with_locale = total_and_with_locale_count
+ return { total: 0, posts_with_detected_locale: 0 } if total.zero?
+ { total:, posts_with_detected_locale: with_locale }
+ end
end
- # The completion in float percentage for the given locale
+ # Returns the number of posts that have been translated, and the total number of posts that need translation for a given locale.
+ # The total number of posts is based off candidates that already have a locale.
# @param locale [String] the locale for which to calculate the completion percentage
- # @return [Float] the completion percentage for the given locale e.g. 0.75 for 75%
+ # @return [Hash] a hash with keys :done and :total
def self.get_completion_per_locale(locale)
Discourse
.cache
- .fetch(get_completion_cache_key(locale), expires_in: COMPLETION_CACHE_TTL) do
+ .fetch(get_completion_cache_key(locale), expires_in: CACHE_TTL) do
done, total = calculate_completion_per_locale(locale)
return { done: 0, total: 0 } if total.zero?
{ done:, total: }
@@ -30,11 +38,17 @@ module DiscourseAi
private
+ # ModelType that are eligible for translation based on site settings
+ # @return [ActiveRecord::Relation] the ActiveRecord relation of the candidates
+ def self.get
+ raise NotImplementedError
+ end
+
# This method should return [completed_translations, total_needed_translations]
#
# This allows flexibility for the implementation to determine how the completion percentage is calculated.
# # @param locale [String] the locale for which to calculate the completion percentage
- # @return [integer, integer]
+ # @return [integer, integer] the number of done and total translations for the given locale
def self.calculate_completion_per_locale(locale)
raise NotImplementedError
end
@@ -43,8 +57,34 @@ module DiscourseAi
raise NotImplementedError
end
+ def self.total_cache_key_for_type
+ raise NotImplementedError
+ end
+
def self.get_completion_cache_key(locale)
- "#{completion_cache_key_for_type}_#{locale}"
+ "#{cache_key_for_type}_completion_#{locale}"
+ end
+
+ def self.get_total_cache_key
+ "#{cache_key_for_type}_total"
+ end
+
+ def self.total_and_with_locale_count
+ DB.query_single(<<~SQL)
+ WITH eligible_posts AS (
+ #{get.to_sql}
+ ),
+ total_count AS (
+ SELECT COUNT(*) AS count FROM eligible_posts
+ ),
+ done_count AS (
+ SELECT COUNT(DISTINCT p.id)
+ FROM eligible_posts p
+ WHERE p.locale IS NOT NULL
+ )
+ SELECT t.count AS total, d.count AS done
+ FROM total_count t, done_count d
+ SQL
end
end
end
diff --git a/plugins/discourse-ai/lib/translation/category_candidates.rb b/plugins/discourse-ai/lib/translation/category_candidates.rb
index b0196f0692f..03d50aad82b 100644
--- a/plugins/discourse-ai/lib/translation/category_candidates.rb
+++ b/plugins/discourse-ai/lib/translation/category_candidates.rb
@@ -3,6 +3,10 @@
module DiscourseAi
module Translation
class CategoryCandidates < BaseCandidates
+ private
+
+ # all categories that are eligible for translation based on site settings,
+ # including those without locale detected yet.
def self.get
categories = Category.all
if SiteSetting.ai_translation_backfill_limit_to_public_content
@@ -11,13 +15,11 @@ module DiscourseAi
categories
end
- private
-
def self.calculate_completion_per_locale(locale)
base_locale = "#{locale.split("_").first}%"
sql = <<~SQL
WITH eligible_categories AS (
- #{get.to_sql}
+ #{get.where("categories.locale IS NOT NULL").to_sql}
),
total_count AS (
SELECT COUNT(*) AS count FROM eligible_categories
@@ -32,10 +34,10 @@ module DiscourseAi
FROM total_count t, done_count d
SQL
- DB.query_single(sql, base_locale: "#{base_locale}%")
+ DB.query_single(sql, base_locale:)
end
- def self.completion_cache_key_for_type
+ def self.cache_key_for_type
"discourse_ai::translation::category_candidates"
end
end
diff --git a/plugins/discourse-ai/lib/translation/post_candidates.rb b/plugins/discourse-ai/lib/translation/post_candidates.rb
index 855dd6125e5..88fe00dd536 100644
--- a/plugins/discourse-ai/lib/translation/post_candidates.rb
+++ b/plugins/discourse-ai/lib/translation/post_candidates.rb
@@ -3,7 +3,10 @@
module DiscourseAi
module Translation
class PostCandidates < BaseCandidates
- # Posts that are eligible for translation based on site settings
+ private
+
+ # all posts that are eligible for translation based on site settings,
+ # including those without locale detected yet.
def self.get
posts =
Post
@@ -33,14 +36,12 @@ module DiscourseAi
end
end
- private
-
def self.calculate_completion_per_locale(locale)
base_locale = "#{locale.split("_").first}%"
sql = <<~SQL
WITH eligible_posts AS (
- #{get.to_sql}
+ #{get.where("posts.locale IS NOT NULL").to_sql}
),
total_count AS (
SELECT COUNT(*) AS count FROM eligible_posts
@@ -55,10 +56,10 @@ module DiscourseAi
FROM total_count t, done_count d
SQL
- DB.query_single(sql, base_locale: "#{base_locale}%")
+ DB.query_single(sql, base_locale:)
end
- def self.completion_cache_key_for_type
+ def self.cache_key_for_type
"discourse_ai::translation::post_candidates"
end
end
diff --git a/plugins/discourse-ai/lib/translation/topic_candidates.rb b/plugins/discourse-ai/lib/translation/topic_candidates.rb
index 52c8ac2eb1e..68a68868d41 100644
--- a/plugins/discourse-ai/lib/translation/topic_candidates.rb
+++ b/plugins/discourse-ai/lib/translation/topic_candidates.rb
@@ -3,6 +3,10 @@
module DiscourseAi
module Translation
class TopicCandidates < BaseCandidates
+ private
+
+ # all topics that are eligible for translation based on site settings,
+ # including those without locale detected yet.
def self.get
topics =
Topic
@@ -30,14 +34,12 @@ module DiscourseAi
end
end
- private
-
def self.calculate_completion_per_locale(locale)
- base_locale = locale.split("_").first
+ base_locale = "#{locale.split("_").first}%"
sql = <<~SQL
WITH eligible_topics AS (
- #{get.to_sql}
+ #{get.where("topics.locale IS NOT NULL").to_sql}
),
total_count AS (
SELECT COUNT(*) AS count FROM eligible_topics
@@ -52,10 +54,10 @@ module DiscourseAi
FROM total_count t, done_count d
SQL
- DB.query_single(sql, base_locale: "#{base_locale}%")
+ DB.query_single(sql, base_locale:)
end
- def self.completion_cache_key_for_type
+ def self.cache_key_for_type
"discourse_ai::translation::topic_candidates"
end
end
diff --git a/plugins/discourse-ai/spec/lib/translation/category_candidates_spec.rb b/plugins/discourse-ai/spec/lib/translation/category_candidates_spec.rb
index 935a45f1e24..edd92ff11f1 100644
--- a/plugins/discourse-ai/spec/lib/translation/category_candidates_spec.rb
+++ b/plugins/discourse-ai/spec/lib/translation/category_candidates_spec.rb
@@ -18,12 +18,12 @@ describe DiscourseAi::Translation::CategoryCandidates do
end
describe ".get_completion_per_locale" do
- context "when (scenario A) percentage determined by category's locale" do
+ context "when (scenario A) completion determined by category's locale" do
it "returns done = total if all categories are in the locale" do
locale = "pt_BR"
Fabricate(:category, locale:)
Category.update_all(locale: locale)
- Fabricate(:category, locale: "pt")
+ Fabricate(:category, locale: "pt") # pt counts as pt_BR
completion = DiscourseAi::Translation::CategoryCandidates.get_completion_per_locale(locale)
expect(completion).to eq({ done: Category.count, total: Category.count })
@@ -31,20 +31,26 @@ describe DiscourseAi::Translation::CategoryCandidates do
it "returns correct done and total if some categories are in the locale" do
locale = "pt_BR"
+ Category.update_all(locale: "ar") # not portuguese
+
Fabricate(:category, locale:)
- Fabricate(:category, locale: "not_pt")
+ Fabricate(:category, locale: "ar") # not portuguese
completion = DiscourseAi::Translation::CategoryCandidates.get_completion_per_locale(locale)
expect(completion).to eq({ done: 1, total: Category.count })
end
end
- context "when (scenario B) percentage determined by category localizations" do
+ context "when (scenario B) completion determined by category localizations" do
it "returns done = total if all categories have a localization in the locale" do
locale = "pt_BR"
- Fabricate(:category)
- Category.all.each { |category| Fabricate(:category_localization, category:, locale:) }
- Fabricate(:category_localization, locale: "pt")
+
+ Fabricate(:category, locale: "en")
+ Category.all.each do |category|
+ category.update(locale: "en")
+ Fabricate(:category_localization, category:, locale:)
+ end
+ CategoryLocalization.order("RANDOM()").first.update(locale: "pt") # pt counts as pt_BR
completion = DiscourseAi::Translation::CategoryCandidates.get_completion_per_locale(locale)
expect(completion).to eq({ done: Category.count, total: Category.count })
@@ -52,29 +58,34 @@ describe DiscourseAi::Translation::CategoryCandidates do
it "returns correct done and total if some categories have a localization in the locale" do
locale = "es"
- Fabricate(:category_localization, locale:)
- Fabricate(:category_localization, locale: "pt")
+ category1 = Fabricate(:category, locale: "en")
+ category2 = Fabricate(:category, locale: "fr")
+ Fabricate(:category_localization, category: category1, locale:)
+ Fabricate(:category_localization, category: category2, locale: "ar") # not the target locale
completion = DiscourseAi::Translation::CategoryCandidates.get_completion_per_locale(locale)
- expect(completion).to eq({ done: 1, total: Category.count })
+ categories_with_locale = Category.where.not(locale: nil).count
+ expect(completion).to eq({ done: 1, total: categories_with_locale })
end
end
it "returns the correct done and total based on (scenario A & B) `category.locale` and `CategoryLocalization` in the specified locale" do
locale = "pt_BR"
+ Category.update_all(locale: "en")
+
# translated candidates
Fabricate(:category, locale:)
- category2 = Fabricate(:category)
+ category2 = Fabricate(:category, locale: "en")
Fabricate(:category_localization, category: category2, locale:)
# untranslated candidate
- category3 = Fabricate(:category)
+ category3 = Fabricate(:category, locale: "fr")
Fabricate(:category_localization, category: category3, locale: "zh_CN")
# not a candidate as it is read restricted
SiteSetting.ai_translation_backfill_limit_to_public_content = true
- category4 = Fabricate(:category, read_restricted: true)
+ category4 = Fabricate(:category, read_restricted: true, locale: "de")
Fabricate(:category_localization, category: category4, locale:)
completion = DiscourseAi::Translation::CategoryCandidates.get_completion_per_locale(locale)
@@ -93,7 +104,7 @@ describe DiscourseAi::Translation::CategoryCandidates do
expect(completion).to eq({ done: Category.count, total: Category.count })
end
- it "returns nil - nil for done and total when there are no categories" do
+ it "returns nil - nil for done and total when no categories are present" do
SiteSetting.ai_translation_backfill_limit_to_public_content = false
Category.destroy_all
diff --git a/plugins/discourse-ai/spec/lib/translation/post_candidates_spec.rb b/plugins/discourse-ai/spec/lib/translation/post_candidates_spec.rb
index 3f8682474bb..906a5ad7622 100644
--- a/plugins/discourse-ai/spec/lib/translation/post_candidates_spec.rb
+++ b/plugins/discourse-ai/spec/lib/translation/post_candidates_spec.rb
@@ -84,9 +84,12 @@ describe DiscourseAi::Translation::PostCandidates do
context "when (scenario B) 'done' determined by post localizations" do
it "returns done = total if all posts have a localization in the locale" do
locale = "pt_BR"
- Fabricate(:post)
- Post.all.each { |post| Fabricate(:post_localization, post:, locale:) }
- Fabricate(:post_localization, locale: "pt")
+ Fabricate(:post, locale: "en")
+ Post.all.each do |post|
+ post.update(locale: "en")
+ Fabricate(:post_localization, post:, locale:)
+ end
+ PostLocalization.order("RANDOM()").first.update(locale: "pt")
completion = DiscourseAi::Translation::PostCandidates.get_completion_per_locale(locale)
expect(completion).to eq({ done: Post.count, total: Post.count })
@@ -94,11 +97,14 @@ describe DiscourseAi::Translation::PostCandidates do
it "returns correct done and total if some posts have a localization in the locale" do
locale = "es"
- Fabricate(:post_localization, locale:)
- Fabricate(:post_localization, locale: "not_es")
+ post1 = Fabricate(:post, locale: "en")
+ post2 = Fabricate(:post, locale: "fr")
+ Fabricate(:post_localization, post: post1, locale:)
+ Fabricate(:post_localization, post: post2, locale: "not_es")
completion = DiscourseAi::Translation::PostCandidates.get_completion_per_locale(locale)
- expect(completion).to eq({ done: 1, total: Post.count })
+ posts_with_locale = Post.where.not(locale: nil).count
+ expect(completion).to eq({ done: 1, total: posts_with_locale })
end
end
@@ -107,15 +113,15 @@ describe DiscourseAi::Translation::PostCandidates do
# translated candidates
Fabricate(:post, locale:)
- post2 = Fabricate(:post)
+ post2 = Fabricate(:post, locale: "en")
Fabricate(:post_localization, post: post2, locale:)
# untranslated candidate
- post4 = Fabricate(:post)
+ post4 = Fabricate(:post, locale: "fr")
Fabricate(:post_localization, post: post4, locale: "zh_CN")
# not a candidate as it is a bot post
- post3 = Fabricate(:post, user: Discourse.system_user)
+ post3 = Fabricate(:post, user: Discourse.system_user, locale: "de")
Fabricate(:post_localization, post: post3, locale:)
completion = DiscourseAi::Translation::PostCandidates.get_completion_per_locale(locale)
diff --git a/plugins/discourse-ai/spec/lib/translation/topic_candidates_spec.rb b/plugins/discourse-ai/spec/lib/translation/topic_candidates_spec.rb
index b7bddde5603..b47dc5f629f 100644
--- a/plugins/discourse-ai/spec/lib/translation/topic_candidates_spec.rb
+++ b/plugins/discourse-ai/spec/lib/translation/topic_candidates_spec.rb
@@ -74,11 +74,14 @@ describe DiscourseAi::Translation::TopicCandidates do
end
context "when (scenario B) 'done' determined by topic localizations" do
- it "returns 100% completion if all topics have a localization in the locale" do
+ it "returns done = total if all topics have a localization in the locale" do
locale = "pt_BR"
- Fabricate(:topic)
- Topic.all.each { |topic| Fabricate(:topic_localization, topic:, locale:) }
- Fabricate(:topic_localization, locale: "pt")
+ Fabricate(:topic, locale: "en")
+ Topic.all.each do |topic|
+ topic.update(locale: "en")
+ Fabricate(:topic_localization, topic:, locale:)
+ end
+ TopicLocalization.order("RANDOM()").first.update(locale: "pt")
completion = DiscourseAi::Translation::TopicCandidates.get_completion_per_locale(locale)
expect(completion).to eq({ done: Topic.count, total: Topic.count })
@@ -86,11 +89,14 @@ describe DiscourseAi::Translation::TopicCandidates do
it "returns correct done and total if some topics have a localization in the locale" do
locale = "es"
- Fabricate(:topic_localization, locale:)
- Fabricate(:topic_localization, locale: "not_es")
+ topic1 = Fabricate(:topic, locale: "en")
+ topic2 = Fabricate(:topic, locale: "fr")
+ Fabricate(:topic_localization, topic: topic1, locale:)
+ Fabricate(:topic_localization, topic: topic2, locale: "not_es")
completion = DiscourseAi::Translation::TopicCandidates.get_completion_per_locale(locale)
- expect(completion).to eq({ done: 1, total: Topic.count })
+ topics_with_locale = Topic.where.not(locale: nil).count
+ expect(completion).to eq({ done: 1, total: topics_with_locale })
end
end
@@ -99,21 +105,21 @@ describe DiscourseAi::Translation::TopicCandidates do
# translated candidates
Fabricate(:topic, locale:)
- topic2 = Fabricate(:topic)
+ topic2 = Fabricate(:topic, locale: "en")
Fabricate(:topic_localization, topic: topic2, locale:)
# untranslated candidate
- topic4 = Fabricate(:topic)
+ topic4 = Fabricate(:topic, locale: "fr")
Fabricate(:topic_localization, topic: topic4, locale: "zh_CN")
# not a candidate as it is a bot topic
- topic3 = Fabricate(:topic, user: Discourse.system_user)
+ topic3 = Fabricate(:topic, user: Discourse.system_user, locale: "de")
Fabricate(:topic_localization, topic: topic3, locale:)
completion = DiscourseAi::Translation::TopicCandidates.get_completion_per_locale(locale)
translated_candidates = 2 # topic1 + topic2
total_candidates = Topic.count - 1 # excluding the bot topic
- expect(completion).to eq({ done: 2, total: 3 })
+ expect(completion).to eq({ done: translated_candidates, total: total_candidates })
end
it "does not allow done to exceed total when topic.locale and topic_localization both exist" do
@@ -125,9 +131,8 @@ describe DiscourseAi::Translation::TopicCandidates do
expect(completion).to eq({ done: 1, total: 1 })
end
- it "returns nil - nil for done and total if no topics" do
+ it "returns nil - nil for done and total when no topics are present" do
SiteSetting.ai_translation_backfill_max_age_days = 0
- SiteSetting.ai_translation_backfill_limit_to_public_content = false
completion = DiscourseAi::Translation::TopicCandidates.get_completion_per_locale("es")
expect(completion).to eq({ done: 0, total: 0 })
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_translations_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_translations_controller_spec.rb
index cc5ab239b0b..00fe7f4c62c 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_translations_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_translations_controller_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-RSpec.describe DiscourseAi::Admin::AiTranslationsController do
+describe DiscourseAi::Admin::AiTranslationsController do
fab!(:admin)
fab!(:user)
@@ -19,10 +19,9 @@ RSpec.describe DiscourseAi::Admin::AiTranslationsController do
end
it "returns translation progress data" do
- # Mock the translation candidate methods
- allow(DiscourseAi::Translation::PostCandidates).to receive(
- :get_completion_per_locale,
- ).and_return({ total: 100, done: 50 })
+ Fabricate.times(14, :post, locale: "en")
+ Fabricate.times(1, :post, locale: "fr")
+ Fabricate.times(4, :post)
get "/admin/plugins/discourse-ai/ai-translations.json"
@@ -30,18 +29,20 @@ RSpec.describe DiscourseAi::Admin::AiTranslationsController do
json = response.parsed_body
expect(json["translation_progress"]).to be_an(Array)
- expect(json["translation_progress"].length).to eq(3) # en, fr, es
+ expect(json["translation_progress"].length).to eq(3)
expect(json["translation_id"]).to eq(DiscourseAi::Configuration::Module::TRANSLATION_ID)
expect(json["enabled"]).to be_in([true, false])
+ expect(json["total"]).to eq(19)
+ expect(json["posts_with_detected_locale"]).to eq(15)
# Check structure of first locale data
locale_data = json["translation_progress"].first
- expect(locale_data["locale"]).to be_present
- expect(locale_data["completion_percentage"]).to be_present
- expect(locale_data["remaining_percentage"]).to be_present
+ expect(locale_data["locale"]).to eq("en")
+ expect(locale_data["total"]).to eq(15)
+ expect(locale_data["done"]).to eq(14)
end
- it "returns empty array when no locales are supported" do
+ it "returns empty when no locales are supported" do
SiteSetting.content_localization_supported_locales = ""
get "/admin/plugins/discourse-ai/ai-translations.json"
@@ -50,6 +51,8 @@ RSpec.describe DiscourseAi::Admin::AiTranslationsController do
json = response.parsed_body
expect(json["translation_progress"]).to eq([])
+ expect(json["total"]).to eq(0)
+ expect(json["posts_with_detected_locale"]).to eq(0)
end
it "correctly indicates if backfill is enabled" do