The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add support for content translations for auth embeds (#67730)
Timofey Kachalovaa5a35f94c1d
diff --git a/e2e/test-component/scenarios/embedding-sdk/content-translations.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/content-translations.cy.spec.tsxnew file mode 100644index 00000000000..2d919781bc1--- /dev/null+++ b/e2e/test-component/scenarios/embedding-sdk/content-translations.cy.spec.tsx@@ -0,0 +1,78 @@+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { createQuestion } from "e2e/support/helpers";+import { uploadTranslationDictionaryViaAPI } from "e2e/support/helpers/e2e-content-translation-helpers";+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";+import { mountInteractiveQuestion } from "e2e/support/helpers/embedding-sdk-component-testing";+import {+ mockAuthProviderAndJwtSignIn,+ signInAsAdminAndEnableEmbeddingSdk,+} from "e2e/support/helpers/embedding-sdk-testing";+import type { Card } from "metabase-types/api";++const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;++describe("scenarios > embedding-sdk > content-translations", () => {+ describe("question", () => {+ const setup = ({ display }: { display?: Card["display"] } = {}) => {+ signInAsAdminAndEnableEmbeddingSdk();++ createQuestion({+ name: "Question Embed SDK",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],+ breakout: [["field", ORDERS.PRODUCT_ID, null]],+ limit: 2,+ },+ display,+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });++ cy.signOut();+ };++ describe("content translation", () => {+ it("should show question content with applied content translation", () => {+ setup();++ cy.signInAsAdmin();++ uploadTranslationDictionaryViaAPI([+ {+ locale: "de",+ msgid: "Question Embed SDK",+ msgstr: "Override title für Deutsch",+ },+ {+ locale: "de",+ msgid: "Product ID",+ msgstr: "Override Product ID für Deutsch",+ },+ ]);++ cy.signOut();++ mockAuthProviderAndJwtSignIn();++ cy.get("@questionId").then(async () => {+ mountInteractiveQuestion(+ { title: true },+ {+ sdkProviderProps: {+ locale: "de",+ },+ },+ );++ getSdkRoot().within(() => {+ cy.findByText("Override title für Deutsch").should("be.visible");+ cy.findByText("Override Product ID für Deutsch").should(+ "be.visible",+ );+ });+ });+ });+ });+ });+});diff --git a/enterprise/backend/src/metabase_enterprise/content_translation/routes.clj b/enterprise/backend/src/metabase_enterprise/content_translation/routes.cljindex 8d8ccdbfc67..6bb4c434a25 100644--- a/enterprise/backend/src/metabase_enterprise/content_translation/routes.clj+++ b/enterprise/backend/src/metabase_enterprise/content_translation/routes.clj@@ -26,6 +26,16 @@{:locale "ja" :msgid "Sample translation" :msgstr "サンプル翻訳"}{:locale "ko" :msgid "Sample translation" :msgstr "샘플 번역"}])+(def ^:private Translation+ [:map+ [:locale ms/NonBlankString]+ [:msgid ms/NonBlankString]+ [:msgstr :string]])++(def ^:private DictionaryResponse+ [:map+ [:data [:sequential Translation]]])+;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen;;@@ -92,6 +102,13 @@{:data (ct/get-translations (i18n/normalized-locale-string (str/trim locale)))}(throw (ex-info (str (tru "Locale is required.")) {:status-code 400}))))+(api.macros/defendpoint :get "/dictionary" :- DictionaryResponse+ "Fetch the content translation dictionary for authenticated users (auth-based embedding flows)."+ [_route-params+ {:keys [locale]} :- [:map [:locale :string]]]+ (api/check api/*current-user-id* 401 "Unauthenticated")+ {:data (ct/get-translations (i18n/normalized-locale-string (str/trim locale)))})+(defn- +require-content-translation [handler](ee.api/+require-premium-feature :content-translation (deferred-tru "Content translation") handler))diff --git a/enterprise/backend/test/metabase_enterprise/content_translation/routes_test.clj b/enterprise/backend/test/metabase_enterprise/content_translation/routes_test.cljindex ab3bb4a0637..cce491fff57 100644--- a/enterprise/backend/test/metabase_enterprise/content_translation/routes_test.clj+++ b/enterprise/backend/test/metabase_enterprise/content_translation/routes_test.clj@@ -176,3 +176,31 @@(client/client :get 400 (str (embedded-dictionary-url(jwt/sign {} (random-embedding-secret-key)))"?locale=sv")))))))))))++(deftest authenticated-dictionary-test+ (testing "GET /api/ee/content-translation/dictionary"+ (ct-utils/with-clean-translations!+ (mt/with-premium-features #{:content-translation}+ (testing "requires authentication"+ (is (= "Unauthenticated"+ (client/client :get 401 "ee/content-translation/dictionary?locale=sv"))))+ (testing "requires locale parameter"+ (is (=? {:errors {:locale some?}}+ (mt/user-http-request :rasta :get 400 "ee/content-translation/dictionary"))))+ (testing "returns translations for authenticated user"+ (mt/with-temp [:model/ContentTranslation _ {:locale "sv" :msgid "blueberry" :msgstr "blåbär"}]+ (is (=? {:data [{:locale "sv"+ :msgid "blueberry"+ :msgstr "blåbär"}]}+ (mt/user-http-request :rasta :get 200 "ee/content-translation/dictionary?locale=sv")))))+ (testing "normalizes locale"+ (mt/with-temp [:model/ContentTranslation _ {:locale "pt_BR" :msgid "blueberry" :msgstr "mirtilo"}]+ (is (=? {:data [{:locale "pt_BR"+ :msgid "blueberry"+ :msgstr "mirtilo"}]}+ (mt/user-http-request :rasta :get 200 "ee/content-translation/dictionary?locale=pt-BR")))))))+ (testing "requires content-translation feature"+ (mt/with-premium-features #{}+ (mt/assert-has-premium-feature-error+ "Content translation"+ (mt/user-http-request :rasta :get 402 "ee/content-translation/dictionary?locale=sv"))))))diff --git a/enterprise/frontend/src/metabase-enterprise/content_translation/index.ts b/enterprise/frontend/src/metabase-enterprise/content_translation/index.tsindex f3bfcf51ef7..cf13bf61a33 100644--- a/enterprise/frontend/src/metabase-enterprise/content_translation/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/content_translation/index.ts@@ -25,6 +25,13 @@ export function initializePlugin() {useTranslateFieldValuesInHoveredObject,useTranslateSeries,getDictionaryBasePath,+ setEndpointsForAuthEmbedding: () => {+ if (contentTranslationEndpoints.getDictionary) {+ return;+ }++ contentTranslationEndpoints.getDictionary = getDictionaryBasePath;+ },setEndpointsForStaticEmbedding: (encodedToken: string) => {if (contentTranslationEndpoints.getDictionary) {return;diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsxindex d4bc918410a..720985311c5 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx@@ -4,6 +4,7 @@ import { t } from "ttag";import { SdkError } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { useExtractResourceIdFromJwtToken } from "embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token";import { useLoadQuestion } from "embedding-sdk-bundle/hooks/private/use-load-question";+import { useSetupContentTranslations } from "embedding-sdk-bundle/hooks/private/use-setup-content-translations";import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";import {getError,@@ -14,7 +15,6 @@ import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";import { EmbeddingEntityContextProvider } from "metabase/embedding/context";import { transformSdkQuestion } from "metabase/embedding-sdk/lib/transform-question";import type { MetabasePluginsConfig as InternalMetabasePluginsConfig } from "metabase/embedding-sdk/types/plugins";-import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";import {type OnCreateOptions,useCreateQuestion,@@ -75,11 +75,7 @@ export const SdkQuestionProvider = ({token: rawToken ?? undefined,});- useEffect(() => {- if (isGuestEmbed && token) {- PLUGIN_CONTENT_TRANSLATION.setEndpointsForStaticEmbedding(token);- }- }, [isGuestEmbed, token]);+ useSetupContentTranslations({ token });const isNewQuestion = questionId === "new";diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsxindex 99e0540fc48..93508e3a8fd 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx@@ -25,6 +25,7 @@ import {type SdkDashboardDisplayProps,useSdkDashboardParams,} from "embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params";+import { useSetupContentTranslations } from "embedding-sdk-bundle/hooks/private/use-setup-content-translations";import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";import type { MetabaseQuestion } from "embedding-sdk-bundle/types";@@ -54,7 +55,6 @@ import { EmbeddingEntityContextProvider } from "metabase/embedding/context";import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";import { isStaticEmbeddingEntityLoadingError } from "metabase/lib/errors/is-static-embedding-entity-loading-error";import { useSelector } from "metabase/lib/redux";-import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";import EmbedFrameS from "metabase/public/components/EmbedFrame/EmbedFrame.module.css";import { resetErrorPage, setErrorPage } from "metabase/redux/app";import { dismissAllUndo } from "metabase/redux/undo";@@ -193,11 +193,7 @@ const SdkDashboardInner = ({token: rawToken ?? undefined,});- useEffect(() => {- if (isGuestEmbed && token) {- PLUGIN_CONTENT_TRANSLATION.setEndpointsForStaticEmbedding(token);- }- }, [isGuestEmbed, token]);+ useSetupContentTranslations({ token });const { handleLoad, handleLoadWithoutCards } = useDashboardLoadHandlers({onLoad,diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-setup-content-translations.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-setup-content-translations.tsnew file mode 100644index 00000000000..26d8925bb01--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-setup-content-translations.ts@@ -0,0 +1,26 @@+import { useEffect } from "react";++import { useSdkSelector } from "embedding-sdk-bundle/store";+import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";+import type { SdkEntityToken } from "embedding-sdk-bundle/types";+import { useLocale } from "metabase/common/hooks";+import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";++export const useSetupContentTranslations = ({+ token,+}: {+ token: SdkEntityToken | null;+}) => {+ const { locale } = useLocale();+ const isGuestEmbed = useSdkSelector(getIsGuestEmbed);++ useEffect(() => {+ if (locale !== "en") {+ if (isGuestEmbed && token) {+ PLUGIN_CONTENT_TRANSLATION.setEndpointsForStaticEmbedding(token);+ } else {+ PLUGIN_CONTENT_TRANSLATION.setEndpointsForAuthEmbedding();+ }+ }+ }, [isGuestEmbed, locale, token]);+};diff --git a/frontend/src/metabase/plugins/oss/content-translation.ts b/frontend/src/metabase/plugins/oss/content-translation.tsindex 4ded161c864..a103081b5fe 100644--- a/frontend/src/metabase/plugins/oss/content-translation.ts+++ b/frontend/src/metabase/plugins/oss/content-translation.ts@@ -9,6 +9,7 @@ import type { EntityToken } from "metabase-types/api/entity";const getDefaultPluginContentTranslation = () => ({isEnabled: false,getDictionaryBasePath: null as string | null,+ setEndpointsForAuthEmbedding: () => {},setEndpointsForStaticEmbedding: (_encodedToken: EntityToken) => {},ContentTranslationConfiguration: PluginPlaceholder,useTranslateContent: <